@stll/docx-core 0.27.0 → 0.28.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.
@@ -0,0 +1,2683 @@
1
+ import "../document-Bz9rYlJI.js";
2
+ import { r as hasIllegalXmlCharacters } from "../xmlEscape-T-2DeGlS.js";
3
+ import { Result, TaggedError, panic } from "better-result";
4
+ //#region src/ops/equality.ts
5
+ const NOTHING = /* @__PURE__ */ new Set();
6
+ const equal = (left, right, skipped) => {
7
+ if (Object.is(left, right)) return true;
8
+ if (typeof left !== "object" || typeof right !== "object" || left === null || right === null) return false;
9
+ if (Array.isArray(left) || Array.isArray(right)) {
10
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;
11
+ return left.every((item, index) => equal(item, right[index], skipped));
12
+ }
13
+ const fields = (record) => {
14
+ const entries = Object.entries(record);
15
+ const skip = skipped(entries);
16
+ return entries.filter(([key, value]) => value !== void 0 && !skip.has(key));
17
+ };
18
+ const leftEntries = fields(left);
19
+ const rightEntries = new Map(fields(right));
20
+ if (leftEntries.length !== rightEntries.size) return false;
21
+ return leftEntries.every(([key, value]) => rightEntries.has(key) && equal(value, rightEntries.get(key), skipped));
22
+ };
23
+ const structurallyEqual = (left, right) => equal(left, right, () => NOTHING);
24
+ /**
25
+ * Paragraph fields a layout or numbering pass recomputes. They describe the
26
+ * content rather than being it, so they never make an operation's
27
+ * precondition stale.
28
+ */
29
+ const DERIVED_PARAGRAPH_FIELDS = /* @__PURE__ */ new Set(["listRendering", "renderedPageBreakBefore"]);
30
+ const derivedFields = (entries) => entries.some(([key, value]) => key === "type" && value === "paragraph") ? DERIVED_PARAGRAPH_FIELDS : NOTHING;
31
+ /**
32
+ * The equality an operation's precondition is checked under: structural,
33
+ * with the fields a relayout or renumbering recomputes left out. An undo is
34
+ * refused as stale when the content it expects has changed, never because
35
+ * numbering or pagination was recomputed since.
36
+ */
37
+ const equalForStaleness = (left, right) => equal(left, right, derivedFields);
38
+ //#endregion
39
+ //#region src/ops/types.ts
40
+ /** The operation schema this module reads and writes. */
41
+ const DOCUMENT_OP_SCHEMA_VERSION = 1;
42
+ /**
43
+ * The stories an operation can address. Headers, footers, notes and comment
44
+ * bodies are stories too; version 1 addresses the main story only.
45
+ */
46
+ const OP_STORIES = Object.freeze({ MAIN: "main" });
47
+ /**
48
+ * What a property set a patch leaves without keys becomes: absent, or an
49
+ * empty set. The two state the same thing; the choice is how an inverse
50
+ * gives back a record in the spelling it had.
51
+ */
52
+ const EMPTY_PROPERTY_SETS = Object.freeze({
53
+ OMIT: "omit",
54
+ KEEP: "keep"
55
+ });
56
+ /**
57
+ * Inserted text takes the properties of the run it joins: the run holding the
58
+ * unit before the position, or the one after it at the start of a paragraph.
59
+ */
60
+ const INHERIT_RUN_PROPS = "inherit";
61
+ /** The operation kinds of schema version 1. */
62
+ const DOCUMENT_OP_TYPES = Object.freeze({
63
+ INSERT_TEXT: "insertText",
64
+ INSERT_CONTENT: "insertContent",
65
+ DELETE_RANGE: "deleteRange",
66
+ SPLIT_INLINE: "splitInline",
67
+ JOIN_INLINE: "joinInline",
68
+ SET_RUN_PROPS: "setRunProps",
69
+ SET_PARAGRAPH_PROPS: "setParagraphProps",
70
+ SPLIT_BLOCK: "splitBlock",
71
+ JOIN_BLOCKS: "joinBlocks",
72
+ REPLACE_BLOCKS: "replaceBlocks"
73
+ });
74
+ /** An operation in the envelope it is journaled and sent in. */
75
+ const toOpEnvelope = (op) => ({
76
+ schema: 1,
77
+ op
78
+ });
79
+ //#endregion
80
+ //#region src/ops/blocks.ts
81
+ /**
82
+ * Finding and replacing paragraphs in a story.
83
+ *
84
+ * A story is a tree of block lists: the body, each table cell and each block
85
+ * content control holds one. A paragraph is found by its `w14:paraId`
86
+ * wherever it sits in that tree, and a replacement rebuilds only the records
87
+ * on the path to it, so every other block is `===` to its input.
88
+ */
89
+ const collectParagraphs = (blocks, list, out) => {
90
+ for (const [index, block] of blocks.entries()) switch (block.type) {
91
+ case "paragraph":
92
+ out.push({
93
+ list,
94
+ index,
95
+ paragraph: block
96
+ });
97
+ break;
98
+ case "table":
99
+ for (const [row, tableRow] of block.rows.entries()) for (const [cell, tableCell] of tableRow.cells.entries()) collectParagraphs(tableCell.content, [...list, {
100
+ kind: "tableCell",
101
+ block: index,
102
+ row,
103
+ cell
104
+ }], out);
105
+ break;
106
+ case "blockSdt":
107
+ collectParagraphs(block.content, [...list, {
108
+ kind: "blockSdt",
109
+ block: index
110
+ }], out);
111
+ break;
112
+ case "preservedBlock":
113
+ case "bookmarkStart":
114
+ case "bookmarkEnd": break;
115
+ default: return block;
116
+ }
117
+ };
118
+ /** The block-level content of a story. */
119
+ const storyBody = (document, story) => {
120
+ switch (story) {
121
+ case OP_STORIES.MAIN: return document.package.document;
122
+ default: return story;
123
+ }
124
+ };
125
+ /** Every paragraph of a story's block tree, in document order. */
126
+ const storyParagraphs = (body) => {
127
+ const out = [];
128
+ collectParagraphs(body.content, [], out);
129
+ return out;
130
+ };
131
+ const sameStep = (left, right) => {
132
+ switch (left.kind) {
133
+ case "tableCell": return right.kind === "tableCell" && left.block === right.block && left.row === right.row && left.cell === right.cell;
134
+ case "blockSdt": return right.kind === "blockSdt" && left.block === right.block;
135
+ default: return left;
136
+ }
137
+ };
138
+ /** Whether two locations are in the same block list. */
139
+ const sameBlockList = (left, right) => left.length === right.length && left.every((step, index) => {
140
+ const other = right[index];
141
+ return other !== void 0 && sameStep(step, other);
142
+ });
143
+ const updateBlockList = (blocks, list, update) => {
144
+ const [step, ...rest] = list;
145
+ if (step === void 0) return update(blocks);
146
+ const block = blocks[step.block];
147
+ const out = [...blocks];
148
+ switch (step.kind) {
149
+ case "tableCell": {
150
+ const row = block?.type === "table" ? block.rows[step.row] : void 0;
151
+ const cell = row?.cells[step.cell];
152
+ if (block?.type !== "table" || row === void 0 || cell === void 0) return panic(`Block list step does not name a table cell at block ${step.block}.`);
153
+ const cells = [...row.cells];
154
+ cells[step.cell] = {
155
+ ...cell,
156
+ content: updateBlockList(cell.content, rest, update)
157
+ };
158
+ const rows = [...block.rows];
159
+ rows[step.row] = {
160
+ ...row,
161
+ cells
162
+ };
163
+ out[step.block] = {
164
+ ...block,
165
+ rows
166
+ };
167
+ return out;
168
+ }
169
+ case "blockSdt":
170
+ if (block?.type !== "blockSdt") return panic(`Block list step does not name a block content control at ${step.block}.`);
171
+ out[step.block] = {
172
+ ...block,
173
+ content: updateBlockList(block.content, rest, update)
174
+ };
175
+ return out;
176
+ default: return step;
177
+ }
178
+ };
179
+ const breaksSection = (block) => block.type === "paragraph" && block.sectionProperties !== void 0;
180
+ /**
181
+ * The body's blocks grouped as the parser groups them into sections: each
182
+ * top-level paragraph carrying section properties ends one and the rest end
183
+ * the last. The last group is dropped when it is empty and an earlier section
184
+ * exists, as the parser does.
185
+ */
186
+ const sectionGroups = (content) => {
187
+ const groups = [];
188
+ let current = [];
189
+ for (const block of content) {
190
+ current.push(block);
191
+ if (breaksSection(block)) {
192
+ groups.push(current);
193
+ current = [];
194
+ }
195
+ }
196
+ if (current.length > 0 || groups.length === 0) groups.push(current);
197
+ return groups;
198
+ };
199
+ /**
200
+ * `sections`, the parser's per-section view of the body's top-level blocks,
201
+ * derived again from the body after an edit. Section `i` keeps every field of
202
+ * the section it replaces (properties, headers, footers) and holds group `i`;
203
+ * a section whose group is unchanged is the same object. Operations never
204
+ * add, remove or move a section break, so a different count is a bug here.
205
+ */
206
+ const deriveSections = (content, previous) => {
207
+ const groups = sectionGroups(content);
208
+ if (groups.length !== previous.length) return panic(`An edit changed the section count from ${previous.length} to ${groups.length}.`);
209
+ let changed = false;
210
+ const out = [];
211
+ for (const [index, section] of previous.entries()) {
212
+ const group = groups[index] ?? [];
213
+ const same = group.length === section.content.length && group.every((block, position) => block === section.content[position]);
214
+ changed ||= !same;
215
+ out.push(same ? section : {
216
+ ...section,
217
+ content: group
218
+ });
219
+ }
220
+ return changed ? out : previous;
221
+ };
222
+ /**
223
+ * A body holding other blocks, its section view derived from them. A view
224
+ * that does not line up with the blocks (a different section count) is left
225
+ * for {@link sectionsInStep} to report.
226
+ */
227
+ const withBodyContent = (body, content) => {
228
+ const next = {
229
+ ...body,
230
+ content
231
+ };
232
+ if (body.sections !== void 0 && sectionGroups(content).length === body.sections.length) next.sections = deriveSections(content, body.sections);
233
+ return next;
234
+ };
235
+ /**
236
+ * Whether a body's section view says what its blocks say: the same groups
237
+ * of structurally equal blocks, each ended by a paragraph whose section
238
+ * properties the section carries. A view out of step with its body cannot be
239
+ * edited: every edit derives the view again, and its inverse could not give
240
+ * back the stale one.
241
+ */
242
+ const sectionsInStep = (body) => {
243
+ const { sections } = body;
244
+ if (sections === void 0) return true;
245
+ const groups = sectionGroups(body.content);
246
+ if (groups.length !== sections.length) return false;
247
+ return sections.every((section, index) => {
248
+ const group = groups[index] ?? [];
249
+ if (!(group.length === section.content.length && group.every((block, position) => block === section.content[position] || structurallyEqual(block, section.content[position])))) return false;
250
+ const last = group.at(-1);
251
+ const stated = last?.type === "paragraph" && last.sectionProperties !== void 0 ? last.sectionProperties : body.finalSectionProperties;
252
+ return stated === void 0 || structurallyEqual(stated, section.properties);
253
+ });
254
+ };
255
+ /** The document with `count` paragraphs from `at` replaced. */
256
+ const replaceParagraphs = ({ document, story, at, count, replacement }) => {
257
+ const body = storyBody(document, story);
258
+ const content = updateBlockList(body.content, at.list, (blocks) => {
259
+ const out = [...blocks];
260
+ out.splice(at.index, count, ...replacement);
261
+ return out;
262
+ });
263
+ const nextBody = {
264
+ ...body,
265
+ content
266
+ };
267
+ if (body.sections !== void 0) nextBody.sections = deriveSections(content, body.sections);
268
+ switch (story) {
269
+ case OP_STORIES.MAIN: return {
270
+ ...document,
271
+ package: {
272
+ ...document.package,
273
+ document: nextBody
274
+ }
275
+ };
276
+ default: return story;
277
+ }
278
+ };
279
+ //#endregion
280
+ //#region src/ops/ids.ts
281
+ const isPlainRecord = (value) => {
282
+ const prototype = Object.getPrototypeOf(value);
283
+ return prototype === Object.prototype || prototype === null;
284
+ };
285
+ const walk = (value, visit, heldBy) => {
286
+ if (typeof value !== "object" || value === null) return;
287
+ if (Array.isArray(value)) {
288
+ for (const item of value) walk(item, visit, heldBy);
289
+ return;
290
+ }
291
+ if (value instanceof Map) {
292
+ for (const item of value.values()) walk(item, visit, heldBy);
293
+ return;
294
+ }
295
+ if (!isPlainRecord(value)) return;
296
+ const entries = Object.entries(value);
297
+ visit(entries, heldBy);
298
+ for (const [key, field] of entries) walk(field, visit, key);
299
+ };
300
+ /** The package's stories, each once: the body without its derived section view. */
301
+ const storiesOf = (pkg) => ({
302
+ ...pkg,
303
+ document: {
304
+ ...pkg.document,
305
+ sections: void 0
306
+ }
307
+ });
308
+ const fieldOf = (entries, name) => entries.find(([key]) => key === name)?.[1];
309
+ const paragraphIdOf = (entries) => {
310
+ if (fieldOf(entries, "type") !== "paragraph") return void 0;
311
+ const id = fieldOf(entries, "paraId");
312
+ return typeof id === "string" ? id : void 0;
313
+ };
314
+ /** Every `paraId` of every paragraph in a value, nested ones included, in document order. */
315
+ const paragraphIdsIn = (value) => {
316
+ const out = [];
317
+ walk(value, (entries) => {
318
+ const id = paragraphIdOf(entries);
319
+ if (id !== void 0) out.push(id);
320
+ });
321
+ return out;
322
+ };
323
+ /** Every paragraph id of a package, each story walked once. */
324
+ const packageParagraphIds = (pkg) => paragraphIdsIn(storiesOf(pkg));
325
+ /**
326
+ * The key two spellings of one id share. `ST_LongHexNumber` is hex, so
327
+ * `0000abcd` and `0000ABCD` are the same id; every lookup and comparison of
328
+ * paragraph ids goes through this.
329
+ */
330
+ const idKey = (id) => id.toUpperCase();
331
+ /** How many records carry each key. */
332
+ const countKeys = (keys) => {
333
+ const counts = /* @__PURE__ */ new Map();
334
+ for (const key of keys) counts.set(key, (counts.get(key) ?? 0) + 1);
335
+ return counts;
336
+ };
337
+ /** How many paragraphs carry each id, by {@link idKey}. */
338
+ const countIds = (ids) => countKeys(ids.map(idKey));
339
+ /** Whether `incoming` repeats an id of `existing` or of itself, by {@link idKey}. */
340
+ const collides = (existing, incoming) => {
341
+ const seen = /* @__PURE__ */ new Set();
342
+ return incoming.some((id) => {
343
+ const key = idKey(id);
344
+ const repeated = seen.has(key) || (existing.get(key) ?? 0) > 0;
345
+ seen.add(key);
346
+ return repeated;
347
+ });
348
+ };
349
+ /** `ST_LongHexNumber` as `w14:paraId` uses it: eight hex digits below `0x80000000`. */
350
+ const PARA_ID_PATTERN = /^[0-7][0-9A-Fa-f]{7}$/u;
351
+ /** Zero is reserved: it means "no id". */
352
+ const RESERVED_PARA_ID_PATTERN = /^0{8}$/u;
353
+ /** Whether an id can name a paragraph an operation creates. */
354
+ const isParaId = (id) => PARA_ID_PATTERN.test(id) && !RESERVED_PARA_ID_PATTERN.test(id);
355
+ /** The id spaces of revisions and content controls. */
356
+ const IDENTITY_SPACES = Object.freeze({
357
+ REVISION: "revision",
358
+ CONTROL: "control"
359
+ });
360
+ const slotKey = ({ space, id }) => `${space}:${id}`;
361
+ const revisionIdOf = (entries) => {
362
+ const info = fieldOf(entries, "info");
363
+ if (typeof info !== "object" || info === null) return void 0;
364
+ const infoEntries = Object.entries(info);
365
+ const id = fieldOf(infoEntries, "id");
366
+ return typeof id === "number" && typeof fieldOf(infoEntries, "author") === "string" ? id : void 0;
367
+ };
368
+ const controlIdOf = (entries) => {
369
+ const id = fieldOf(entries, "id");
370
+ return typeof fieldOf(entries, "sdtType") === "string" && typeof id === "number" ? id : void 0;
371
+ };
372
+ /**
373
+ * Every revision and content-control id in a value, as slot keys: tracked
374
+ * changes and property changes by their `info`, content controls by their
375
+ * properties.
376
+ */
377
+ const identityKeysIn = (value) => {
378
+ const out = [];
379
+ const stacked = /* @__PURE__ */ new Map();
380
+ walk(value, (entries, heldBy) => {
381
+ const revision = revisionIdOf(entries);
382
+ if (revision !== void 0) out.push(slotKey({
383
+ space: IDENTITY_SPACES.REVISION,
384
+ id: revision
385
+ }));
386
+ const control = controlIdOf(entries);
387
+ if (control === void 0) return;
388
+ if (heldBy === CONTENT_CONTROL_STACK) {
389
+ const record = Object.fromEntries(entries);
390
+ const seen = stacked.get(control) ?? [];
391
+ if (seen.some((other) => structurallyEqual(other, record))) return;
392
+ seen.push(record);
393
+ stacked.set(control, seen);
394
+ }
395
+ out.push(slotKey({
396
+ space: IDENTITY_SPACES.CONTROL,
397
+ id: control
398
+ }));
399
+ });
400
+ return out;
401
+ };
402
+ /** The field holding the stack of content controls a table row or cell sits inside. */
403
+ const CONTENT_CONTROL_STACK = "contentControls";
404
+ /** Every revision and content-control id of a package, each story walked once. */
405
+ const packageIdentityKeys = (pkg) => identityKeysIn(storiesOf(pkg));
406
+ //#endregion
407
+ //#region src/ops/offsets.ts
408
+ /**
409
+ * A paragraph's logical offset space.
410
+ *
411
+ * Every position an operation names is a count of units from the start of a
412
+ * paragraph:
413
+ *
414
+ * - a character of run text is one unit per UTF-16 code unit;
415
+ * - every other run child (tab, break, symbol, note reference, drawing,
416
+ * captured markup, field character) is one unit, except the cached
417
+ * rendered-page-break marker a layout pass writes, which is zero-width;
418
+ * - a field, an equation and a comment reference are one unit each, however
419
+ * much they hold;
420
+ * - captured inline markup is one unit when it shows text and none when it
421
+ * shows nothing;
422
+ * - bookmark, comment and move boundaries take no units;
423
+ * - hyperlinks, tracked changes, content controls and the transparent
424
+ * wrappers take none themselves: their content is counted in place.
425
+ *
426
+ * Tracked-deleted text counts like any other: the visible-text view is
427
+ * derived, and positions stay stable when a revision is accepted or rejected
428
+ * elsewhere in the paragraph.
429
+ */
430
+ /** How each paragraph child takes part in the offset space. */
431
+ const INLINE_KINDS = {
432
+ run: "run",
433
+ hyperlink: "container",
434
+ insertion: "container",
435
+ deletion: "container",
436
+ moveFrom: "container",
437
+ moveTo: "container",
438
+ inlineSdt: "container",
439
+ inlineWrapper: "container",
440
+ simpleField: "atom",
441
+ complexField: "atom",
442
+ mathEquation: "atom",
443
+ commentReference: "atom",
444
+ preservedInline: "opaque",
445
+ bookmarkStart: "openingMarker",
446
+ commentRangeStart: "openingMarker",
447
+ moveFromRangeStart: "openingMarker",
448
+ moveToRangeStart: "openingMarker",
449
+ bookmarkEnd: "closingMarker",
450
+ commentRangeEnd: "closingMarker",
451
+ moveFromRangeEnd: "closingMarker",
452
+ moveToRangeEnd: "closingMarker"
453
+ };
454
+ const isInlineContainer = (item) => INLINE_KINDS[item.type] === "container";
455
+ /** A zero-width boundary that opens a range: it belongs with what follows it. */
456
+ const isOpeningMarker = (item) => INLINE_KINDS[item.type] === "openingMarker";
457
+ /** Tracked content that direct text must not join: it is on its way out. */
458
+ const isRemovedRevision = (item) => item.type === "deletion" || item.type === "moveFrom";
459
+ const runContentWidth = (content) => {
460
+ switch (content.type) {
461
+ case "text": return content.text.length;
462
+ case "renderedPageBreak": return 0;
463
+ default: return 1;
464
+ }
465
+ };
466
+ const runWidth = (run) => {
467
+ let width = 0;
468
+ for (const content of run.content) width += runContentWidth(content);
469
+ return width;
470
+ };
471
+ const childrenOf = (container) => container.type === "hyperlink" ? container.children : container.content;
472
+ const inlineWidth = (item) => {
473
+ if (item.type === "run") return runWidth(item);
474
+ if (isInlineContainer(item)) return contentWidth(childrenOf(item));
475
+ if (item.type === "preservedInline") return item.text === "" ? 0 : 1;
476
+ return INLINE_KINDS[item.type] === "atom" ? 1 : 0;
477
+ };
478
+ const contentWidth = (items) => {
479
+ let width = 0;
480
+ for (const item of items) width += inlineWidth(item);
481
+ return width;
482
+ };
483
+ /** The number of logical units in a paragraph: its largest valid offset. */
484
+ const paragraphLength = (paragraph) => contentWidth(paragraph.content);
485
+ /** The character a unit that is not run text stands for in {@link paragraphLogicalText}. */
486
+ const OBJECT_REPLACEMENT_CHARACTER = "";
487
+ const appendLogicalText = (items, out) => {
488
+ for (const item of items) {
489
+ if (item.type === "run") {
490
+ for (const content of item.content) if (content.type === "text") out.push(content.text);
491
+ else if (runContentWidth(content) === 1) out.push("");
492
+ continue;
493
+ }
494
+ if (isInlineContainer(item)) {
495
+ appendLogicalText(childrenOf(item), out);
496
+ continue;
497
+ }
498
+ if (inlineWidth(item) === 1) out.push("");
499
+ }
500
+ };
501
+ /**
502
+ * The paragraph's offset space as a string: run text as it stands and
503
+ * {@link OBJECT_REPLACEMENT_CHARACTER} for every other unit, so index `i` of
504
+ * the string is unit `i` of the paragraph.
505
+ */
506
+ const paragraphLogicalText = (paragraph) => {
507
+ const out = [];
508
+ appendLogicalText(paragraph.content, out);
509
+ return out.join("");
510
+ };
511
+ const HYPERLINK_CHILD_TYPES = {
512
+ run: true,
513
+ bookmarkStart: true,
514
+ bookmarkEnd: true,
515
+ inlineWrapper: true,
516
+ preservedInline: true
517
+ };
518
+ const TRACKED_CHILD_TYPES = {
519
+ run: true,
520
+ hyperlink: true,
521
+ bookmarkStart: true,
522
+ bookmarkEnd: true,
523
+ moveFromRangeStart: true,
524
+ moveFromRangeEnd: true,
525
+ moveToRangeStart: true,
526
+ moveToRangeEnd: true,
527
+ simpleField: true,
528
+ complexField: true,
529
+ inlineSdt: true,
530
+ inlineWrapper: true,
531
+ mathEquation: true,
532
+ preservedInline: true,
533
+ insertion: true,
534
+ deletion: true,
535
+ moveFrom: true,
536
+ moveTo: true
537
+ };
538
+ const INLINE_SDT_CHILD_TYPES = {
539
+ run: true,
540
+ hyperlink: true,
541
+ bookmarkStart: true,
542
+ bookmarkEnd: true,
543
+ moveFromRangeStart: true,
544
+ moveFromRangeEnd: true,
545
+ moveToRangeStart: true,
546
+ moveToRangeEnd: true,
547
+ simpleField: true,
548
+ complexField: true,
549
+ inlineSdt: true,
550
+ inlineWrapper: true,
551
+ insertion: true,
552
+ deletion: true,
553
+ moveFrom: true,
554
+ moveTo: true,
555
+ mathEquation: true,
556
+ preservedInline: true
557
+ };
558
+ const isHyperlinkChild = (item) => Object.hasOwn(HYPERLINK_CHILD_TYPES, item.type);
559
+ const isTrackedChild = (item) => Object.hasOwn(TRACKED_CHILD_TYPES, item.type);
560
+ const isInlineSdtChild = (item) => Object.hasOwn(INLINE_SDT_CHILD_TYPES, item.type);
561
+ /**
562
+ * Narrow a rebuilt child list back to what its container admits. Every edit
563
+ * keeps the kinds it was given and adds only runs, which each container
564
+ * admits, so a child outside the container's content model is a bug here.
565
+ */
566
+ const narrowChildren = (items, admits, container) => {
567
+ const out = [];
568
+ for (const item of items) {
569
+ if (!admits(item)) return panic(`A ${item.type} cannot be a child of ${container}.`);
570
+ out.push(item);
571
+ }
572
+ return out;
573
+ };
574
+ /** The same container holding other children. */
575
+ const withChildren = (container, items) => {
576
+ switch (container.type) {
577
+ case "hyperlink": return {
578
+ ...container,
579
+ children: narrowChildren(items, isHyperlinkChild, container.type)
580
+ };
581
+ case "insertion":
582
+ case "deletion":
583
+ case "moveFrom":
584
+ case "moveTo": return {
585
+ ...container,
586
+ content: narrowChildren(items, isTrackedChild, container.type)
587
+ };
588
+ case "inlineSdt": return {
589
+ ...container,
590
+ content: narrowChildren(items, isInlineSdtChild, container.type)
591
+ };
592
+ case "inlineWrapper": return {
593
+ ...container,
594
+ content: [...items]
595
+ };
596
+ default: return container;
597
+ }
598
+ };
599
+ //#endregion
600
+ //#region src/ops/slots.ts
601
+ const revision = (id) => ({
602
+ space: IDENTITY_SPACES.REVISION,
603
+ id
604
+ });
605
+ /** The ids a record carries itself, in a fixed order; its children's are their own. */
606
+ const identitySlots = (record) => {
607
+ switch (record.type) {
608
+ case "paragraph": {
609
+ const out = (record.propertyChanges ?? []).map((change) => revision(change.info.id));
610
+ if (record.pPrMark !== void 0) out.push(revision(record.pPrMark.info.id));
611
+ return out;
612
+ }
613
+ case "run": return (record.propertyChanges ?? []).map((change) => revision(change.info.id));
614
+ case "insertion":
615
+ case "deletion":
616
+ case "moveFrom":
617
+ case "moveTo": return [revision(record.info.id)];
618
+ case "inlineSdt": return record.properties.id === void 0 ? [] : [{
619
+ space: IDENTITY_SPACES.CONTROL,
620
+ id: record.properties.id
621
+ }];
622
+ default: return [];
623
+ }
624
+ };
625
+ const withRunChangeIds = (changes, ids) => {
626
+ const out = [];
627
+ for (const [index, change] of changes.entries()) out.push({
628
+ ...change,
629
+ info: {
630
+ ...change.info,
631
+ id: ids[index] ?? change.info.id
632
+ }
633
+ });
634
+ return out;
635
+ };
636
+ const withParagraphChangeIds = (changes, ids) => {
637
+ const out = [];
638
+ for (const [index, change] of changes.entries()) out.push({
639
+ ...change,
640
+ info: {
641
+ ...change.info,
642
+ id: ids[index] ?? change.info.id
643
+ }
644
+ });
645
+ return out;
646
+ };
647
+ /** The same inline record carrying other ids, slot for slot. */
648
+ const withInlineIdentity = (node, ids) => {
649
+ switch (node.type) {
650
+ case "run": return node.propertyChanges === void 0 ? node : {
651
+ ...node,
652
+ propertyChanges: withRunChangeIds(node.propertyChanges, ids)
653
+ };
654
+ case "insertion":
655
+ case "deletion":
656
+ case "moveFrom":
657
+ case "moveTo": return {
658
+ ...node,
659
+ info: {
660
+ ...node.info,
661
+ id: ids[0] ?? node.info.id
662
+ }
663
+ };
664
+ case "inlineSdt": return node.properties.id === void 0 ? node : {
665
+ ...node,
666
+ properties: {
667
+ ...node.properties,
668
+ id: ids[0] ?? node.properties.id
669
+ }
670
+ };
671
+ default: return node;
672
+ }
673
+ };
674
+ /** The same paragraph carrying other ids on its own tracked changes, slot for slot. */
675
+ const withParagraphIdentity = (paragraph, ids) => {
676
+ const next = { ...paragraph };
677
+ const changes = paragraph.propertyChanges;
678
+ if (changes !== void 0) next.propertyChanges = withParagraphChangeIds(changes, ids);
679
+ if (paragraph.pPrMark !== void 0) {
680
+ const id = ids[changes?.length ?? 0] ?? paragraph.pPrMark.info.id;
681
+ next.pPrMark = {
682
+ ...paragraph.pPrMark,
683
+ info: {
684
+ ...paragraph.pPrMark.info,
685
+ id
686
+ }
687
+ };
688
+ }
689
+ return next;
690
+ };
691
+ /** A record with every id it carries set to zero: the form two records are compared in. */
692
+ const maskIdentity = (node) => {
693
+ const slots = identitySlots(node);
694
+ return slots.length === 0 ? node : withInlineIdentity(node, slots.map(() => 0));
695
+ };
696
+ //#endregion
697
+ //#region src/ops/leaves.ts
698
+ /**
699
+ * A paragraph's content as a sequence of leaves, and the three moves every
700
+ * edit is made of: partition the leaves between gaps, find the records that
701
+ * run across a gap, and merge records that meet at one.
702
+ *
703
+ * A leaf is a unit of the offset space (a character of run text, a tab, a
704
+ * field) or a zero-width child (a range marker, markup that shows nothing, a
705
+ * run or container with nothing in it). A gap is a place between two leaves:
706
+ * an offset plus how many zero-width leaves at that offset come before it.
707
+ *
708
+ * Partitioning keeps each record whose leaves all fall on one side as the
709
+ * same object and cuts the others in two, each half keeping every field of
710
+ * the original. Merging is the reverse: two records alike in everything but
711
+ * their content become one. Because a deletion is "keep the leaves outside
712
+ * the gaps" and an insertion is "cut at a gap and merge the new leaves in",
713
+ * each is the other's exact inverse, whatever the records around them hold.
714
+ */
715
+ const RUN_CONTENT_TYPES = {
716
+ text: true,
717
+ tab: true,
718
+ break: true,
719
+ symbol: true,
720
+ footnoteRef: true,
721
+ endnoteRef: true,
722
+ fieldChar: true,
723
+ instrText: true,
724
+ softHyphen: true,
725
+ noBreakHyphen: true,
726
+ renderedPageBreak: true,
727
+ preservedXml: true,
728
+ drawing: true,
729
+ shape: true
730
+ };
731
+ const isRunContent = (node) => Object.hasOwn(RUN_CONTENT_TYPES, node.type);
732
+ const isParagraphContent = (node) => !isRunContent(node);
733
+ /** The children of a run or container; `undefined` for anything that has none. */
734
+ const childNodes = (node) => {
735
+ if (node.type === "run") return node.content;
736
+ if (isRunContent(node)) return;
737
+ return isInlineContainer(node) ? childrenOf(node) : void 0;
738
+ };
739
+ const kindOf = (node) => {
740
+ if (node.type === "text") return node.text === "" ? "zeroWidth" : "characters";
741
+ const children = childNodes(node);
742
+ if (children !== void 0) return children.length === 0 ? "zeroWidth" : "branch";
743
+ if (isRunContent(node)) return runContentWidth(node) === 1 ? "unit" : "zeroWidth";
744
+ return inlineWidth(node) === 1 ? "unit" : "zeroWidth";
745
+ };
746
+ /**
747
+ * Whether a record is an empty run or an empty text node. Neither says
748
+ * anything, operations never create one, and a document is normalized so it
749
+ * holds none (see `contract.ts`): otherwise each is a zero-width leaf that
750
+ * positions would have to count. An empty hyperlink or content control is
751
+ * not empty in this sense: it is markup, and stays a zero-width leaf.
752
+ */
753
+ const isEmptyRecord = (node) => node.type === "text" && node.text === "" || node.type === "run" && node.content.length === 0;
754
+ const startCursor = () => ({
755
+ position: 0,
756
+ zeroWidthSeen: 0
757
+ });
758
+ const unitRegion = (gaps, unit) => {
759
+ let region = 0;
760
+ for (const gap of gaps) if (gap.offset <= unit) region += 1;
761
+ return region;
762
+ };
763
+ const zeroWidthRegion = (gaps, cursor) => {
764
+ let region = 0;
765
+ for (const gap of gaps) if (gap.offset < cursor.position || gap.offset === cursor.position && gap.zeroWidthBefore <= cursor.zeroWidthSeen) region += 1;
766
+ return region;
767
+ };
768
+ /** Narrow rebuilt children back to what their parent admits; anything else is a bug here. */
769
+ const narrowNodes = (nodes, admits) => {
770
+ const out = [];
771
+ for (const node of nodes) {
772
+ if (!admits(node)) return panic(`A ${node.type} is not admitted here.`);
773
+ out.push(node);
774
+ }
775
+ return out;
776
+ };
777
+ /** Paragraph children, narrowed from nodes. */
778
+ const asParagraphContent = (nodes) => narrowNodes(nodes, isParagraphContent);
779
+ /** The same run or container holding other children. */
780
+ const rebuildNode = (node, children) => {
781
+ if (node.type === "run") return {
782
+ ...node,
783
+ content: narrowNodes(children, isRunContent)
784
+ };
785
+ if (isRunContent(node) || !isInlineContainer(node)) return panic(`A ${node.type} has no children to rebuild.`);
786
+ return withChildren(node, narrowNodes(children, isParagraphContent));
787
+ };
788
+ const partitionNode = (node, gaps, cursor) => {
789
+ if (node.type === "text" && node.text !== "") {
790
+ const start = cursor.position;
791
+ const pieces = [];
792
+ let pieceStart = 0;
793
+ let region = unitRegion(gaps, start);
794
+ for (let index = 1; index < node.text.length; index += 1) {
795
+ const next = unitRegion(gaps, start + index);
796
+ if (next !== region) {
797
+ pieces.push([region, {
798
+ ...node,
799
+ text: node.text.slice(pieceStart, index)
800
+ }]);
801
+ pieceStart = index;
802
+ region = next;
803
+ }
804
+ }
805
+ cursor.position += node.text.length;
806
+ cursor.zeroWidthSeen = 0;
807
+ if (pieces.length === 0) return {
808
+ pieces: [[region, node]],
809
+ min: region,
810
+ max: region
811
+ };
812
+ pieces.push([region, {
813
+ ...node,
814
+ text: node.text.slice(pieceStart)
815
+ }]);
816
+ return {
817
+ pieces,
818
+ min: pieces[0]?.[0] ?? region,
819
+ max: region
820
+ };
821
+ }
822
+ const kind = kindOf(node);
823
+ switch (kind) {
824
+ case "unit": {
825
+ const region = unitRegion(gaps, cursor.position);
826
+ cursor.position += 1;
827
+ cursor.zeroWidthSeen = 0;
828
+ return {
829
+ pieces: [[region, node]],
830
+ min: region,
831
+ max: region
832
+ };
833
+ }
834
+ case "zeroWidth": {
835
+ const region = zeroWidthRegion(gaps, cursor);
836
+ cursor.zeroWidthSeen += 1;
837
+ return {
838
+ pieces: [[region, node]],
839
+ min: region,
840
+ max: region
841
+ };
842
+ }
843
+ case "characters": return panic("Run text is partitioned by character above.");
844
+ case "branch": {
845
+ const inner = partitionNodes(childNodes(node) ?? [], gaps, cursor);
846
+ if (inner.min === inner.max) return {
847
+ pieces: [[inner.min, node]],
848
+ min: inner.min,
849
+ max: inner.max
850
+ };
851
+ const pieces = [];
852
+ for (const [region, part] of inner.parts.entries()) if (part.length > 0) pieces.push([region, rebuildNode(node, part)]);
853
+ return {
854
+ pieces,
855
+ min: inner.min,
856
+ max: inner.max
857
+ };
858
+ }
859
+ default: return kind;
860
+ }
861
+ };
862
+ const partitionNodes = (items, gaps, cursor) => {
863
+ const parts = Array.from({ length: gaps.length + 1 }, () => []);
864
+ let min = Number.POSITIVE_INFINITY;
865
+ let max = Number.NEGATIVE_INFINITY;
866
+ for (const item of items) {
867
+ const piece = partitionNode(item, gaps, cursor);
868
+ for (const [region, node] of piece.pieces) parts[region]?.push(node);
869
+ min = Math.min(min, piece.min);
870
+ max = Math.max(max, piece.max);
871
+ }
872
+ return {
873
+ parts,
874
+ min,
875
+ max
876
+ };
877
+ };
878
+ /**
879
+ * The content between consecutive gaps, one list per region: the records of
880
+ * each region, cut where a gap passes through them. Gaps must be in order.
881
+ */
882
+ const partitionContent = (items, gaps) => partitionNodes(items, gaps, startCursor()).parts;
883
+ /**
884
+ * The records holding leaves of both region `first` and region `last`,
885
+ * outermost first. They form one chain: each is inside the one before.
886
+ */
887
+ const spanningRecords = (items, gaps, first, last) => {
888
+ const spine = [];
889
+ const cursor = startCursor();
890
+ let list = items;
891
+ while (list !== void 0) {
892
+ let found;
893
+ for (const item of list) {
894
+ const start = { ...cursor };
895
+ const { min, max } = partitionNode(item, gaps, cursor);
896
+ if (min <= first && max >= last) {
897
+ found = item;
898
+ cursor.position = start.position;
899
+ cursor.zeroWidthSeen = start.zeroWidthSeen;
900
+ break;
901
+ }
902
+ }
903
+ if (found === void 0) return spine;
904
+ spine.push(found);
905
+ list = found.type === "text" ? void 0 : childNodes(found);
906
+ }
907
+ return spine;
908
+ };
909
+ const childrenKey = (node) => node.type === "hyperlink" ? "children" : "content";
910
+ const ownFields = (node) => {
911
+ const key = childrenKey(node);
912
+ return Object.entries(node).filter(([name]) => name !== key);
913
+ };
914
+ /**
915
+ * Whether two records are alike in everything but their content and the ids
916
+ * they carry: merged, the first one's ids stand for both.
917
+ */
918
+ const sameOwnFields = (left, right) => left.type === right.type && structurallyEqual(Object.fromEntries(ownFields(maskIdentity(left))), Object.fromEntries(ownFields(maskIdentity(right))));
919
+ const EXACT_MERGE = Object.freeze({ mode: "exact" });
920
+ const mergeNode = (left, right, depth, rule, level) => {
921
+ const kind = kindOf(left);
922
+ if (kind !== kindOf(right) || kind !== "characters" && kind !== "branch") return;
923
+ if (left.type === "text" && right.type === "text") return depth === 1 ? {
924
+ ...left,
925
+ text: left.text + right.text
926
+ } : void 0;
927
+ const leftChildren = childNodes(left);
928
+ const rightChildren = childNodes(right);
929
+ if (leftChildren === void 0 || rightChildren === void 0 || !sameOwnFields(left, right)) return;
930
+ rule.onMerge?.(left, right, level);
931
+ const children = mergeLists(leftChildren, rightChildren, depth - 1, rule, level + 1);
932
+ if (children === void 0) return;
933
+ const merged = rebuildNode(left, children);
934
+ return rule.identity === "second" ? withInlineIdentity(merged, identitySlots(right).map(({ id }) => id)) : merged;
935
+ };
936
+ /**
937
+ * Two lists end to end, the last record of the first merged with the first of
938
+ * the second, and so on `depth` levels down. `undefined` when an exact merge
939
+ * meets records that cannot be merged.
940
+ */
941
+ const mergeLists = (left, right, depth, rule = EXACT_MERGE, level = 1) => {
942
+ if (depth === 0) return [...left, ...right];
943
+ const last = left.at(-1);
944
+ const first = right.at(0);
945
+ const merged = last === void 0 || first === void 0 ? void 0 : mergeNode(last, first, depth, rule, level);
946
+ if (merged === void 0) return rule.mode === "asFarAsAlike" ? [...left, ...right] : void 0;
947
+ return [
948
+ ...left.slice(0, -1),
949
+ merged,
950
+ ...right.slice(1)
951
+ ];
952
+ };
953
+ /** The zero-width leaves at an offset, in document order. */
954
+ const zeroWidthLeavesAt = (items, offset) => {
955
+ const out = [];
956
+ const cursor = startCursor();
957
+ const walk = (list) => {
958
+ for (const node of list) {
959
+ if (cursor.position > offset) return;
960
+ const kind = kindOf(node);
961
+ switch (kind) {
962
+ case "characters":
963
+ if (node.type === "text") cursor.position += node.text.length;
964
+ break;
965
+ case "unit":
966
+ cursor.position += 1;
967
+ break;
968
+ case "zeroWidth":
969
+ if (cursor.position === offset) out.push(node);
970
+ break;
971
+ case "branch":
972
+ walk(childNodes(node) ?? []);
973
+ break;
974
+ default: return kind;
975
+ }
976
+ }
977
+ };
978
+ walk(items);
979
+ return out;
980
+ };
981
+ /**
982
+ * The gap an insertion defaults to: before the first zero-width leaf at the
983
+ * offset that opens a range, so a marker opening there stays with what
984
+ * follows it and every other one with what precedes it.
985
+ */
986
+ const defaultInsertionGap = (items, offset) => {
987
+ const leaves = zeroWidthLeavesAt(items, offset);
988
+ const opening = leaves.findIndex((leaf) => isParagraphContent(leaf) && isOpeningMarker(leaf));
989
+ return {
990
+ offset,
991
+ zeroWidthBefore: opening === -1 ? leaves.length : opening
992
+ };
993
+ };
994
+ /** Every run text in a list, nested ones included. */
995
+ const textsIn = (items) => {
996
+ const out = [];
997
+ const walk = (list) => {
998
+ for (const node of list) {
999
+ if (node.type === "text") {
1000
+ out.push(node.text);
1001
+ continue;
1002
+ }
1003
+ const children = childNodes(node);
1004
+ if (children !== void 0) walk(children);
1005
+ }
1006
+ };
1007
+ walk(items);
1008
+ return out;
1009
+ };
1010
+ /**
1011
+ * The records every leaf of which lies between two gaps, nested ones
1012
+ * included: what an insertion put in, as opposed to records holding content
1013
+ * that was there before.
1014
+ */
1015
+ const recordsBetween = (items, from, to) => {
1016
+ const out = /* @__PURE__ */ new Set();
1017
+ const gaps = [from, to];
1018
+ const cursor = startCursor();
1019
+ const walk = (list) => {
1020
+ for (const node of list) {
1021
+ const start = { ...cursor };
1022
+ const { min, max } = partitionNode(node, gaps, cursor);
1023
+ if (min === 1 && max === 1) out.add(node);
1024
+ const children = childNodes(node);
1025
+ if (children !== void 0 && kindOf(node) === "branch" && !(min === 1 && max === 1)) {
1026
+ const end = { ...cursor };
1027
+ cursor.position = start.position;
1028
+ cursor.zeroWidthSeen = start.zeroWidthSeen;
1029
+ walk(children);
1030
+ cursor.position = end.position;
1031
+ cursor.zeroWidthSeen = end.zeroWidthSeen;
1032
+ } else if (min === 1 && max === 1 && children !== void 0) {
1033
+ const collect = (nodes) => {
1034
+ for (const child of nodes) {
1035
+ out.add(child);
1036
+ collect(childNodes(child) ?? []);
1037
+ }
1038
+ };
1039
+ collect(children);
1040
+ }
1041
+ }
1042
+ };
1043
+ walk(items);
1044
+ return out;
1045
+ };
1046
+ const advance = (node, cursor) => {
1047
+ const kind = kindOf(node);
1048
+ switch (kind) {
1049
+ case "characters":
1050
+ if (node.type === "text") cursor.position += node.text.length;
1051
+ cursor.zeroWidthSeen = 0;
1052
+ return;
1053
+ case "unit":
1054
+ cursor.position += 1;
1055
+ cursor.zeroWidthSeen = 0;
1056
+ return;
1057
+ case "zeroWidth":
1058
+ cursor.zeroWidthSeen += 1;
1059
+ return;
1060
+ case "branch":
1061
+ for (const child of childNodes(node) ?? []) advance(child, cursor);
1062
+ return;
1063
+ default: return kind;
1064
+ }
1065
+ };
1066
+ /**
1067
+ * Every run in document order with its gaps, runs inside hyperlinks, tracked
1068
+ * changes, content controls and wrappers included; runs inside a field are
1069
+ * part of the field's one unit and are not listed.
1070
+ */
1071
+ const runGaps = (items) => {
1072
+ const out = [];
1073
+ const cursor = startCursor();
1074
+ const walk = (list) => {
1075
+ for (const node of list) {
1076
+ if (node.type === "run") {
1077
+ const before = {
1078
+ offset: cursor.position,
1079
+ zeroWidthBefore: cursor.zeroWidthSeen
1080
+ };
1081
+ advance(node, cursor);
1082
+ out.push({
1083
+ node,
1084
+ before,
1085
+ after: {
1086
+ offset: cursor.position,
1087
+ zeroWidthBefore: cursor.zeroWidthSeen
1088
+ }
1089
+ });
1090
+ continue;
1091
+ }
1092
+ if (kindOf(node) === "branch") {
1093
+ walk(childNodes(node) ?? []);
1094
+ continue;
1095
+ }
1096
+ advance(node, cursor);
1097
+ }
1098
+ };
1099
+ walk(items);
1100
+ return out;
1101
+ };
1102
+ //#endregion
1103
+ //#region src/ops/refusal.ts
1104
+ /**
1105
+ * Why an operation was not applied. A refused operation changes nothing: the
1106
+ * document it was applied to is returned as it was.
1107
+ */
1108
+ const DOCUMENT_OP_REFUSAL_REASONS = Object.freeze({
1109
+ /** No paragraph in the story carries the id. */
1110
+ BLOCK_NOT_FOUND: "blockNotFound",
1111
+ /** An offset is not an integer from `0` to the paragraph's length, or a range runs backwards. */
1112
+ INVALID_OFFSET: "invalidOffset",
1113
+ /** A range starts and ends in different paragraphs or stories. */
1114
+ CROSS_BLOCK_RANGE: "crossBlockRange",
1115
+ /** A position falls between the two halves of a surrogate pair. */
1116
+ SPLITS_SURROGATE_PAIR: "splitsSurrogatePair",
1117
+ /** Inserted text is empty, holds a tab or line-break character, or cannot be written to XML. */
1118
+ INVALID_TEXT: "invalidText",
1119
+ /**
1120
+ * A paragraph id the operation (or its inverse) creates is not eight hex
1121
+ * digits below `0x80000000`, or is the reserved `00000000`.
1122
+ */
1123
+ INVALID_BLOCK_ID: "invalidBlockId",
1124
+ /**
1125
+ * An id the operation brings in (a paragraph id, or a revision or
1126
+ * content-control id a replacement carries) is already used in the package.
1127
+ */
1128
+ ID_COLLISION: "idCollision",
1129
+ /** The paragraphs to join or replace are not adjacent siblings of one container. */
1130
+ NOT_ADJACENT: "notAdjacent",
1131
+ /**
1132
+ * The operation would move or remove a section break (joining a paragraph
1133
+ * that ends a section, replacing paragraphs across or at one); that is a
1134
+ * section operation.
1135
+ */
1136
+ SECTION_BOUNDARY: "sectionBoundary",
1137
+ /** Direct text would land inside tracked-deleted or moved-away content. */
1138
+ INSIDE_TRACKED_DELETION: "insideTrackedDeletion",
1139
+ /**
1140
+ * The operation cuts a record carrying a revision or content-control id in
1141
+ * two and names too few `newIds` for the halves after the first.
1142
+ */
1143
+ NEEDS_NEW_IDS: "needsNewIds",
1144
+ /** A new revision or content-control id is not an integer from 0 to 2^31 - 1. */
1145
+ INVALID_NEW_ID: "invalidNewId",
1146
+ /**
1147
+ * The operation would merge two records carrying the same revision or
1148
+ * content-control id: nothing could tell them apart again to undo it.
1149
+ */
1150
+ SHARED_ID: "sharedId",
1151
+ /**
1152
+ * What the operation expects (paragraphs to replace, a slice to delete,
1153
+ * the values a patch replaced) is not what is there.
1154
+ */
1155
+ STALE: "stale",
1156
+ /**
1157
+ * The records at a position are not the shape the operation needs: an open
1158
+ * end meets a record it cannot merge with, records to join differ, a slice
1159
+ * would merge records that were separate, or there are fewer records to cut
1160
+ * than the operation names.
1161
+ */
1162
+ STRUCTURE_MISMATCH: "structureMismatch",
1163
+ /** Inserted content is empty, or holds an empty run or text node. */
1164
+ EMPTY_CONTENT: "emptyContent",
1165
+ /** A replacement names no paragraph to replace, or none to put in its place. */
1166
+ EMPTY_BLOCK_LIST: "emptyBlockList",
1167
+ /** Seed contract: a main-story paragraph has no `paraId`. */
1168
+ MISSING_BLOCK_ID: "missingBlockId",
1169
+ /** Seed contract: two paragraphs in the package carry one id. */
1170
+ DUPLICATE_BLOCK_ID: "duplicateBlockId",
1171
+ /** Seed contract: two records in the package carry one revision or content-control id. */
1172
+ DUPLICATE_RECORD_ID: "duplicateRecordId",
1173
+ /** Seed contract: the body's section view does not match its blocks. */
1174
+ SECTIONS_OUT_OF_STEP: "sectionsOutOfStep",
1175
+ /** Seed contract: the main story holds an empty run or empty text node. */
1176
+ EMPTY_RECORD: "emptyRecord"
1177
+ });
1178
+ /** An operation the document cannot take as stated. */
1179
+ var DocumentOpRefusal = class extends TaggedError("DocumentOpRefusal") {};
1180
+ //#endregion
1181
+ //#region src/ops/contract.ts
1182
+ /**
1183
+ * The seed contract: what a document must be for operations to apply to it.
1184
+ *
1185
+ * A host establishes it once, when a document enters the journal: run
1186
+ * `ensureParaIds` over the package bytes (it stamps every story, headers,
1187
+ * footers and notes included, and makes ids unique), parse, then
1188
+ * {@link normalizeForOps}. {@link validateOpsDocument} states the result:
1189
+ *
1190
+ * - every paragraph of the main story has a `w14:paraId`;
1191
+ * - no paragraph id repeats anywhere in the package, compared as hex, so an
1192
+ * inverse can always recreate the ids it removed;
1193
+ * - no revision id (tracked changes, property changes) or content-control id
1194
+ * repeats, so the one record carrying an id is the one it names;
1195
+ * - the body's section view says what its blocks say;
1196
+ * - the main story holds no empty run or empty text node.
1197
+ *
1198
+ * Paragraphs in text boxes, headers, footers, notes and comments are other
1199
+ * stories: they are not addressable in schema version 1, and their ids count
1200
+ * toward uniqueness like any other.
1201
+ *
1202
+ * Every operation checks the contract before applying and leaves it holding,
1203
+ * so a document an operation produced is not checked again: documents are
1204
+ * values, never modified in place.
1205
+ */
1206
+ /** A document that does not meet the seed contract. */
1207
+ var DocumentOpsContractError = class extends TaggedError("DocumentOpsContractError") {};
1208
+ const holdsEmptyRecord$1 = (nodes) => nodes.some((node) => isEmptyRecord(node) || holdsEmptyRecord$1(childNodes(node) ?? []));
1209
+ const violation = (document) => {
1210
+ const body = document.package.document;
1211
+ const paragraphs = storyParagraphs(body);
1212
+ if (paragraphs.some(({ paragraph }) => paragraph.paraId === void 0)) return new DocumentOpsContractError({
1213
+ reason: DOCUMENT_OP_REFUSAL_REASONS.MISSING_BLOCK_ID,
1214
+ message: "A main-story paragraph has no paraId; ensureParaIds establishes one."
1215
+ });
1216
+ const repeated = [...countIds(packageParagraphIds(document.package))].find(([, count]) => count > 1);
1217
+ if (repeated !== void 0) return new DocumentOpsContractError({
1218
+ reason: DOCUMENT_OP_REFUSAL_REASONS.DUPLICATE_BLOCK_ID,
1219
+ message: `${repeated[1]} paragraphs in the package are ${repeated[0]}.`
1220
+ });
1221
+ const repeatedRecord = [...countKeys(packageIdentityKeys(document.package))].find(([, count]) => count > 1);
1222
+ if (repeatedRecord !== void 0) return new DocumentOpsContractError({
1223
+ reason: DOCUMENT_OP_REFUSAL_REASONS.DUPLICATE_RECORD_ID,
1224
+ message: `${repeatedRecord[1]} records in the package carry ${repeatedRecord[0]}.`
1225
+ });
1226
+ if (!sectionsInStep(body)) return new DocumentOpsContractError({
1227
+ reason: DOCUMENT_OP_REFUSAL_REASONS.SECTIONS_OUT_OF_STEP,
1228
+ message: "The body's section view does not match its blocks."
1229
+ });
1230
+ if (paragraphs.some(({ paragraph }) => holdsEmptyRecord$1(paragraph.content))) return new DocumentOpsContractError({
1231
+ reason: DOCUMENT_OP_REFUSAL_REASONS.EMPTY_RECORD,
1232
+ message: "The main story holds an empty run or text node; normalizeForOps removes them."
1233
+ });
1234
+ };
1235
+ /** Documents known to meet the contract: checked ones and ones an operation produced. */
1236
+ const MEETS_CONTRACT = /* @__PURE__ */ new WeakSet();
1237
+ /** Check a document against the seed contract. */
1238
+ const validateOpsDocument = (document) => {
1239
+ if (MEETS_CONTRACT.has(document)) return Result.ok(document);
1240
+ const found = violation(document);
1241
+ if (found !== void 0) return Result.err(found);
1242
+ MEETS_CONTRACT.add(document);
1243
+ return Result.ok(document);
1244
+ };
1245
+ /** Record that an operation produced `document` from one that met the contract. */
1246
+ const meetsContract = (document) => {
1247
+ MEETS_CONTRACT.add(document);
1248
+ };
1249
+ const withoutEmpty = (nodes) => {
1250
+ let changed = false;
1251
+ const out = [];
1252
+ for (const node of nodes) {
1253
+ if (isEmptyRecord(node)) {
1254
+ changed = true;
1255
+ continue;
1256
+ }
1257
+ const children = childNodes(node);
1258
+ const kept = children === void 0 ? children : withoutEmpty(children);
1259
+ if (kept !== children && kept !== void 0) {
1260
+ changed = true;
1261
+ const rebuilt = rebuildNode(node, kept);
1262
+ if (!isEmptyRecord(rebuilt)) out.push(rebuilt);
1263
+ continue;
1264
+ }
1265
+ out.push(node);
1266
+ }
1267
+ return changed ? out : nodes;
1268
+ };
1269
+ const normalizeBlocks = (blocks) => {
1270
+ const out = [];
1271
+ for (const block of blocks) switch (block.type) {
1272
+ case "paragraph": {
1273
+ const content = withoutEmpty(block.content);
1274
+ out.push(content === block.content ? block : {
1275
+ ...block,
1276
+ content: asParagraphContent(content)
1277
+ });
1278
+ break;
1279
+ }
1280
+ case "table": {
1281
+ const rows = [];
1282
+ for (const row of block.rows) {
1283
+ const cells = [];
1284
+ for (const cell of row.cells) cells.push({
1285
+ ...cell,
1286
+ content: normalizeBlocks(cell.content)
1287
+ });
1288
+ rows.push({
1289
+ ...row,
1290
+ cells
1291
+ });
1292
+ }
1293
+ out.push({
1294
+ ...block,
1295
+ rows
1296
+ });
1297
+ break;
1298
+ }
1299
+ case "blockSdt":
1300
+ out.push({
1301
+ ...block,
1302
+ content: normalizeBlocks(block.content)
1303
+ });
1304
+ break;
1305
+ case "preservedBlock":
1306
+ case "bookmarkStart":
1307
+ case "bookmarkEnd":
1308
+ out.push(block);
1309
+ break;
1310
+ default: return block;
1311
+ }
1312
+ return out;
1313
+ };
1314
+ /**
1315
+ * The document with every empty run and empty text node of the main story
1316
+ * removed, and its section view derived again. Nothing else changes.
1317
+ */
1318
+ const normalizeForOps = (document) => {
1319
+ const body = document.package.document;
1320
+ return {
1321
+ ...document,
1322
+ package: {
1323
+ ...document.package,
1324
+ document: withBodyContent(body, normalizeBlocks(body.content))
1325
+ }
1326
+ };
1327
+ };
1328
+ //#endregion
1329
+ //#region src/ops/identity.ts
1330
+ /**
1331
+ * How an edit keeps the ids of identified records unique (see `slots.ts`).
1332
+ *
1333
+ * Cutting an identified record in two would leave both halves with its one
1334
+ * id, and operations mint no ids, so the operation that makes the cut names
1335
+ * the new ones (`newIds`): the half holding the start keeps the id, and every
1336
+ * later half takes the next new id, in document order. Merging two identified
1337
+ * records keeps the first one's ids and retires the second's; the inverse
1338
+ * that cuts them apart again names the retired ids, so it recreates them
1339
+ * exactly.
1340
+ */
1341
+ const visitNodes = (nodes, visit) => {
1342
+ for (const node of nodes) {
1343
+ visit(node);
1344
+ visitNodes(childNodes(node) ?? [], visit);
1345
+ }
1346
+ };
1347
+ /** The slot keys of paragraphs and everything in them, in document order. */
1348
+ const identityKeysOf = (paragraphs) => {
1349
+ const out = [];
1350
+ for (const paragraph of paragraphs) {
1351
+ for (const slot of identitySlots(paragraph)) out.push(slotKey(slot));
1352
+ visitNodes(paragraph.content, (node) => {
1353
+ for (const slot of identitySlots(node)) out.push(slotKey(slot));
1354
+ });
1355
+ }
1356
+ return out;
1357
+ };
1358
+ const recordsOf = (paragraphs) => {
1359
+ const out = new Set(paragraphs);
1360
+ for (const paragraph of paragraphs) visitNodes(paragraph.content, (node) => out.add(node));
1361
+ return out;
1362
+ };
1363
+ /**
1364
+ * Give fresh ids to the records an edit created that would otherwise share an
1365
+ * id. A record carried over from `before` unchanged keeps its ids. A record
1366
+ * the edit created (a half of a cut record, inserted content, a rebuilt
1367
+ * container) keeps an id no other record holds, and takes the next of
1368
+ * `newIds`, in document order, for one another record holds: the first half
1369
+ * of a cut record keeps the id, and the halves after it take new ones. Where
1370
+ * a record holding content that was there before and a record holding only
1371
+ * inserted content share an id, the first keeps it: the id stays with the
1372
+ * content it named.
1373
+ *
1374
+ * The seed contract makes every id unique, so the only records that share one
1375
+ * are those the edit created.
1376
+ */
1377
+ const freshenIdentities = ({ before, after, newIds, usedElsewhere, inserted = /* @__PURE__ */ new Set() }) => {
1378
+ const carried = recordsOf(before);
1379
+ const fixed = /* @__PURE__ */ new Set();
1380
+ const createdKeys = [];
1381
+ const note = (record, slots) => {
1382
+ for (const slot of slots) if (carried.has(record)) fixed.add(slotKey(slot));
1383
+ else createdKeys.push(slotKey(slot));
1384
+ };
1385
+ for (const paragraph of after) {
1386
+ note(paragraph, identitySlots(paragraph));
1387
+ visitNodes(paragraph.content, (node) => note(node, identitySlots(node)));
1388
+ }
1389
+ const repeats = /* @__PURE__ */ new Set();
1390
+ const needsFresh = createdKeys.some((key) => {
1391
+ const repeated = fixed.has(key) || repeats.has(key);
1392
+ repeats.add(key);
1393
+ return repeated;
1394
+ });
1395
+ if (!needsFresh && createdKeys.length === 0) return {
1396
+ kind: "fresh",
1397
+ paragraphs: [...after]
1398
+ };
1399
+ const elsewhere = usedElsewhere();
1400
+ if (!needsFresh && !createdKeys.some((key) => elsewhere.has(key))) return {
1401
+ kind: "fresh",
1402
+ paragraphs: [...after]
1403
+ };
1404
+ const keepers = /* @__PURE__ */ new Map();
1405
+ const claimed = /* @__PURE__ */ new Set();
1406
+ const created = [];
1407
+ const collect = (record, slots) => {
1408
+ if (!carried.has(record) && slots.length > 0) created.push([record, slots]);
1409
+ };
1410
+ for (const paragraph of after) {
1411
+ collect(paragraph, identitySlots(paragraph));
1412
+ visitNodes(paragraph.content, (node) => collect(node, identitySlots(node)));
1413
+ }
1414
+ for (const [record, slots] of [...created.filter(([candidate]) => !inserted.has(candidate)), ...created.filter(([candidate]) => inserted.has(candidate))]) for (const [index, slot] of slots.entries()) {
1415
+ const key = slotKey(slot);
1416
+ if (elsewhere.has(key) || fixed.has(key) || claimed.has(key)) continue;
1417
+ claimed.add(key);
1418
+ const kept = keepers.get(record) ?? /* @__PURE__ */ new Set();
1419
+ kept.add(index);
1420
+ keepers.set(record, kept);
1421
+ }
1422
+ const taken = /* @__PURE__ */ new Set([
1423
+ ...elsewhere,
1424
+ ...identityKeysOf(before),
1425
+ ...identityKeysOf(after)
1426
+ ]);
1427
+ const pools = {
1428
+ [IDENTITY_SPACES.REVISION]: newIds.revision ?? [],
1429
+ [IDENTITY_SPACES.CONTROL]: newIds.control ?? []
1430
+ };
1431
+ const next = {
1432
+ [IDENTITY_SPACES.REVISION]: 0,
1433
+ [IDENTITY_SPACES.CONTROL]: 0
1434
+ };
1435
+ let missing = 0;
1436
+ let invalid;
1437
+ const idsFor = (record, slots) => {
1438
+ if (carried.has(record)) return void 0;
1439
+ let changed = false;
1440
+ const ids = slots.map((slot, index) => {
1441
+ if (keepers.get(record)?.has(index) === true) return slot.id;
1442
+ const pool = pools[slot.space];
1443
+ const isTaken = (id) => taken.has(slotKey({
1444
+ space: slot.space,
1445
+ id
1446
+ }));
1447
+ let fresh = pool[next[slot.space]];
1448
+ while (fresh !== void 0 && Number.isInteger(fresh) && isTaken(fresh)) {
1449
+ next[slot.space] += 1;
1450
+ fresh = pool[next[slot.space]];
1451
+ }
1452
+ next[slot.space] += 1;
1453
+ if (fresh === void 0) {
1454
+ missing += 1;
1455
+ return slot.id;
1456
+ }
1457
+ if (!Number.isInteger(fresh) || fresh < 0 || fresh > 2147483647) {
1458
+ invalid ??= fresh;
1459
+ return slot.id;
1460
+ }
1461
+ taken.add(slotKey({
1462
+ space: slot.space,
1463
+ id: fresh
1464
+ }));
1465
+ changed = true;
1466
+ return fresh;
1467
+ });
1468
+ return changed ? ids : void 0;
1469
+ };
1470
+ const freshenNodes = (nodes) => {
1471
+ let changed = false;
1472
+ const out = [];
1473
+ for (const node of nodes) {
1474
+ const ids = idsFor(node, identitySlots(node));
1475
+ const own = ids === void 0 ? node : withInlineIdentity(node, ids);
1476
+ const children = childNodes(node);
1477
+ const freshened = children === void 0 ? children : freshenNodes(children);
1478
+ const result = freshened === children ? own : rebuildNode(own, freshened ?? []);
1479
+ changed ||= result !== node;
1480
+ out.push(result);
1481
+ }
1482
+ return changed ? out : nodes;
1483
+ };
1484
+ const paragraphs = [];
1485
+ for (const paragraph of after) {
1486
+ const ids = idsFor(paragraph, identitySlots(paragraph));
1487
+ const own = ids === void 0 ? paragraph : withParagraphIdentity(paragraph, ids);
1488
+ const content = freshenNodes(paragraph.content);
1489
+ paragraphs.push(content === paragraph.content ? own : {
1490
+ ...own,
1491
+ content: asParagraphContent(content)
1492
+ });
1493
+ }
1494
+ if (missing > 0) return {
1495
+ kind: "needsIds",
1496
+ missing
1497
+ };
1498
+ return invalid === void 0 ? {
1499
+ kind: "fresh",
1500
+ paragraphs
1501
+ } : {
1502
+ kind: "invalidId",
1503
+ id: invalid
1504
+ };
1505
+ };
1506
+ //#endregion
1507
+ //#region src/ops/patch.ts
1508
+ /**
1509
+ * The keys an object states.
1510
+ *
1511
+ * SAFETY: `Object.keys` widens to `string[]`. Both callers pass a model
1512
+ * property set or a patch over one, object literals whose own keys are all
1513
+ * keys of `Formatting`.
1514
+ */
1515
+ const ownKeys = (value) => Object.keys(value);
1516
+ /**
1517
+ * A property set with a patch applied: a value sets its key, `null` clears
1518
+ * it, an absent key is untouched. The input is not modified. A set left with
1519
+ * no keys is `undefined`, the model's spelling of "states nothing".
1520
+ */
1521
+ const applyFormattingPatch = (base, patch) => {
1522
+ const next = {};
1523
+ if (base !== void 0) {
1524
+ for (const key of ownKeys(base)) if (patch[key] === void 0) next[key] = base[key];
1525
+ }
1526
+ for (const key of ownKeys(patch)) {
1527
+ const value = patch[key];
1528
+ if (value !== void 0 && value !== null) next[key] = value;
1529
+ }
1530
+ return Object.keys(next).length === 0 ? void 0 : next;
1531
+ };
1532
+ /**
1533
+ * The patch that gives back what `patch` replaced in `base`: each key it names
1534
+ * set to the value it had, or cleared where it had none.
1535
+ */
1536
+ const priorValues = (base, patch) => {
1537
+ const restore = {};
1538
+ for (const key of ownKeys(patch)) {
1539
+ if (patch[key] === void 0) continue;
1540
+ const prior = base?.[key];
1541
+ restore[key] = prior === void 0 ? null : prior;
1542
+ }
1543
+ return restore;
1544
+ };
1545
+ //#endregion
1546
+ //#region src/ops/inline.ts
1547
+ /**
1548
+ * Edits over a paragraph's content in its logical offset space.
1549
+ *
1550
+ * Every function here is pure: it returns new arrays and records along the
1551
+ * path it changed and hands back every child it did not change as the same
1552
+ * object, so an untouched run is `===` to its input.
1553
+ */
1554
+ /** A run with the property set it states, or none. */
1555
+ const withRunFormatting = (run, formatting) => {
1556
+ const next = { ...run };
1557
+ if (formatting === void 0) delete next.formatting;
1558
+ else next.formatting = formatting;
1559
+ return next;
1560
+ };
1561
+ const withRunContent = (run, content) => ({
1562
+ ...run,
1563
+ content
1564
+ });
1565
+ /** Two property sets state the same thing; an absent set states nothing. */
1566
+ const sameRunFormatting = (left, right) => structurallyEqual(left ?? {}, right ?? {});
1567
+ /** How an inverse spells a property set it gives back: absent, or an empty set. */
1568
+ const emptySetSpelling = (formatting) => formatting !== void 0 && Object.keys(formatting).length === 0 ? EMPTY_PROPERTY_SETS.KEEP : EMPTY_PROPERTY_SETS.OMIT;
1569
+ /** A patched property set, spelled as `whenEmpty` says once it has no keys left. */
1570
+ const patchedSet = (base, patch, whenEmpty) => applyFormattingPatch(base, patch) ?? (whenEmpty === EMPTY_PROPERTY_SETS.KEEP ? {} : void 0);
1571
+ const newTextRun = (text, formatting) => {
1572
+ const content = [{
1573
+ type: "text",
1574
+ text
1575
+ }];
1576
+ return formatting === void 0 || Object.keys(formatting).length === 0 ? {
1577
+ type: "run",
1578
+ content
1579
+ } : {
1580
+ type: "run",
1581
+ formatting,
1582
+ content
1583
+ };
1584
+ };
1585
+ /**
1586
+ * Remove the leaves between two gaps. A record the range passes through keeps
1587
+ * its two ends as one record; one left with nothing goes. Returns the new
1588
+ * content and the slice removed, with its cut ends.
1589
+ */
1590
+ const deleteBetween = (items, from, to) => {
1591
+ const gaps = [from, to];
1592
+ const [before = [], middle = [], after = []] = partitionContent(items, gaps);
1593
+ const across = spanningRecords(items, gaps, 0, 2).length;
1594
+ return {
1595
+ content: asParagraphContent(mergeLists(before, after, across) ?? panic("The two ends of a cut record always merge.")),
1596
+ removed: {
1597
+ content: asParagraphContent(middle),
1598
+ openStart: spanningRecords(items, gaps, 0, 1).length,
1599
+ openEnd: spanningRecords(items, gaps, 1, 2).length
1600
+ }
1601
+ };
1602
+ };
1603
+ /**
1604
+ * Cut the content at a gap and put a slice in, merging its open ends with the
1605
+ * halves; `undefined` when an open end does not match the record it meets.
1606
+ */
1607
+ const insertSliceAt = (items, at, slice) => {
1608
+ const [before = [], after = []] = partitionContent(items, [at]);
1609
+ const withStart = mergeLists(before, slice.content, slice.openStart);
1610
+ const whole = withStart === void 0 ? void 0 : mergeLists(withStart, after, slice.openEnd, {
1611
+ mode: "exact",
1612
+ identity: "second"
1613
+ });
1614
+ return whole === void 0 ? void 0 : asParagraphContent(whole);
1615
+ };
1616
+ /** The gap after inserted content: its trailing zero-width leaves come before it. */
1617
+ const gapAfterInserted = (at, inserted) => {
1618
+ const width = contentWidth(inserted);
1619
+ const trailing = zeroWidthLeavesAt(inserted, width).length;
1620
+ return {
1621
+ offset: at.offset + width,
1622
+ zeroWidthBefore: width === 0 ? at.zeroWidthBefore + trailing : trailing
1623
+ };
1624
+ };
1625
+ /**
1626
+ * What undoes an insertion: removing the inserted leaves, then merging the
1627
+ * records the insertion cut back to how `before` had them, `join` levels
1628
+ * below the ones still running across the gap. `undefined` when the
1629
+ * insertion merged records that were separate before it: no deletion could
1630
+ * tell them apart again, so such an insertion is refused.
1631
+ */
1632
+ const insertionInverse = (before, after, start, end) => {
1633
+ const { content: restored, removed } = deleteBetween(after, start, end);
1634
+ const cut = spanningRecords(before, [start], 0, 1).length;
1635
+ const across = spanningRecords(restored, [start], 0, 1).length;
1636
+ return across > cut ? void 0 : {
1637
+ removed,
1638
+ join: cut - across
1639
+ };
1640
+ };
1641
+ /** Cut the innermost `depth` records running across a gap in two; `undefined` when fewer do. */
1642
+ const splitAt = (items, at, depth) => {
1643
+ const spine = spanningRecords(items, [at], 0, 1);
1644
+ if (depth > spine.length) return;
1645
+ const [before = [], after = []] = partitionContent(items, [at]);
1646
+ return asParagraphContent(mergeLists(before, after, spine.length - depth) ?? panic("The two ends of a cut record always merge."));
1647
+ };
1648
+ /** Two sets of new ids, each space's in order: `first`'s then `second`'s. */
1649
+ const concatIds = (first, second) => {
1650
+ const revision = [...first.revision ?? [], ...second.revision ?? []];
1651
+ const control = [...first.control ?? [], ...second.control ?? []];
1652
+ return {
1653
+ ...revision.length > 0 ? { revision } : {},
1654
+ ...control.length > 0 ? { control } : {}
1655
+ };
1656
+ };
1657
+ /** Whether a set of new ids names any. */
1658
+ const namesIds = (ids) => (ids.revision?.length ?? 0) > 0 || (ids.control?.length ?? 0) > 0;
1659
+ /**
1660
+ * Merge `left` and `right`, `depth` levels, retiring ids from level `from`
1661
+ * down. Two records carrying the same id cannot be merged: a cut could not
1662
+ * give them back two.
1663
+ */
1664
+ const mergeRetiring = (left, right, depth, from) => {
1665
+ const retired = {
1666
+ revision: [],
1667
+ control: []
1668
+ };
1669
+ let shared = false;
1670
+ const content = mergeLists(left, right, depth, {
1671
+ mode: "exact",
1672
+ onMerge: (first, second, level) => {
1673
+ if (level < from) return;
1674
+ const kept = identitySlots(first);
1675
+ for (const [index, slot] of identitySlots(second).entries()) {
1676
+ shared ||= kept[index]?.id === slot.id;
1677
+ retired[slot.space].push(slot.id);
1678
+ }
1679
+ }
1680
+ });
1681
+ if (content === void 0) return { kind: "notAlike" };
1682
+ if (shared) return { kind: "sharedId" };
1683
+ return {
1684
+ kind: "joined",
1685
+ content: asParagraphContent(content),
1686
+ retired: concatIds({}, retired)
1687
+ };
1688
+ };
1689
+ /** Merge the records meeting at a gap, `depth` levels below the ones already running across it. */
1690
+ const joinAt = (items, at, depth) => {
1691
+ const across = spanningRecords(items, [at], 0, 1).length;
1692
+ const [before = [], after = []] = partitionContent(items, [at]);
1693
+ return mergeRetiring(before, after, across + depth, across + 1);
1694
+ };
1695
+ /** A split paragraph's two halves and the records the cut ran through. */
1696
+ const cutAt = (items, at) => {
1697
+ const [before = [], after = []] = partitionContent(items, [at]);
1698
+ return {
1699
+ before: asParagraphContent(before),
1700
+ after: asParagraphContent(after),
1701
+ through: spanningRecords(items, [at], 0, 1)
1702
+ };
1703
+ };
1704
+ /** Two paragraphs' content end to end, `depth` levels of the records meeting there merged. */
1705
+ const joinContent = (first, second, depth) => mergeRetiring(first, second, depth, 1);
1706
+ const splitRun = (run, offset) => {
1707
+ const left = [];
1708
+ const right = [];
1709
+ let position = 0;
1710
+ for (const child of run.content) {
1711
+ const width = runContentWidth(child);
1712
+ const start = position;
1713
+ position += width;
1714
+ if (position <= offset) left.push(child);
1715
+ else if (start >= offset) right.push(child);
1716
+ else if (child.type === "text") {
1717
+ left.push({
1718
+ ...child,
1719
+ text: child.text.slice(0, offset - start)
1720
+ });
1721
+ right.push({
1722
+ ...child,
1723
+ text: child.text.slice(offset - start)
1724
+ });
1725
+ }
1726
+ }
1727
+ return {
1728
+ left: left.length === 0 ? void 0 : withRunContent(run, left),
1729
+ right: right.length === 0 ? void 0 : withRunContent(run, right)
1730
+ };
1731
+ };
1732
+ /** The run holding unit `unit`, or `undefined` when the unit is not run content. */
1733
+ const runAtUnit = (items, unit, insideRemovedRevision) => {
1734
+ let position = 0;
1735
+ for (const [index, item] of items.entries()) {
1736
+ const width = inlineWidth(item);
1737
+ const start = position;
1738
+ position += width;
1739
+ if (unit < start || unit >= position) continue;
1740
+ if (item.type === "run") return {
1741
+ path: [index],
1742
+ run: item,
1743
+ runOffset: unit - start,
1744
+ insideRemovedRevision
1745
+ };
1746
+ if (isInlineContainer(item)) {
1747
+ const hit = runAtUnit(childrenOf(item), unit - start, insideRemovedRevision || isRemovedRevision(item));
1748
+ return hit === void 0 ? void 0 : {
1749
+ ...hit,
1750
+ path: [index, ...hit.path]
1751
+ };
1752
+ }
1753
+ return;
1754
+ }
1755
+ };
1756
+ /**
1757
+ * The run inserted text joins: the one holding the unit before the position,
1758
+ * else the one holding the unit after it, skipping runs inside tracked
1759
+ * deletions and moved-away content.
1760
+ */
1761
+ const insertionHost = (items, offset) => {
1762
+ const before = offset > 0 ? runAtUnit(items, offset - 1, false) : void 0;
1763
+ if (before !== void 0 && !before.insideRemovedRevision) return {
1764
+ path: before.path,
1765
+ run: before.run,
1766
+ runOffset: before.runOffset + 1
1767
+ };
1768
+ const after = runAtUnit(items, offset, false);
1769
+ if (after !== void 0 && !after.insideRemovedRevision) return {
1770
+ path: after.path,
1771
+ run: after.run,
1772
+ runOffset: after.runOffset
1773
+ };
1774
+ };
1775
+ /** Replace the child at `path` with `replacement`. */
1776
+ const replaceAtPath = (items, path, replacement) => {
1777
+ const [index, ...rest] = path;
1778
+ if (index === void 0) return [...replacement];
1779
+ const out = [...items];
1780
+ if (rest.length === 0) {
1781
+ out.splice(index, 1, ...replacement);
1782
+ return out;
1783
+ }
1784
+ const item = items[index];
1785
+ if (item === void 0 || !isInlineContainer(item)) return panic(`Inline path step ${index} does not name a container.`);
1786
+ out[index] = withChildren(item, replaceAtPath(childrenOf(item), rest, replacement));
1787
+ return out;
1788
+ };
1789
+ /**
1790
+ * The run with text added at a unit offset, joining the text node there when
1791
+ * one does. An empty text node is a zero-width child of its own and is left
1792
+ * as it is.
1793
+ */
1794
+ const runWithText = (run, runOffset, text) => {
1795
+ let position = 0;
1796
+ let insertAt = 0;
1797
+ for (const [index, child] of run.content.entries()) {
1798
+ const width = runContentWidth(child);
1799
+ if (child.type === "text" && width > 0 && position <= runOffset && runOffset <= position + width) {
1800
+ const cut = runOffset - position;
1801
+ const content = [...run.content];
1802
+ content[index] = {
1803
+ ...child,
1804
+ text: child.text.slice(0, cut) + text + child.text.slice(cut)
1805
+ };
1806
+ return withRunContent(run, content);
1807
+ }
1808
+ position += width;
1809
+ if (position <= runOffset) insertAt = index + 1;
1810
+ }
1811
+ const content = [...run.content];
1812
+ content.splice(insertAt, 0, {
1813
+ type: "text",
1814
+ text
1815
+ });
1816
+ return withRunContent(run, content);
1817
+ };
1818
+ /**
1819
+ * Put a new run at a position that no run holds; `undefined` when the position
1820
+ * is inside tracked-deleted or moved-away content.
1821
+ */
1822
+ const insertRunAtSlot = (items, offset, run) => {
1823
+ let position = 0;
1824
+ let insertAt = 0;
1825
+ for (const [index, item] of items.entries()) {
1826
+ const width = inlineWidth(item);
1827
+ const start = position;
1828
+ position += width;
1829
+ if (start < offset && offset < position && isInlineContainer(item)) {
1830
+ if (isRemovedRevision(item)) return;
1831
+ const children = insertRunAtSlot(childrenOf(item), offset - start, run);
1832
+ if (children === void 0) return;
1833
+ const out = [...items];
1834
+ out[index] = withChildren(item, children);
1835
+ return out;
1836
+ }
1837
+ if (position <= offset) insertAt = index + 1;
1838
+ }
1839
+ const out = [...items];
1840
+ out.splice(insertAt, 0, run);
1841
+ return out;
1842
+ };
1843
+ /**
1844
+ * Insert text at a position; `undefined` when the position is inside
1845
+ * tracked-deleted or moved-away content and no other run borders it.
1846
+ */
1847
+ const insertTextInContent = (items, offset, text, runProps) => {
1848
+ const host = insertionHost(items, offset);
1849
+ const formatting = runProps === "inherit" ? void 0 : runProps;
1850
+ if (host === void 0) return insertRunAtSlot(items, offset, newTextRun(text, formatting));
1851
+ if (formatting === void 0 || sameRunFormatting(formatting, host.run.formatting)) return replaceAtPath(items, host.path, [runWithText(host.run, host.runOffset, text)]);
1852
+ const halves = splitRun(host.run, host.runOffset);
1853
+ const replacement = [];
1854
+ if (halves.left !== void 0) replacement.push(halves.left);
1855
+ replacement.push(newTextRun(text, formatting));
1856
+ if (halves.right !== void 0) replacement.push(halves.right);
1857
+ return replaceAtPath(items, host.path, replacement);
1858
+ };
1859
+ const patchRunsIn = (nodes, patch, whenEmpty, prior) => {
1860
+ const out = [];
1861
+ for (const node of nodes) {
1862
+ if (node.type === "run") {
1863
+ const formatting = patchedSet(node.formatting, patch, whenEmpty);
1864
+ if (runWidth(node) === 0 || sameRunFormatting(formatting, node.formatting)) {
1865
+ out.push(node);
1866
+ continue;
1867
+ }
1868
+ const run = withRunFormatting(node, formatting);
1869
+ prior.set(run, node.formatting);
1870
+ out.push(run);
1871
+ continue;
1872
+ }
1873
+ if (isParagraphContent(node) && isInlineContainer(node)) {
1874
+ const children = childrenOf(node);
1875
+ const next = patchRunsIn(children, patch, whenEmpty, prior);
1876
+ const same = next.every((child, index) => child === children[index]);
1877
+ out.push(same ? node : withChildren(node, asParagraphContent(next)));
1878
+ continue;
1879
+ }
1880
+ out.push(node);
1881
+ }
1882
+ return out;
1883
+ };
1884
+ const collectRuns = (nodes, out) => {
1885
+ for (const node of nodes) {
1886
+ if (node.type === "run") {
1887
+ if (runWidth(node) > 0) out.push(node);
1888
+ continue;
1889
+ }
1890
+ if (isParagraphContent(node) && isInlineContainer(node)) collectRuns(childrenOf(node), out);
1891
+ }
1892
+ };
1893
+ /** The runs a patch between two gaps reaches, cut at the gaps: those with units there. */
1894
+ const runsBetween = (items, from, to) => {
1895
+ const [, middle = []] = partitionContent(items, [from, to]);
1896
+ const out = [];
1897
+ collectRuns(middle, out);
1898
+ return out;
1899
+ };
1900
+ /**
1901
+ * Patch the run properties of every run between two gaps, cutting runs at the
1902
+ * gaps. A run the patch leaves as it was is not cut. `undefined` when no run
1903
+ * changes.
1904
+ *
1905
+ * `restoring` gives the changed runs back the values the patch replaced, one
1906
+ * patch per stretch of adjacent runs that had the same values. A run the
1907
+ * patch left alone ends a stretch, so a restoring patch never reaches it.
1908
+ */
1909
+ const patchRunsBetween = (items, from, to, patch, whenEmpty) => {
1910
+ const gaps = [from, to];
1911
+ const [before = [], middle = [], after = []] = partitionContent(items, gaps);
1912
+ const prior = /* @__PURE__ */ new Map();
1913
+ const patchedMiddle = patchRunsIn(middle, patch, whenEmpty, prior);
1914
+ if (prior.size === 0) return;
1915
+ const alike = { mode: "asFarAsAlike" };
1916
+ const content = asParagraphContent(mergeLists(mergeLists(before, patchedMiddle, spanningRecords(items, gaps, 0, 1).length, alike) ?? [], after, spanningRecords(items, gaps, 1, 2).length, alike) ?? []);
1917
+ const restoring = [];
1918
+ let stretchOpen = false;
1919
+ for (const { node, before: start, after: end } of runGaps(content)) {
1920
+ if (node.type !== "run") continue;
1921
+ if (!prior.has(node)) {
1922
+ if (runWidth(node) > 0) stretchOpen = false;
1923
+ continue;
1924
+ }
1925
+ const previous = prior.get(node);
1926
+ const restore = priorValues(previous, patch);
1927
+ const spelling = emptySetSpelling(previous);
1928
+ const key = JSON.stringify([restore, spelling]);
1929
+ const last = restoring.at(-1);
1930
+ if (stretchOpen && last !== void 0 && last.key === key) last.to = end;
1931
+ else restoring.push({
1932
+ from: start,
1933
+ to: end,
1934
+ patch: restore,
1935
+ whenEmpty: spelling,
1936
+ key
1937
+ });
1938
+ stretchOpen = true;
1939
+ }
1940
+ return {
1941
+ content,
1942
+ restoring: restoring.map(({ from: start, to: end, patch: restore, whenEmpty: spelling }) => ({
1943
+ from: start,
1944
+ to: end,
1945
+ patch: restore,
1946
+ whenEmpty: spelling
1947
+ }))
1948
+ };
1949
+ };
1950
+ //#endregion
1951
+ //#region src/ops/apply.ts
1952
+ /**
1953
+ * Apply a document operation and record its exact inverse.
1954
+ *
1955
+ * `applyDocumentOp` is total: it returns the new document or a typed refusal,
1956
+ * and a refused operation changes nothing. It is deterministic: no clock, no
1957
+ * randomness and no counter outside its inputs, so equal documents and equal
1958
+ * operations give equal results in any realm, whether or not their records
1959
+ * share objects. It is local: every block the operation does not name is the
1960
+ * same object in the output as in the input, and so is every package part
1961
+ * other than the story it edits. It applies only to a document that meets
1962
+ * the seed contract (`contract.ts`), and leaves the contract holding.
1963
+ *
1964
+ * The inverse is a list of ordinary operations, addressed by position like
1965
+ * the one it undoes, captured from the state the operation changed:
1966
+ *
1967
+ * | operation | inverse |
1968
+ * | ------------------- | --------------------------------------------------------- |
1969
+ * | `insertText` | `deleteRange` (its `join` merges a run the text cut) |
1970
+ * | `insertContent` | `deleteRange` (its `join` merges the records the cut left) |
1971
+ * | `deleteRange` | `insertContent` with the removed slice |
1972
+ * | `splitInline` | `joinInline` |
1973
+ * | `joinInline` | `splitInline` |
1974
+ * | `setRunProps` | `setRunProps` per stretch of prior values, joining cuts |
1975
+ * | `setParagraphProps` | `setParagraphProps` with the prior values |
1976
+ * | `splitBlock` | `joinBlocks` |
1977
+ * | `joinBlocks` | `splitBlock` with the second paragraph's fields |
1978
+ * | `replaceBlocks` | `replaceBlocks` |
1979
+ *
1980
+ * Each inverse carries its precondition: a deletion the slice it removes, a
1981
+ * patch the values it replaces, a join the fields of the paragraph it merges
1982
+ * away. An inverse applied to content that has changed since is refused as
1983
+ * stale. An inverse that cuts records apart again names the ids its forward
1984
+ * operation retired.
1985
+ */
1986
+ const UNTOUCHED = Object.freeze({
1987
+ modified: [],
1988
+ inserted: [],
1989
+ removed: []
1990
+ });
1991
+ const unchanged = (document) => Result.ok({
1992
+ document,
1993
+ inverse: [],
1994
+ touched: UNTOUCHED
1995
+ });
1996
+ const refusal = (op, reason, message) => new DocumentOpRefusal({
1997
+ message,
1998
+ reason,
1999
+ opType: op.type
2000
+ });
2001
+ const refuse = (op, reason, message) => Result.err(refusal(op, reason, message));
2002
+ /** Characters `insertText` does not carry: each is an inline atom of its own. */
2003
+ const NON_TEXT_CHARACTER_PATTERN = /[\t\n\r]/u;
2004
+ const isHighSurrogate = (code) => code >= 55296 && code <= 56319;
2005
+ const isLowSurrogate = (code) => code >= 56320 && code <= 57343;
2006
+ /** The paragraph carrying an id, compared as hex; the contract makes it unique. */
2007
+ const findParagraph = (op, paragraphs, blockId) => {
2008
+ const key = idKey(blockId);
2009
+ const match = paragraphs.find(({ paragraph }) => idKey(paragraph.paraId ?? "") === key);
2010
+ return match === void 0 ? Result.err(refusal(op, DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND, `No paragraph is ${blockId}.`)) : Result.ok(match);
2011
+ };
2012
+ const locate = (document, op, story, blockId) => findParagraph(op, storyParagraphs(storyBody(document, story)), blockId);
2013
+ /** The gap a position names, or why it names none in this paragraph. */
2014
+ const resolveGap = (paragraph, position, fallback) => {
2015
+ const text = paragraphLogicalText(paragraph);
2016
+ const { offset, zeroWidthBefore } = position;
2017
+ if (!Number.isInteger(offset) || offset < 0 || offset > text.length) return DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET;
2018
+ if (offset > 0 && offset < text.length && isHighSurrogate(text.charCodeAt(offset - 1)) && isLowSurrogate(text.charCodeAt(offset))) return DOCUMENT_OP_REFUSAL_REASONS.SPLITS_SURROGATE_PAIR;
2019
+ const available = zeroWidthLeavesAt(paragraph.content, offset).length;
2020
+ if (zeroWidthBefore !== void 0) return Number.isInteger(zeroWidthBefore) && zeroWidthBefore >= 0 && zeroWidthBefore <= available ? {
2021
+ offset,
2022
+ zeroWidthBefore
2023
+ } : DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET;
2024
+ switch (fallback) {
2025
+ case "afterAll": return {
2026
+ offset,
2027
+ zeroWidthBefore: available
2028
+ };
2029
+ case "beforeAll": return {
2030
+ offset,
2031
+ zeroWidthBefore: 0
2032
+ };
2033
+ case "insertion": return defaultInsertionGap(paragraph.content, offset);
2034
+ default: return fallback;
2035
+ }
2036
+ };
2037
+ const isGap = (value) => typeof value === "object";
2038
+ /**
2039
+ * A range of one paragraph. Absent `zeroWidthBefore` leaves the zero-width
2040
+ * leaves at both ends outside the range.
2041
+ */
2042
+ const locateRange = (document, op, from, to) => {
2043
+ if (from.story !== to.story || idKey(from.blockId) !== idKey(to.blockId)) return Result.err(refusal(op, DOCUMENT_OP_REFUSAL_REASONS.CROSS_BLOCK_RANGE, "A range starts and ends in one paragraph."));
2044
+ const located = locate(document, op, from.story, from.blockId);
2045
+ if (located.isErr()) return Result.err(located.error);
2046
+ const { paragraph } = located.value;
2047
+ const start = resolveGap(paragraph, from, "afterAll");
2048
+ const end = resolveGap(paragraph, to, "beforeAll");
2049
+ const invalid = (reason) => Result.err(refusal(op, reason, `[${from.offset}, ${to.offset}) is not a range of ${from.blockId}.`));
2050
+ if (!isGap(start)) return invalid(start);
2051
+ if (!isGap(end)) return invalid(end);
2052
+ const statesZeroWidth = from.zeroWidthBefore !== void 0 || to.zeroWidthBefore !== void 0;
2053
+ if (start.offset > end.offset || start.offset === end.offset && start.zeroWidthBefore > end.zeroWidthBefore && statesZeroWidth) return invalid(DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET);
2054
+ const empty = start.offset === end.offset && start.zeroWidthBefore >= end.zeroWidthBefore;
2055
+ return Result.ok({
2056
+ story: from.story,
2057
+ location: located.value,
2058
+ from: start,
2059
+ to: end,
2060
+ empty
2061
+ });
2062
+ };
2063
+ const locatePosition = (document, op, at, fallback) => {
2064
+ const located = locate(document, op, at.story, at.blockId);
2065
+ if (located.isErr()) return Result.err(located.error);
2066
+ const gap = resolveGap(located.value.paragraph, at, fallback);
2067
+ if (!isGap(gap)) return Result.err(refusal(op, gap, `${at.offset} is not a position in ${at.blockId}.`));
2068
+ return Result.ok({
2069
+ location: located.value,
2070
+ gap
2071
+ });
2072
+ };
2073
+ /** A position naming its paragraph by the id the paragraph carries. */
2074
+ const positionAt = (story, paragraph, gap) => ({
2075
+ story,
2076
+ blockId: paragraph.paraId ?? "",
2077
+ offset: gap.offset,
2078
+ zeroWidthBefore: gap.zeroWidthBefore
2079
+ });
2080
+ const touchedBetween = (before, after) => {
2081
+ const beforeIds = before.flatMap(({ paraId }) => paraId === void 0 ? [] : [paraId]);
2082
+ const afterIds = after.flatMap(({ paraId }) => paraId === void 0 ? [] : [paraId]);
2083
+ const afterKeys = new Set(afterIds.map(idKey));
2084
+ const beforeKeys = new Set(beforeIds.map(idKey));
2085
+ return {
2086
+ modified: beforeIds.filter((id) => afterKeys.has(idKey(id))),
2087
+ inserted: afterIds.filter((id) => !beforeKeys.has(idKey(id))),
2088
+ removed: beforeIds.filter((id) => !afterKeys.has(idKey(id)))
2089
+ };
2090
+ };
2091
+ /** Revision and control ids the package uses outside `before`. */
2092
+ const identitiesOutside = (document, before) => {
2093
+ const counts = countKeys(packageIdentityKeys(document.package));
2094
+ for (const key of identityKeysIn(before)) counts.set(key, (counts.get(key) ?? 1) - 1);
2095
+ return new Set([...counts].flatMap(([key, count]) => count > 0 ? [key] : []));
2096
+ };
2097
+ /** `after` with the records the edit would leave sharing an id given the operation's new ids. */
2098
+ const withFreshIds = ({ document, op, before, after, newIds, inserted }) => {
2099
+ const freshened = freshenIdentities({
2100
+ before,
2101
+ after,
2102
+ newIds: newIds ?? {},
2103
+ usedElsewhere: () => identitiesOutside(document, before),
2104
+ ...inserted === void 0 ? {} : { inserted }
2105
+ });
2106
+ switch (freshened.kind) {
2107
+ case "needsIds": return Result.err(refusal(op, DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS, `The edit cuts records carrying ids and needs ${freshened.missing} more new ids.`));
2108
+ case "invalidId": return Result.err(refusal(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID, `${freshened.id} cannot be a new revision or content-control id here.`));
2109
+ case "fresh": return Result.ok(freshened.paragraphs);
2110
+ default: return freshened;
2111
+ }
2112
+ };
2113
+ /** Put `after` where `before` stands, its records given fresh ids where they need them. */
2114
+ const commit = (options) => {
2115
+ const paragraphs = withFreshIds(options);
2116
+ if (paragraphs.isErr()) return Result.err(paragraphs.error);
2117
+ const { document, story, at, before } = options;
2118
+ return Result.ok({
2119
+ document: replaceParagraphs({
2120
+ document,
2121
+ story,
2122
+ at,
2123
+ count: before.length,
2124
+ replacement: paragraphs.value
2125
+ }),
2126
+ paragraphs: paragraphs.value,
2127
+ touched: touchedBetween(before, paragraphs.value)
2128
+ });
2129
+ };
2130
+ const withContent = (paragraph, content) => content === paragraph.content ? paragraph : {
2131
+ ...paragraph,
2132
+ content: [...content]
2133
+ };
2134
+ /** An edit of one paragraph, committed, with the inverse built from the paragraph it became. */
2135
+ const editOne = (commitOptions, inverseOf) => {
2136
+ const { paragraph, at, document } = commitOptions;
2137
+ if (paragraph === at.paragraph) return unchanged(document);
2138
+ const committed = commit({
2139
+ ...commitOptions,
2140
+ before: [at.paragraph],
2141
+ after: [paragraph]
2142
+ });
2143
+ if (committed.isErr()) return Result.err(committed.error);
2144
+ const [result] = committed.value.paragraphs;
2145
+ if (result === void 0) return Result.ok({
2146
+ document: committed.value.document,
2147
+ inverse: [],
2148
+ touched: UNTOUCHED
2149
+ });
2150
+ const inverse = inverseOf(result);
2151
+ if (inverse.isErr()) return Result.err(inverse.error);
2152
+ return Result.ok({
2153
+ document: committed.value.document,
2154
+ inverse: inverse.value,
2155
+ touched: committed.value.touched
2156
+ });
2157
+ };
2158
+ /** Commit an insertion, recording the one deletion that undoes it. */
2159
+ const inserted = ({ document, op, story, location, content, start, end, newIds }) => editOne({
2160
+ document,
2161
+ op,
2162
+ story,
2163
+ at: location,
2164
+ paragraph: withContent(location.paragraph, content),
2165
+ newIds,
2166
+ inserted: recordsBetween(content, start, end)
2167
+ }, (result) => {
2168
+ const inverse = insertionInverse(location.paragraph.content, result.content, start, end);
2169
+ if (inverse === void 0) return Result.err(refusal(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "The insertion would merge records that were separate."));
2170
+ const deletion = {
2171
+ type: DOCUMENT_OP_TYPES.DELETE_RANGE,
2172
+ from: positionAt(story, result, start),
2173
+ to: positionAt(story, result, end),
2174
+ expected: inverse.removed
2175
+ };
2176
+ if (inverse.join > 0) deletion.join = inverse.join;
2177
+ return Result.ok([deletion]);
2178
+ });
2179
+ const insertText = (document, op) => {
2180
+ if (op.text === "" || NON_TEXT_CHARACTER_PATTERN.test(op.text) || hasIllegalXmlCharacters(op.text)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_TEXT, "The text cannot be inserted.");
2181
+ const located = locatePosition(document, op, op.at, "afterAll");
2182
+ if (located.isErr()) return Result.err(located.error);
2183
+ const { location } = located.value;
2184
+ const { offset } = op.at;
2185
+ const content = insertTextInContent(location.paragraph.content, offset, op.text, op.runProps);
2186
+ if (content === void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INSIDE_TRACKED_DELETION, `${offset} in ${op.at.blockId} is inside tracked-removed content.`);
2187
+ const start = {
2188
+ offset,
2189
+ zeroWidthBefore: zeroWidthLeavesAt(content, offset).length
2190
+ };
2191
+ const end = {
2192
+ offset: offset + op.text.length,
2193
+ zeroWidthBefore: 0
2194
+ };
2195
+ return inserted({
2196
+ document,
2197
+ op,
2198
+ story: op.at.story,
2199
+ location,
2200
+ content,
2201
+ start,
2202
+ end,
2203
+ newIds: op.newIds
2204
+ });
2205
+ };
2206
+ const holdsEmptyRecord = (nodes) => nodes.some((node) => isEmptyRecord(node) || holdsEmptyRecord(childNodes(node) ?? []));
2207
+ const insertContent = (document, op) => {
2208
+ const slice = {
2209
+ ...op.slice,
2210
+ content: structuredClone(op.slice.content)
2211
+ };
2212
+ if (slice.content.length === 0 || holdsEmptyRecord(slice.content)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT, "The slice holds nothing, or an empty run or text node.");
2213
+ if (!Number.isInteger(slice.openStart) || !Number.isInteger(slice.openEnd) || slice.openStart < 0 || slice.openEnd < 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "Open depths are counts.");
2214
+ if (textsIn(slice.content).some(hasIllegalXmlCharacters)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_TEXT, "The slice holds text that cannot be written.");
2215
+ const incoming = paragraphIdsIn(slice.content);
2216
+ if (incoming.length > 0 && collides(countIds(packageParagraphIds(document.package)), incoming)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "The slice holds a paragraph id the package already uses.");
2217
+ const located = locatePosition(document, op, op.at, "insertion");
2218
+ if (located.isErr()) return Result.err(located.error);
2219
+ const { location, gap } = located.value;
2220
+ const content = insertSliceAt(location.paragraph.content, gap, slice);
2221
+ if (content === void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, `The slice's open ends do not fit ${op.at.offset} in ${op.at.blockId}.`);
2222
+ return inserted({
2223
+ document,
2224
+ op,
2225
+ story: op.at.story,
2226
+ location,
2227
+ content,
2228
+ start: gap,
2229
+ end: gapAfterInserted(gap, slice.content),
2230
+ newIds: op.newIds
2231
+ });
2232
+ };
2233
+ /** A merge's content, or the refusal naming why it cannot be made. */
2234
+ const joinedContent = (op, joined, where) => {
2235
+ switch (joined.kind) {
2236
+ case "joined": return Result.ok({
2237
+ content: joined.content,
2238
+ retired: joined.retired
2239
+ });
2240
+ case "notAlike": return Result.err(refusal(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, `The records meeting ${where} cannot be merged.`));
2241
+ case "sharedId": return Result.err(refusal(op, DOCUMENT_OP_REFUSAL_REASONS.SHARED_ID, `The records meeting ${where} carry the same id.`));
2242
+ default: return joined;
2243
+ }
2244
+ };
2245
+ const isCount = (value) => Number.isInteger(value) && value >= 0;
2246
+ const deleteRange = (document, op) => {
2247
+ const join = op.join ?? 0;
2248
+ if (!isCount(join)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
2249
+ const located = locateRange(document, op, op.from, op.to);
2250
+ if (located.isErr()) return Result.err(located.error);
2251
+ const { story, location, from, to, empty } = located.value;
2252
+ const { expected } = op;
2253
+ if (empty) return expected === void 0 || expected.content.length === 0 ? unchanged(document) : refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, "The range to delete is empty.");
2254
+ const { paragraph } = location;
2255
+ const { content: remaining, removed } = deleteBetween(paragraph.content, from, to);
2256
+ if (expected !== void 0 && !equalForStaleness(expected, removed)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `The range of ${op.from.blockId} holds other content than expected.`);
2257
+ if (removed.content.length === 0) return unchanged(document);
2258
+ let content = remaining;
2259
+ let retired = {};
2260
+ if (join > 0) {
2261
+ const joined = joinedContent(op, joinAt(remaining, from, join), `at ${from.offset}`);
2262
+ if (joined.isErr()) return Result.err(joined.error);
2263
+ ({content, retired} = joined.value);
2264
+ }
2265
+ return editOne({
2266
+ document,
2267
+ op,
2268
+ story,
2269
+ at: location,
2270
+ paragraph: withContent(paragraph, content),
2271
+ newIds: void 0
2272
+ }, (result) => {
2273
+ const insertion = {
2274
+ type: DOCUMENT_OP_TYPES.INSERT_CONTENT,
2275
+ at: positionAt(story, result, from),
2276
+ slice: removed
2277
+ };
2278
+ if (namesIds(retired)) insertion.newIds = retired;
2279
+ return Result.ok([insertion]);
2280
+ });
2281
+ };
2282
+ const splitInline = (document, op) => {
2283
+ if (!isCount(op.depth) || op.depth === 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A split cuts one level or more.");
2284
+ const located = locatePosition(document, op, op.at, "beforeAll");
2285
+ if (located.isErr()) return Result.err(located.error);
2286
+ const { location, gap } = located.value;
2287
+ const content = splitAt(location.paragraph.content, gap, op.depth);
2288
+ if (content === void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, `Fewer than ${op.depth} records run across ${op.at.offset} in ${op.at.blockId}.`);
2289
+ return editOne({
2290
+ document,
2291
+ op,
2292
+ story: op.at.story,
2293
+ at: location,
2294
+ paragraph: withContent(location.paragraph, content),
2295
+ newIds: op.newIds
2296
+ }, (result) => Result.ok([{
2297
+ type: DOCUMENT_OP_TYPES.JOIN_INLINE,
2298
+ at: positionAt(op.at.story, result, gap),
2299
+ depth: op.depth
2300
+ }]));
2301
+ };
2302
+ const joinInline = (document, op) => {
2303
+ if (!isCount(op.depth) || op.depth === 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join merges one level or more.");
2304
+ const located = locatePosition(document, op, op.at, "beforeAll");
2305
+ if (located.isErr()) return Result.err(located.error);
2306
+ const { location, gap } = located.value;
2307
+ const joined = joinedContent(op, joinAt(location.paragraph.content, gap, op.depth), `at ${op.at.offset} in ${op.at.blockId}`);
2308
+ if (joined.isErr()) return Result.err(joined.error);
2309
+ const { content, retired } = joined.value;
2310
+ return editOne({
2311
+ document,
2312
+ op,
2313
+ story: op.at.story,
2314
+ at: location,
2315
+ paragraph: withContent(location.paragraph, content),
2316
+ newIds: void 0
2317
+ }, (result) => {
2318
+ const split = {
2319
+ type: DOCUMENT_OP_TYPES.SPLIT_INLINE,
2320
+ at: positionAt(op.at.story, result, gap),
2321
+ depth: op.depth
2322
+ };
2323
+ if (namesIds(retired)) split.newIds = retired;
2324
+ return Result.ok([split]);
2325
+ });
2326
+ };
2327
+ /** Whether a property set states each key of `expected` as it says (`null`: absent). */
2328
+ const statesValues = (formatting, expected) => {
2329
+ const values = new Map(Object.entries(formatting ?? {}));
2330
+ return Object.entries(expected).every(([key, value]) => value === void 0 || structurallyEqual(values.get(key) ?? null, value));
2331
+ };
2332
+ const setRunProps = (document, op) => {
2333
+ const joinStart = op.joinStart ?? 0;
2334
+ const joinEnd = op.joinEnd ?? 0;
2335
+ if (!isCount(joinStart) || !isCount(joinEnd)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
2336
+ const located = locateRange(document, op, op.from, op.to);
2337
+ if (located.isErr()) return Result.err(located.error);
2338
+ const { story, location, from, to, empty } = located.value;
2339
+ if (empty) return unchanged(document);
2340
+ const { paragraph } = location;
2341
+ const { expected } = op;
2342
+ if (expected !== void 0 && !runsBetween(paragraph.content, from, to).every((run) => statesValues(run.formatting, expected))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `The runs of ${op.from.blockId} state other values than expected.`);
2343
+ const patched = patchRunsBetween(paragraph.content, from, to, op.patch, op.whenEmpty);
2344
+ const patchedContent = patched?.content ?? paragraph.content;
2345
+ const freshened = withFreshIds({
2346
+ document,
2347
+ op,
2348
+ before: [paragraph],
2349
+ after: [withContent(paragraph, patchedContent)],
2350
+ newIds: op.newIds
2351
+ });
2352
+ if (freshened.isErr()) return Result.err(freshened.error);
2353
+ let content = freshened.value[0]?.content ?? patchedContent;
2354
+ const retiredAt = {
2355
+ from: {},
2356
+ to: {}
2357
+ };
2358
+ for (const [gap, depth, side] of [[
2359
+ from,
2360
+ joinStart,
2361
+ "from"
2362
+ ], [
2363
+ to,
2364
+ joinEnd,
2365
+ "to"
2366
+ ]]) {
2367
+ if (depth === 0) continue;
2368
+ const joined = joinedContent(op, joinAt(content, gap, depth), `at ${gap.offset}`);
2369
+ if (joined.isErr()) return Result.err(joined.error);
2370
+ content = joined.value.content;
2371
+ retiredAt[side] = joined.value.retired;
2372
+ }
2373
+ const result = withContent(paragraph, content);
2374
+ if (structurallyEqual(result.content, paragraph.content)) return unchanged(document);
2375
+ const inverse = (patched?.restoring ?? []).map((span) => ({
2376
+ type: DOCUMENT_OP_TYPES.SET_RUN_PROPS,
2377
+ from: positionAt(story, result, span.from),
2378
+ to: positionAt(story, result, span.to),
2379
+ patch: span.patch,
2380
+ whenEmpty: span.whenEmpty,
2381
+ expected: op.patch
2382
+ }));
2383
+ const cutAtGap = (gap) => spanningRecords(paragraph.content, [gap], 0, 1).length - spanningRecords(content, [gap], 0, 1).length;
2384
+ const first = inverse.at(0);
2385
+ const last = inverse.at(-1);
2386
+ if (first !== void 0 && last !== void 0) {
2387
+ const cutFrom = cutAtGap(from);
2388
+ const cutTo = cutAtGap(to);
2389
+ if (cutFrom > 0) first.joinStart = cutFrom;
2390
+ if (cutTo > 0) last.joinEnd = cutTo;
2391
+ if (namesIds(retiredAt.from)) first.newIds = concatIds(first.newIds ?? {}, retiredAt.from);
2392
+ if (namesIds(retiredAt.to)) last.newIds = concatIds(last.newIds ?? {}, retiredAt.to);
2393
+ }
2394
+ return Result.ok({
2395
+ document: replaceParagraphs({
2396
+ document,
2397
+ story,
2398
+ at: location,
2399
+ count: 1,
2400
+ replacement: [result]
2401
+ }),
2402
+ inverse,
2403
+ touched: touchedBetween([paragraph], [result])
2404
+ });
2405
+ };
2406
+ const withParagraphFormatting = (paragraph, formatting) => {
2407
+ const next = { ...paragraph };
2408
+ if (formatting === void 0) delete next.formatting;
2409
+ else next.formatting = formatting;
2410
+ return next;
2411
+ };
2412
+ const setParagraphProps = (document, op) => {
2413
+ const located = locate(document, op, op.story, op.blockId);
2414
+ if (located.isErr()) return Result.err(located.error);
2415
+ const { paragraph } = located.value;
2416
+ if (op.expected !== void 0 && !statesValues(paragraph.formatting, op.expected)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${op.blockId} states other paragraph properties than expected.`);
2417
+ const formatting = patchedSet(paragraph.formatting, op.patch, op.whenEmpty);
2418
+ if (structurallyEqual(formatting ?? {}, paragraph.formatting ?? {})) return unchanged(document);
2419
+ return editOne({
2420
+ document,
2421
+ op,
2422
+ story: op.story,
2423
+ at: located.value,
2424
+ paragraph: withParagraphFormatting(paragraph, formatting),
2425
+ newIds: void 0
2426
+ }, (result) => Result.ok([{
2427
+ type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_PROPS,
2428
+ story: op.story,
2429
+ blockId: result.paraId ?? op.blockId,
2430
+ patch: priorValues(paragraph.formatting, op.patch),
2431
+ whenEmpty: emptySetSpelling(paragraph.formatting),
2432
+ expected: op.patch
2433
+ }]));
2434
+ };
2435
+ /** The fields of a paragraph a split gives the new half: all but its id, content and mark. */
2436
+ const splitFieldsOf = (paragraph) => {
2437
+ const fields = { ...paragraph };
2438
+ delete fields.type;
2439
+ delete fields.paraId;
2440
+ delete fields.content;
2441
+ delete fields.sectionProperties;
2442
+ delete fields.pPrMark;
2443
+ return fields;
2444
+ };
2445
+ const splitBlock = (document, op) => {
2446
+ if (!isParaId(op.newBlockId)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, `${op.newBlockId} is not a paragraph id.`);
2447
+ if (collides(countIds(packageParagraphIds(document.package)), [op.newBlockId])) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, `${op.newBlockId} is already used in the package.`);
2448
+ const located = locatePosition(document, op, op.at, "insertion");
2449
+ if (located.isErr()) return Result.err(located.error);
2450
+ const { location, gap } = located.value;
2451
+ const { paragraph } = location;
2452
+ const cut = cutAt(paragraph.content, gap);
2453
+ const first = {
2454
+ ...paragraph,
2455
+ content: cut.before
2456
+ };
2457
+ delete first.sectionProperties;
2458
+ delete first.pPrMark;
2459
+ if (op.firstMark !== void 0) first.pPrMark = op.firstMark;
2460
+ const second = {
2461
+ ...op.newParagraph ?? (paragraph.formatting === void 0 ? {} : { formatting: paragraph.formatting }),
2462
+ type: "paragraph",
2463
+ paraId: op.newBlockId,
2464
+ content: cut.after
2465
+ };
2466
+ if (paragraph.sectionProperties !== void 0) second.sectionProperties = paragraph.sectionProperties;
2467
+ if (paragraph.pPrMark !== void 0) second.pPrMark = paragraph.pPrMark;
2468
+ const committed = commit({
2469
+ document,
2470
+ op,
2471
+ story: op.at.story,
2472
+ at: location,
2473
+ before: [paragraph],
2474
+ after: [first, second],
2475
+ newIds: op.newIds
2476
+ });
2477
+ if (committed.isErr()) return Result.err(committed.error);
2478
+ const [, placedSecond] = committed.value.paragraphs;
2479
+ return Result.ok({
2480
+ document: committed.value.document,
2481
+ inverse: [{
2482
+ type: DOCUMENT_OP_TYPES.JOIN_BLOCKS,
2483
+ story: op.at.story,
2484
+ blockId: paragraph.paraId ?? op.at.blockId,
2485
+ nextBlockId: op.newBlockId,
2486
+ depth: cut.through.length,
2487
+ expectedSecond: splitFieldsOf(placedSecond ?? second)
2488
+ }],
2489
+ touched: committed.value.touched
2490
+ });
2491
+ };
2492
+ const joinBlocks = (document, op) => {
2493
+ const paragraphs = storyParagraphs(storyBody(document, op.story));
2494
+ const first = findParagraph(op, paragraphs, op.blockId);
2495
+ if (first.isErr()) return Result.err(first.error);
2496
+ const next = findParagraph(op, paragraphs, op.nextBlockId);
2497
+ if (next.isErr()) return Result.err(next.error);
2498
+ if (!sameBlockList(first.value.list, next.value.list) || next.value.index !== first.value.index + 1) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.NOT_ADJACENT, `${op.nextBlockId} does not directly follow ${op.blockId}.`);
2499
+ const leading = first.value.paragraph;
2500
+ const trailing = next.value.paragraph;
2501
+ if (leading.sectionProperties !== void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.SECTION_BOUNDARY, `${op.blockId} ends a section.`);
2502
+ if (op.expectedSecond !== void 0 && !equalForStaleness({
2503
+ type: "paragraph",
2504
+ ...splitFieldsOf(trailing)
2505
+ }, {
2506
+ type: "paragraph",
2507
+ ...op.expectedSecond
2508
+ })) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${op.nextBlockId} states other fields than expected.`);
2509
+ const trailingId = trailing.paraId ?? "";
2510
+ if (!isParaId(trailingId)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, `${trailingId} could not name the paragraph again.`);
2511
+ const depth = op.depth ?? 0;
2512
+ if (!isCount(depth)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
2513
+ const merged = joinedContent(op, joinContent(leading.content, trailing.content, depth), `between ${op.blockId} and ${op.nextBlockId}`);
2514
+ if (merged.isErr()) return Result.err(merged.error);
2515
+ const joined = {
2516
+ ...leading,
2517
+ content: merged.value.content
2518
+ };
2519
+ delete joined.pPrMark;
2520
+ if (trailing.sectionProperties !== void 0) joined.sectionProperties = trailing.sectionProperties;
2521
+ if (trailing.pPrMark !== void 0) joined.pPrMark = trailing.pPrMark;
2522
+ const length = paragraphLength(leading);
2523
+ const split = {
2524
+ type: DOCUMENT_OP_TYPES.SPLIT_BLOCK,
2525
+ at: {
2526
+ story: op.story,
2527
+ blockId: leading.paraId ?? op.blockId,
2528
+ offset: length,
2529
+ zeroWidthBefore: zeroWidthLeavesAt(leading.content, length).length
2530
+ },
2531
+ newBlockId: trailingId,
2532
+ newParagraph: splitFieldsOf(trailing)
2533
+ };
2534
+ if (leading.pPrMark !== void 0) split.firstMark = leading.pPrMark;
2535
+ if (namesIds(merged.value.retired)) split.newIds = merged.value.retired;
2536
+ const committed = commit({
2537
+ document,
2538
+ op,
2539
+ story: op.story,
2540
+ at: first.value,
2541
+ before: [leading, trailing],
2542
+ after: [joined],
2543
+ newIds: void 0
2544
+ });
2545
+ if (committed.isErr()) return Result.err(committed.error);
2546
+ return Result.ok({
2547
+ document: committed.value.document,
2548
+ inverse: [split],
2549
+ touched: committed.value.touched
2550
+ });
2551
+ };
2552
+ /**
2553
+ * Whether a replacement leaves every section break where it was: the replaced
2554
+ * paragraphs lie in one section (only the last may end it) and the
2555
+ * replacement ends it the same way. Anything else would change the sections
2556
+ * the body is divided into, which is a section operation.
2557
+ */
2558
+ const sameSectionBreaks = (before, after) => {
2559
+ const breaksInside = (paragraphs) => paragraphs.slice(0, -1).some(({ sectionProperties }) => sectionProperties !== void 0);
2560
+ return !breaksInside(before) && !breaksInside(after) && structurallyEqual(before.at(-1)?.sectionProperties, after.at(-1)?.sectionProperties);
2561
+ };
2562
+ const replaceBlocks = (document, op) => {
2563
+ const [firstExpected] = op.expected;
2564
+ if (firstExpected === void 0 || op.blocks.length === 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_BLOCK_LIST, "A replacement names the paragraphs it replaces and the ones it puts in their place.");
2565
+ const paragraphs = storyParagraphs(storyBody(document, op.story));
2566
+ const found = [];
2567
+ for (const expected of op.expected) {
2568
+ if (expected.paraId === void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND, "A replaced paragraph has no id.");
2569
+ const located = findParagraph(op, paragraphs, expected.paraId);
2570
+ if (located.isErr()) return Result.err(located.error);
2571
+ found.push(located.value);
2572
+ }
2573
+ const [start] = found;
2574
+ if (start === void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_BLOCK_LIST, "Nothing to replace.");
2575
+ if (!found.every((location, offset) => sameBlockList(location.list, start.list) && location.index === start.index + offset)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.NOT_ADJACENT, "The replaced paragraphs are not adjacent.");
2576
+ if (found.some((location, offset) => !equalForStaleness(location.paragraph, op.expected[offset]))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, "The paragraphs to replace have changed.");
2577
+ if (op.blocks.some(({ paraId }) => paraId === void 0)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, "A replacement paragraph has no id.");
2578
+ if (op.blocks.some(({ content }) => holdsEmptyRecord(content))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT, "A replacement paragraph holds an empty run or text node.");
2579
+ const before = found.map(({ paragraph }) => paragraph);
2580
+ const kept = new Set(before.map(({ paraId }) => idKey(paraId ?? "")));
2581
+ const placed = new Set(op.blocks.map(({ paraId }) => idKey(paraId ?? "")));
2582
+ if ([...op.blocks.filter(({ paraId }) => !kept.has(idKey(paraId ?? ""))), ...before.filter(({ paraId }) => !placed.has(idKey(paraId ?? "")))].some(({ paraId }) => paraId === void 0 || !isParaId(paraId))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, "A paragraph the replacement adds or removes has no usable id.");
2583
+ if (!sameSectionBreaks(before, op.blocks)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.SECTION_BOUNDARY, "A replacement keeps every section break where it is.");
2584
+ const remaining = countIds(packageParagraphIds(document.package));
2585
+ for (const id of paragraphIdsIn(before)) remaining.set(idKey(id), (remaining.get(idKey(id)) ?? 1) - 1);
2586
+ if (collides(remaining, paragraphIdsIn(op.blocks))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "A replacement paragraph id is already used in the package.");
2587
+ const outside = identitiesOutside(document, before);
2588
+ const incomingRecords = identityKeysIn(op.blocks);
2589
+ if (incomingRecords.some((key) => outside.has(key)) || new Set(incomingRecords).size !== incomingRecords.length) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "A replacement carries a revision or content-control id already used in the package.");
2590
+ return Result.ok({
2591
+ document: replaceParagraphs({
2592
+ document,
2593
+ story: op.story,
2594
+ at: start,
2595
+ count: before.length,
2596
+ replacement: op.blocks
2597
+ }),
2598
+ inverse: [{
2599
+ type: DOCUMENT_OP_TYPES.REPLACE_BLOCKS,
2600
+ story: op.story,
2601
+ expected: op.blocks,
2602
+ blocks: before
2603
+ }],
2604
+ touched: touchedBetween(before, op.blocks)
2605
+ });
2606
+ };
2607
+ const dispatch = (document, op) => {
2608
+ switch (op.type) {
2609
+ case DOCUMENT_OP_TYPES.INSERT_TEXT: return insertText(document, op);
2610
+ case DOCUMENT_OP_TYPES.INSERT_CONTENT: return insertContent(document, op);
2611
+ case DOCUMENT_OP_TYPES.DELETE_RANGE: return deleteRange(document, op);
2612
+ case DOCUMENT_OP_TYPES.SPLIT_INLINE: return splitInline(document, op);
2613
+ case DOCUMENT_OP_TYPES.JOIN_INLINE: return joinInline(document, op);
2614
+ case DOCUMENT_OP_TYPES.SET_RUN_PROPS: return setRunProps(document, op);
2615
+ case DOCUMENT_OP_TYPES.SET_PARAGRAPH_PROPS: return setParagraphProps(document, op);
2616
+ case DOCUMENT_OP_TYPES.SPLIT_BLOCK: return splitBlock(document, op);
2617
+ case DOCUMENT_OP_TYPES.JOIN_BLOCKS: return joinBlocks(document, op);
2618
+ case DOCUMENT_OP_TYPES.REPLACE_BLOCKS: return replaceBlocks(document, op);
2619
+ default: return op;
2620
+ }
2621
+ };
2622
+ /** Apply one operation to a document that meets the seed contract. */
2623
+ const applyDocumentOp = (document, op) => {
2624
+ const valid = validateOpsDocument(document);
2625
+ if (valid.isErr()) return refuse(op, valid.error.reason, valid.error.message);
2626
+ const applied = dispatch(document, op);
2627
+ if (applied.isOk()) meetsContract(applied.value.document);
2628
+ return applied;
2629
+ };
2630
+ const TOUCH_TRANSITIONS = {
2631
+ modified: {
2632
+ modified: "modified",
2633
+ inserted: "modified",
2634
+ removed: "removed"
2635
+ },
2636
+ inserted: {
2637
+ modified: "inserted",
2638
+ inserted: "inserted",
2639
+ removed: void 0
2640
+ },
2641
+ removed: {
2642
+ modified: "modified",
2643
+ inserted: "modified",
2644
+ removed: "removed"
2645
+ }
2646
+ };
2647
+ /**
2648
+ * Apply operations in order, atomically: the first refusal is returned and
2649
+ * the document is unchanged. The inverse undoes the whole list.
2650
+ */
2651
+ const applyDocumentOps = (document, ops) => {
2652
+ let current = document;
2653
+ const inverses = [];
2654
+ const touched = /* @__PURE__ */ new Map();
2655
+ for (const op of ops) {
2656
+ const applied = applyDocumentOp(current, op);
2657
+ if (applied.isErr()) return applied;
2658
+ current = applied.value.document;
2659
+ inverses.push(applied.value.inverse);
2660
+ for (const state of [
2661
+ "modified",
2662
+ "inserted",
2663
+ "removed"
2664
+ ]) for (const id of applied.value.touched[state]) {
2665
+ const previous = touched.get(id);
2666
+ const nextState = previous === void 0 ? state : TOUCH_TRANSITIONS[previous][state];
2667
+ if (nextState === void 0) touched.delete(id);
2668
+ else touched.set(id, nextState);
2669
+ }
2670
+ }
2671
+ const ids = (state) => [...touched].flatMap(([id, value]) => value === state ? [id] : []);
2672
+ return Result.ok({
2673
+ document: current,
2674
+ inverse: inverses.toReversed().flat(),
2675
+ touched: {
2676
+ modified: ids("modified"),
2677
+ inserted: ids("inserted"),
2678
+ removed: ids("removed")
2679
+ }
2680
+ });
2681
+ };
2682
+ //#endregion
2683
+ export { DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, DocumentOpRefusal, DocumentOpsContractError, EMPTY_PROPERTY_SETS, INHERIT_RUN_PROPS, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, applyDocumentOp, applyDocumentOps, normalizeForOps, paragraphLength, paragraphLogicalText, toOpEnvelope, validateOpsDocument };