@stll/docx-core 0.32.0 → 0.33.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.
@@ -1,4 +1,4 @@
1
- import { E as PARAGRAPH_ALIGNMENTS, J as isNumberingLevel, Z as isNumberingReference, a as INSERTION_SEAM_POLICIES, tt as paragraphNumberingReference } from "../document-3WKQA1r3.js";
1
+ import { D as PARAGRAPH_ALIGNMENTS, Q as isNumberingReference, Y as isNumberingLevel, nt as paragraphNumberingReference, o as INSERTION_SEAM_POLICIES, s as MAX_REVISION_ID, t as COMMENT_PART_RELATIONSHIPS } from "../document-CQ0oovh0.js";
2
2
  import { a as hasIllegalXmlCharacters, t as sanitizeExternalUrl } from "../href-2XSCK-T8.js";
3
3
  import { Result, TaggedError, panic } from "better-result";
4
4
  //#region src/ops/equality.ts
@@ -225,10 +225,10 @@ const captureDocumentOp = (op) => {
225
225
  }
226
226
  };
227
227
  visit(op, []);
228
- return fields.length === 0 ? op : {
229
- ...cloneModel(op),
230
- undefinedFields: cloneModel(fields)
231
- };
228
+ if (fields.length === 0) return op;
229
+ const captured = cloneModel(op);
230
+ captured.undefinedFields = cloneModel(fields);
231
+ return captured;
232
232
  };
233
233
  /** Restore validated presence metadata without mutating the supplied operation. */
234
234
  const restoreDocumentOp = (op) => {
@@ -296,7 +296,7 @@ const restoreDocumentOp = (op) => {
296
296
  * and paragraph operations, and the review operations `setParagraphReview`,
297
297
  * `replaceInline` and `resolveRevision`.
298
298
  */
299
- const DOCUMENT_OP_SCHEMA_VERSION = 9;
299
+ const DOCUMENT_OP_SCHEMA_VERSION = 10;
300
300
  /**
301
301
  * The main story has a fixed address; other editable parts use their stable
302
302
  * relationship id or note id. Comment bodies are not yet editable stories.
@@ -321,8 +321,13 @@ const SECTION_BOUNDARY_POLICIES = Object.freeze({
321
321
  REMOVE: "remove",
322
322
  REPLACE: "replace"
323
323
  });
324
- /** The operation kinds of schema version 9. */
324
+ /** The operation kinds of schema version 10. */
325
325
  const DOCUMENT_OP_TYPES = Object.freeze({
326
+ CREATE_COMMENT: "createComment",
327
+ UPDATE_COMMENT_CONTENT: "updateCommentContent",
328
+ SET_COMMENT_RESOLUTION: "setCommentResolution",
329
+ DELETE_COMMENT: "deleteComment",
330
+ RESTORE_COMMENT_STATE: "restoreCommentState",
326
331
  CREATE_HEADER_FOOTER: "createHeaderFooter",
327
332
  REMOVE_HEADER_FOOTER: "removeHeaderFooter",
328
333
  ADD_NOTE: "addNote",
@@ -384,7 +389,7 @@ const REVISION_DECISIONS = Object.freeze({
384
389
  });
385
390
  /** An operation in the envelope it is journaled and sent in. */
386
391
  const toOpEnvelope = (op) => ({
387
- schema: 9,
392
+ schema: 10,
388
393
  op: captureDocumentOp(op)
389
394
  });
390
395
  //#endregion
@@ -2217,6 +2222,28 @@ const captureStoryParts = (document, owned) => {
2217
2222
  if (owned.footnotes !== void 0) parts.footnotes = pkg.footnotes ?? null;
2218
2223
  if (owned.endnotes !== void 0) parts.endnotes = pkg.endnotes ?? null;
2219
2224
  if (owned.settings !== void 0) parts.settings = pkg.settings ?? null;
2225
+ const undefinedFields = [];
2226
+ const bodyKeys = Object.keys(owned.body ?? {}).filter((key) => key in values).filter((key) => Object.hasOwn(body, key) && Reflect.get(body, key) === void 0);
2227
+ if (bodyKeys.length > 0) undefinedFields.push({
2228
+ target: "body",
2229
+ keys: bodyKeys
2230
+ });
2231
+ const packageKeys = Object.keys(owned).filter((key) => key !== "body" && key !== "sections" && key !== "undefinedFields").filter((key) => Object.hasOwn(pkg, key) && Reflect.get(pkg, key) === void 0);
2232
+ if (packageKeys.length > 0) undefinedFields.push({
2233
+ target: "package",
2234
+ keys: packageKeys
2235
+ });
2236
+ for (const fields of owned.sections ?? []) {
2237
+ const section = body.sections?.at(fields.index);
2238
+ if (!section) continue;
2239
+ const keys = Object.keys(fields).filter((key) => key !== "index").filter((key) => Object.hasOwn(section, key) && Reflect.get(section, key) === void 0);
2240
+ if (keys.length > 0) undefinedFields.push({
2241
+ target: "section",
2242
+ index: fields.index,
2243
+ keys
2244
+ });
2245
+ }
2246
+ if (undefinedFields.length > 0) parts.undefinedFields = undefinedFields;
2220
2247
  return parts;
2221
2248
  };
2222
2249
  /** Immutable operations share unowned fields; section content is a derived mirror. */
@@ -2246,7 +2273,7 @@ const changedParts = (before, after) => {
2246
2273
  if (before.package.footnotes !== after.package.footnotes) parts.footnotes = before.package.footnotes ?? null;
2247
2274
  if (before.package.endnotes !== after.package.endnotes) parts.endnotes = before.package.endnotes ?? null;
2248
2275
  if (before.package.settings !== after.package.settings) parts.settings = before.package.settings ?? null;
2249
- return parts;
2276
+ return captureStoryParts(before, parts);
2250
2277
  };
2251
2278
  const restoreParts = (document, parts) => {
2252
2279
  const pkg = { ...document.package };
@@ -2323,6 +2350,30 @@ const restoreParts = (document, parts) => {
2323
2350
  }
2324
2351
  if (parts.settings !== void 0) if (parts.settings === null) delete pkg.settings;
2325
2352
  else pkg.settings = parts.settings;
2353
+ for (const fields of parts.undefinedFields ?? []) switch (fields.target) {
2354
+ case "body":
2355
+ for (const key of fields.keys) {
2356
+ if (!parts.body || !Object.hasOwn(parts.body, key) || Reflect.get(parts.body, key) !== null) return panic("Undefined body metadata names an unowned field.");
2357
+ Reflect.set(pkg.document, key, void 0);
2358
+ }
2359
+ break;
2360
+ case "package":
2361
+ for (const key of fields.keys) {
2362
+ if (!Object.hasOwn(parts, key) || Reflect.get(parts, key) !== null) return panic("Undefined package metadata names an unowned field.");
2363
+ Reflect.set(pkg, key, void 0);
2364
+ }
2365
+ break;
2366
+ case "section": {
2367
+ const owned = parts.sections?.find(({ index }) => index === fields.index);
2368
+ const section = pkg.document.sections?.at(fields.index);
2369
+ if (!owned || !section) return panic("Undefined section metadata names an unowned section.");
2370
+ for (const key of fields.keys) {
2371
+ if (!Object.hasOwn(owned, key) || Reflect.get(owned, key) !== null) return panic("Undefined section metadata names an unowned field.");
2372
+ Reflect.set(section, key, void 0);
2373
+ }
2374
+ break;
2375
+ }
2376
+ }
2326
2377
  return {
2327
2378
  ...document,
2328
2379
  package: pkg
@@ -2431,8 +2482,25 @@ const withSectionProperties = (document, sectionIndex, properties) => {
2431
2482
  }
2432
2483
  };
2433
2484
  };
2485
+ const undefinedFieldsIssue = (parts) => {
2486
+ for (const fields of parts.undefinedFields ?? []) switch (fields.target) {
2487
+ case "body":
2488
+ if (fields.keys.some((key) => !parts.body || !Object.hasOwn(parts.body, key) || Reflect.get(parts.body, key) !== null)) return "Undefined body metadata must name owned null fields.";
2489
+ break;
2490
+ case "package":
2491
+ if (fields.keys.some((key) => !Object.hasOwn(parts, key) || Reflect.get(parts, key) !== null)) return "Undefined package metadata must name owned null fields.";
2492
+ break;
2493
+ case "section": {
2494
+ const owned = parts.sections?.find(({ index }) => index === fields.index);
2495
+ if (!owned || fields.keys.some((key) => !Object.hasOwn(owned, key) || Reflect.get(owned, key) !== null)) return "Undefined section metadata must name owned null fields.";
2496
+ break;
2497
+ }
2498
+ }
2499
+ };
2434
2500
  const applyStoryLifecycle = (document, op) => {
2435
2501
  if (op.type === DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS) {
2502
+ const metadataIssue = undefinedFieldsIssue(op.parts);
2503
+ if (metadataIssue) return refuse$5(op, metadataIssue);
2436
2504
  if (!structurallyEqual(captureStoryParts(document, op.expected), op.expected)) return Result.err(new DocumentOpRefusal({
2437
2505
  opType: op.type,
2438
2506
  reason: DOCUMENT_OP_REFUSAL_REASONS.STALE,
@@ -2540,6 +2608,640 @@ const applyStoryLifecycle = (document, op) => {
2540
2608
  return storyLifecycleEdit(document, next, op);
2541
2609
  };
2542
2610
  //#endregion
2611
+ //#region src/ops/comments.ts
2612
+ /** Semantic comment definitions and anchors, with narrow exact-state inverses. */
2613
+ const fail = (op, message, reason = DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH) => Result.err(new DocumentOpRefusal({
2614
+ opType: op.type,
2615
+ reason,
2616
+ message
2617
+ }));
2618
+ const validId = (id) => Number.isInteger(id) && id >= 0 && id <= 2147483647;
2619
+ const anchorId = (node) => {
2620
+ switch (node.type) {
2621
+ case "commentRangeStart":
2622
+ case "commentRangeEnd":
2623
+ case "commentReference": return node.id;
2624
+ default: return;
2625
+ }
2626
+ };
2627
+ const anchorsIn = (document) => {
2628
+ const anchors = [];
2629
+ for (const story of documentStories(document)) for (const { paragraph } of storyParagraphs(storyBody(document, story))) for (const span of leafSpans(paragraph.content)) if (isCommentAnchor(span.node)) anchors.push({
2630
+ story,
2631
+ blockId: paragraph.paraId ?? "",
2632
+ ...span
2633
+ });
2634
+ return anchors;
2635
+ };
2636
+ /**
2637
+ * Root comments without any owned source anchor. Loaded packages may carry
2638
+ * them; they stay preserved as read-only entries rather than refusing the
2639
+ * document, and no comment operation may create or target one.
2640
+ */
2641
+ const orphanRootCommentIds = (document) => {
2642
+ const comments = document.package.document.comments ?? [];
2643
+ const ids = new Set(comments.map(({ id }) => id));
2644
+ const anchored = new Set(anchorsIn(document).map(({ node }) => anchorId(node)));
2645
+ return new Set(comments.filter(({ id, parentId }) => (parentId === void 0 || !ids.has(parentId)) && !anchored.has(id)).map(({ id }) => id));
2646
+ };
2647
+ /**
2648
+ * Shared loaded-comment activation contract; legacy parentId revision associations stay explicit.
2649
+ * `allowedOrphans` names unanchored root comments the caller accepts ("all" for a loaded package).
2650
+ */
2651
+ const commentDocumentIssue = (document, allowedOrphans = /* @__PURE__ */ new Set()) => {
2652
+ const comments = document.package.document.comments ?? [];
2653
+ const byId = new Map(comments.map((comment) => [comment.id, comment]));
2654
+ if (comments.some(({ id }) => !validId(id)) || byId.size !== comments.length) return "Comment identities must be unique bounded integers.";
2655
+ const anchors = anchorsIn(document);
2656
+ if (anchors.some(({ node }) => !byId.has(anchorId(node) ?? -1))) return "A comment anchor has no definition.";
2657
+ for (const comment of comments) {
2658
+ const own = anchors.filter(({ node }) => anchorId(node) === comment.id);
2659
+ const starts = own.filter(({ node }) => node.type === "commentRangeStart");
2660
+ const ends = own.filter(({ node }) => node.type === "commentRangeEnd");
2661
+ const references = own.filter(({ node }) => node.type === "commentReference");
2662
+ const start = starts.at(0);
2663
+ const end = ends.at(0);
2664
+ if (starts.length !== ends.length || starts.length > 1 || references.length > 1) return "Comment anchors are unbalanced or duplicated.";
2665
+ if (start && end && (!sameStory(start.story, end.story) || anchors.indexOf(start) > anchors.indexOf(end))) return "Comment range boundaries must be ordered in one story.";
2666
+ const parent = comment.parentId === void 0 ? void 0 : byId.get(comment.parentId);
2667
+ if (!parent && own.length === 0 && allowedOrphans !== "all" && !allowedOrphans.has(comment.id)) return "A root or revision-associated comment needs an owned source anchor.";
2668
+ if (comment.parentId !== void 0 && !validId(comment.parentId)) return "A comment parent identity is invalid.";
2669
+ const visited = /* @__PURE__ */ new Set([comment.id]);
2670
+ let current = parent;
2671
+ while (current) {
2672
+ if (visited.has(current.id)) return "Comment parent relations cannot cycle.";
2673
+ visited.add(current.id);
2674
+ current = current.parentId === void 0 ? void 0 : byId.get(current.parentId);
2675
+ }
2676
+ }
2677
+ };
2678
+ /** Allocate from the package's annotation domains without a hidden mutable counter. */
2679
+ const freshCommentId = (document) => {
2680
+ let maximum = -1;
2681
+ for (const comment of document.package.document.comments ?? []) maximum = Math.max(maximum, comment.id, comment.parentId ?? -1);
2682
+ for (const { node } of anchorsIn(document)) maximum = Math.max(maximum, anchorId(node) ?? -1);
2683
+ for (const key of packageIdentityKeys(document.package)) {
2684
+ if (!Object.values(IDENTITY_SPACES).some((space) => key.startsWith(`${space}:`))) continue;
2685
+ maximum = Math.max(maximum, Number(key.slice(key.lastIndexOf(":") + 1)));
2686
+ }
2687
+ if (!Number.isInteger(maximum) || maximum >= 2147483647) return Result.err(new DocumentOpRefusal({
2688
+ opType: DOCUMENT_OP_TYPES.CREATE_COMMENT,
2689
+ reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID,
2690
+ message: "The package annotation id space is exhausted."
2691
+ }));
2692
+ return Result.ok(maximum + 1);
2693
+ };
2694
+ const propertyPresence = (record, key) => {
2695
+ if (!Object.hasOwn(record, key)) return "absent";
2696
+ return Reflect.get(record, key) === void 0 ? "undefined" : "present";
2697
+ };
2698
+ const capture = (document, ids, addressed) => {
2699
+ const body = document.package.document;
2700
+ const relationships = [];
2701
+ let relationshipIndex = 0;
2702
+ for (const [key, relationship] of document.package.relationships ?? []) {
2703
+ if (isCommentRelationship(relationship.type)) relationships.push({
2704
+ index: relationshipIndex,
2705
+ key,
2706
+ relationship
2707
+ });
2708
+ relationshipIndex += 1;
2709
+ }
2710
+ const records = [];
2711
+ for (const [index, comment] of (body.comments ?? []).entries()) if (ids.has(comment.id)) records.push({
2712
+ index,
2713
+ comment
2714
+ });
2715
+ const anchors = [];
2716
+ for (const { story, blockId } of addressed) {
2717
+ const found = findStoryBody(document, story);
2718
+ const paragraph = found && storyParagraphs(found).find(({ paragraph: value }) => idKey(value.paraId ?? "") === idKey(blockId))?.paragraph;
2719
+ if (paragraph) anchors.push({
2720
+ story,
2721
+ blockId,
2722
+ content: paragraph.content
2723
+ });
2724
+ }
2725
+ return {
2726
+ relationshipPresence: propertyPresence(document.package, "relationships"),
2727
+ relationships,
2728
+ listPresence: propertyPresence(body, "comments"),
2729
+ records,
2730
+ anchors
2731
+ };
2732
+ };
2733
+ const changedAnchors = (before, after) => {
2734
+ const anchors = [];
2735
+ for (const story of documentStories(before)) {
2736
+ const next = new Map(storyParagraphs(storyBody(after, story)).map(({ paragraph }) => [idKey(paragraph.paraId ?? ""), paragraph]));
2737
+ for (const { paragraph } of storyParagraphs(storyBody(before, story))) if (paragraph.content !== next.get(idKey(paragraph.paraId ?? ""))?.content) anchors.push({
2738
+ story,
2739
+ blockId: paragraph.paraId ?? "",
2740
+ content: paragraph.content
2741
+ });
2742
+ }
2743
+ return anchors;
2744
+ };
2745
+ const scaffoldDelta = (before, after) => {
2746
+ const old = new Set(identityKeysIn(before.anchors));
2747
+ const next = new Set(identityKeysIn(after.anchors));
2748
+ const changed = [...old].filter((id) => !next.has(id)).concat([...next].filter((id) => !old.has(id)));
2749
+ const values = (space) => changed.filter((key) => key.startsWith(`${space}:`)).map((key) => Number(key.slice(key.indexOf(":") + 1)));
2750
+ return {
2751
+ revision: values(IDENTITY_SPACES.REVISION),
2752
+ control: values(IDENTITY_SPACES.CONTROL)
2753
+ };
2754
+ };
2755
+ /** Remove only owned anchors, then merge scaffolding with the shared exact field predicate. */
2756
+ const ownedSeams = (content, ids) => {
2757
+ let references = 0;
2758
+ return leafSpans(content).flatMap(({ node, before }) => {
2759
+ const id = anchorId(node);
2760
+ if (id === void 0 || !ids.has(id)) return [];
2761
+ const position = before.offset - references;
2762
+ if (node.type === "commentReference") references++;
2763
+ return [position];
2764
+ });
2765
+ };
2766
+ const normalizedWithoutAnchors = ({ content, ids, seams, start = 0 }) => {
2767
+ let normalized = [];
2768
+ let position = start;
2769
+ for (const node of withoutAnchors(content, ids)) {
2770
+ const children = childNodes(node);
2771
+ const normalizedNode = children === void 0 ? node : rebuildNode(node, normalizedWithoutAnchors({
2772
+ content: children,
2773
+ ids,
2774
+ seams,
2775
+ start: position
2776
+ }));
2777
+ if (seams.has(position)) normalized = mergeAlike(normalized, [normalizedNode]);
2778
+ else normalized.push(normalizedNode);
2779
+ position += leafSpans([normalizedNode]).at(-1)?.after.offset ?? 0;
2780
+ }
2781
+ return normalized;
2782
+ };
2783
+ const isCommentRelationship = (type) => Object.values(COMMENT_PART_RELATIONSHIPS).some((part) => part.type === type);
2784
+ /** Keep the same part ids as the packager: numeric rId maximum plus one. */
2785
+ const reconcileRelationships = (document) => {
2786
+ const comments = document.package.document.comments ?? [];
2787
+ const relationships = new Map(document.package.relationships ?? []);
2788
+ let next = Math.max(0, ...[...relationships.keys()].map((id) => Number(/^rId(\d+)$/u.exec(id)?.at(1) ?? 0))) + 1;
2789
+ const extended = comments.some((comment) => comment.parentId !== void 0 || comment.done !== void 0);
2790
+ for (const [kind, part] of Object.entries(COMMENT_PART_RELATIONSHIPS)) {
2791
+ const needed = kind === "comments" ? comments.length > 0 : extended;
2792
+ const matching = [...relationships].filter(([, relationship]) => relationship.type === part.type);
2793
+ if (needed && matching.length === 0) {
2794
+ const id = `rId${next++}`;
2795
+ relationships.set(id, {
2796
+ id,
2797
+ type: part.type,
2798
+ target: part.target
2799
+ });
2800
+ }
2801
+ if (kind === "commentsExtended" && !needed) for (const [id] of matching) relationships.delete(id);
2802
+ }
2803
+ if (structurallyEqual([...relationships], [...document.package.relationships ?? []])) return document;
2804
+ return {
2805
+ ...document,
2806
+ package: {
2807
+ ...document.package,
2808
+ relationships
2809
+ }
2810
+ };
2811
+ };
2812
+ const edited = (before, after, op, ids) => {
2813
+ if (op.type !== DOCUMENT_OP_TYPES.RESTORE_COMMENT_STATE) after = reconcileRelationships(after);
2814
+ const invalid = contractViolation(after);
2815
+ if (invalid) return fail(op, invalid.message, invalid.reason);
2816
+ const issue = commentDocumentIssue(after, orphanRootCommentIds(before));
2817
+ if (issue) return fail(op, issue);
2818
+ const anchors = changedAnchors(before, after);
2819
+ const prior = capture(before, ids, anchors);
2820
+ const next = capture(after, ids, anchors);
2821
+ if (structurallyEqual(prior, next)) return Result.ok({
2822
+ document: before,
2823
+ inverse: [],
2824
+ touched: {
2825
+ modified: [],
2826
+ inserted: [],
2827
+ removed: []
2828
+ }
2829
+ });
2830
+ return Result.ok({
2831
+ document: after,
2832
+ inverse: [{
2833
+ type: DOCUMENT_OP_TYPES.RESTORE_COMMENT_STATE,
2834
+ ids: [...ids],
2835
+ scaffoldIds: scaffoldDelta(prior, next),
2836
+ expected: cloneModel(next),
2837
+ state: cloneModel(prior)
2838
+ }],
2839
+ touched: {
2840
+ modified: anchors.map(({ blockId }) => blockId),
2841
+ inserted: [],
2842
+ removed: []
2843
+ }
2844
+ });
2845
+ };
2846
+ const withComments = (document, comments, presence = "present") => {
2847
+ const body = { ...document.package.document };
2848
+ switch (presence) {
2849
+ case "present":
2850
+ body.comments = comments;
2851
+ break;
2852
+ case "undefined":
2853
+ Reflect.set(body, "comments", void 0);
2854
+ break;
2855
+ case "absent":
2856
+ delete body.comments;
2857
+ break;
2858
+ default: return presence;
2859
+ }
2860
+ return {
2861
+ ...document,
2862
+ package: {
2863
+ ...document.package,
2864
+ document: body
2865
+ }
2866
+ };
2867
+ };
2868
+ const withoutAnchors = (nodes, ids) => {
2869
+ let changed = false;
2870
+ const kept = [];
2871
+ for (const node of nodes) {
2872
+ const id = anchorId(node);
2873
+ if (id !== void 0 && ids.has(id)) {
2874
+ changed = true;
2875
+ continue;
2876
+ }
2877
+ const children = childNodes(node);
2878
+ const filtered = children === void 0 ? void 0 : withoutAnchors(children, ids);
2879
+ if (filtered === children || filtered === void 0) {
2880
+ kept.push(node);
2881
+ continue;
2882
+ }
2883
+ changed = true;
2884
+ const next = rebuildNode(node, filtered);
2885
+ if (!isEmptyRecord(next)) kept.push(next);
2886
+ }
2887
+ return changed ? kept : nodes;
2888
+ };
2889
+ const restoreAnchors = ({ document, anchors, op }) => {
2890
+ let current = document;
2891
+ for (const { story, blockId, content } of anchors) {
2892
+ const body = findStoryBody(current, story);
2893
+ const location = body && storyParagraphs(body).find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(blockId));
2894
+ if (!location) return fail(op, "An owned comment paragraph is missing.", DOCUMENT_OP_REFUSAL_REASONS.STALE);
2895
+ const changed = replaceParagraphs({
2896
+ document: current,
2897
+ story,
2898
+ at: location,
2899
+ count: 1,
2900
+ replacement: [{
2901
+ ...location.paragraph,
2902
+ content: cloneModel([...content])
2903
+ }]
2904
+ });
2905
+ if (changed.isErr()) return fail(op, changed.error.message, changed.error.reason);
2906
+ current = changed.value;
2907
+ }
2908
+ return Result.ok(current);
2909
+ };
2910
+ const restore = (document, op) => {
2911
+ const ids = new Set(op.ids);
2912
+ if (ids.size !== op.ids.length || op.ids.some((id) => !validId(id)) || !structurallyEqual(capture(document, ids, op.expected.anchors), op.expected)) return fail(op, "The comment inverse is stale.", DOCUMENT_OP_REFUSAL_REASONS.STALE);
2913
+ if (op.state.records.some(({ comment, index }) => !ids.has(comment.id) || !Number.isInteger(index) || index < 0) || new Set(op.state.records.map(({ comment }) => comment.id)).size !== op.state.records.length) return fail(op, "The restored comment records do not match the owned identities.");
2914
+ if (!op.scaffoldIds || !structurallyEqual(scaffoldDelta(op.expected, op.state), op.scaffoldIds)) return fail(op, "The comment inverse scaffold identities do not match its owned cuts.");
2915
+ const allowed = /* @__PURE__ */ new Set([...(op.scaffoldIds.revision ?? []).map((id) => `${IDENTITY_SPACES.REVISION}:${id}`), ...(op.scaffoldIds.control ?? []).map((id) => `${IDENTITY_SPACES.CONTROL}:${id}`)]);
2916
+ const identities = (state) => identityKeysIn(state.anchors).filter((id) => !allowed.has(id)).toSorted();
2917
+ if (!structurallyEqual(identities(op.expected), identities(op.state))) return fail(op, "The comment inverse changes an unowned identified record.");
2918
+ if (op.state.anchors.length !== op.expected.anchors.length || op.state.anchors.some((entry, index) => {
2919
+ const expected = op.expected.anchors.at(index);
2920
+ if (!expected || !sameStory(entry.story, expected.story) || idKey(entry.blockId) !== idKey(expected.blockId)) return true;
2921
+ const seams = /* @__PURE__ */ new Set([...ownedSeams(entry.content, ids), ...ownedSeams(expected.content, ids)]);
2922
+ const preserved = (content) => normalizedWithoutAnchors({
2923
+ content,
2924
+ ids,
2925
+ seams
2926
+ });
2927
+ const unowned = (content) => leafSpans(content).filter(({ node }) => {
2928
+ const id = anchorId(node);
2929
+ return id !== void 0 && !ids.has(id);
2930
+ }).map(({ node }) => node);
2931
+ return !structurallyEqual(preserved(entry.content), preserved(expected.content)) || !structurallyEqual(unowned(entry.content), unowned(expected.content));
2932
+ })) return fail(op, "A comment inverse cannot replace text or unowned anchors.");
2933
+ const anchors = restoreAnchors({
2934
+ document,
2935
+ op,
2936
+ anchors: op.state.anchors
2937
+ });
2938
+ if (anchors.isErr()) return anchors;
2939
+ const comments = (document.package.document.comments ?? []).filter(({ id }) => !ids.has(id));
2940
+ for (const { index, comment } of op.state.records) {
2941
+ if (index > comments.length) return fail(op, "A restored comment declaration position is stale.", DOCUMENT_OP_REFUSAL_REASONS.STALE);
2942
+ comments.splice(index, 0, cloneModel(comment));
2943
+ }
2944
+ if (op.state.listPresence !== "present" && comments.length > 0) return fail(op, "A missing comment list cannot discard unowned definitions.");
2945
+ const relationships = [...anchors.value.package.relationships ?? []].filter(([, relation]) => !isCommentRelationship(relation.type));
2946
+ for (const { index, key, relationship } of op.state.relationships) {
2947
+ const existing = op.expected.relationships.find((entry) => entry.key === key);
2948
+ if (existing && !structurallyEqual(existing.relationship, relationship)) return fail(op, "A comment inverse cannot alter an existing relationship payload.");
2949
+ if (!isCommentRelationship(relationship.type) || relationship.id !== key || index < 0 || index > relationships.length || relationships.some(([id]) => id === key)) return fail(op, "The comment inverse cannot replace an unowned relationship.");
2950
+ relationships.splice(index, 0, [key, cloneModel(relationship)]);
2951
+ }
2952
+ if (op.state.relationshipPresence !== "present" && relationships.length > 0) return fail(op, "A missing relationship map cannot discard unowned relationships.");
2953
+ const restored = withComments(anchors.value, comments, op.state.listPresence);
2954
+ const pkg = { ...restored.package };
2955
+ switch (op.state.relationshipPresence) {
2956
+ case "present":
2957
+ pkg.relationships = new Map(relationships);
2958
+ break;
2959
+ case "undefined":
2960
+ Reflect.set(pkg, "relationships", void 0);
2961
+ break;
2962
+ case "absent":
2963
+ delete pkg.relationships;
2964
+ break;
2965
+ }
2966
+ return edited(document, {
2967
+ ...restored,
2968
+ package: pkg
2969
+ }, op, ids);
2970
+ };
2971
+ const revisionRange = (document, story, revisionId) => {
2972
+ const body = findStoryBody(document, story);
2973
+ if (!body) return void 0;
2974
+ const spans = storyParagraphs(body).flatMap(({ paragraph }) => {
2975
+ const leaves = leafSpans(paragraph.content);
2976
+ const position = (gap) => ({
2977
+ story,
2978
+ blockId: paragraph.paraId ?? "",
2979
+ offset: gap.offset,
2980
+ zeroWidthBefore: gap.zeroWidthBefore
2981
+ });
2982
+ if (paragraph.propertyChanges?.some(({ info }) => info.id === revisionId) || paragraph.pPrMark?.info.id === revisionId) {
2983
+ const start = leaves.at(0)?.before ?? {
2984
+ offset: 0,
2985
+ zeroWidthBefore: 0
2986
+ };
2987
+ const end = leaves.at(-1)?.after ?? start;
2988
+ return [{
2989
+ from: position(start),
2990
+ to: position(end)
2991
+ }];
2992
+ }
2993
+ return leaves.flatMap((span) => {
2994
+ return [span.node, ...span.ancestors].some((node) => (node.type === "insertion" || node.type === "deletion" || node.type === "moveFrom" || node.type === "moveTo") && node.info.id === revisionId || node.type === "run" && node.propertyChanges?.some(({ info }) => info.id === revisionId)) ? [{
2995
+ from: position(span.before),
2996
+ to: position(span.after)
2997
+ }] : [];
2998
+ });
2999
+ });
3000
+ const first = spans.at(0);
3001
+ const last = spans.at(-1);
3002
+ return first && last ? {
3003
+ from: first.from,
3004
+ to: last.to
3005
+ } : void 0;
3006
+ };
3007
+ const remainingIds = (document, ids) => {
3008
+ const used = new Set(packageIdentityKeys(document.package));
3009
+ return {
3010
+ ...ids?.revision === void 0 ? {} : { revision: ids.revision.filter((id) => !used.has(`${IDENTITY_SPACES.REVISION}:${id}`)) },
3011
+ ...ids?.control === void 0 ? {} : { control: ids.control.filter((id) => !used.has(`${IDENTITY_SPACES.CONTROL}:${id}`)) }
3012
+ };
3013
+ };
3014
+ const create = (document, op, applyOps) => {
3015
+ const comments = document.package.document.comments ?? [];
3016
+ if (!validId(op.comment.id) || comments.some(({ id }) => id === op.comment.id) || anchorsIn(document).some(({ node }) => anchorId(node) === op.comment.id) || new Set(packageIdentityKeys(document.package)).has(`${IDENTITY_SPACES.REVISION}:${op.comment.id}`)) return fail(op, "The fresh comment identity is invalid or already used.", DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION);
3017
+ if (Object.hasOwn(op.comment, "parentId")) return fail(op, "Comment parent ownership belongs to the anchor discriminator.");
3018
+ if (op.comment.content.length === 0 || op.comment.content.some(({ paraId }) => paraId === void 0 || !isParaId(paraId))) return fail(op, "Comment paragraphs need explicit package paragraph identities.", DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID);
3019
+ let comment = cloneModel(op.comment);
3020
+ let positions = [];
3021
+ let range;
3022
+ switch (op.anchor.kind) {
3023
+ case "reply": {
3024
+ const parentId = op.anchor.parentId;
3025
+ if (!comments.some(({ id }) => id === parentId)) return fail(op, "The parent comment does not exist.");
3026
+ comment = {
3027
+ ...comment,
3028
+ parentId: op.anchor.parentId
3029
+ };
3030
+ const anchors = anchorsIn(document);
3031
+ const parentById = new Map(comments.map(({ id, parentId: owner }) => [id, owner]));
3032
+ const visited = /* @__PURE__ */ new Set();
3033
+ let anchorOwner = parentId;
3034
+ let parentAnchors = [];
3035
+ while (anchorOwner !== void 0 && !visited.has(anchorOwner)) {
3036
+ visited.add(anchorOwner);
3037
+ const owner = anchorOwner;
3038
+ parentAnchors = anchors.filter(({ node }) => anchorId(node) === owner);
3039
+ if (parentAnchors.length > 0) break;
3040
+ const next = parentById.get(owner);
3041
+ anchorOwner = typeof next === "number" && parentById.has(next) ? next : void 0;
3042
+ }
3043
+ if (parentAnchors.length === 0) return fail(op, "The parent comment has no representable owned anchors.");
3044
+ positions = parentAnchors.toReversed().map(({ story, blockId, node, after }) => {
3045
+ switch (node.type) {
3046
+ case "commentRangeStart":
3047
+ case "commentRangeEnd":
3048
+ case "commentReference": return {
3049
+ at: {
3050
+ story,
3051
+ blockId,
3052
+ offset: after.offset,
3053
+ zeroWidthBefore: after.zeroWidthBefore
3054
+ },
3055
+ content: [{
3056
+ type: node.type,
3057
+ id: comment.id
3058
+ }]
3059
+ };
3060
+ default: return {
3061
+ at: {
3062
+ story,
3063
+ blockId,
3064
+ offset: after.offset,
3065
+ zeroWidthBefore: after.zeroWidthBefore
3066
+ },
3067
+ content: []
3068
+ };
3069
+ }
3070
+ });
3071
+ break;
3072
+ }
3073
+ case "revision": {
3074
+ const revisionId = op.anchor.revisionId;
3075
+ if (!validId(revisionId) || comments.some(({ id }) => id === revisionId)) return fail(op, "Revision association cannot ambiguously name a comment parent.");
3076
+ range = revisionRange(document, op.anchor.story, op.anchor.revisionId);
3077
+ if (!range) return fail(op, "The associated revision has no representable source range.");
3078
+ comment = {
3079
+ ...comment,
3080
+ parentId: op.anchor.revisionId
3081
+ };
3082
+ if (range.from.blockId === range.to.blockId && range.from.offset === range.to.offset && range.from.zeroWidthBefore === range.to.zeroWidthBefore) {
3083
+ positions = [{
3084
+ at: range.from,
3085
+ content: [{
3086
+ type: "commentReference",
3087
+ id: comment.id
3088
+ }]
3089
+ }];
3090
+ range = void 0;
3091
+ }
3092
+ break;
3093
+ }
3094
+ case "point":
3095
+ positions = [{
3096
+ at: op.anchor.at,
3097
+ content: [{
3098
+ type: "commentReference",
3099
+ id: comment.id
3100
+ }]
3101
+ }];
3102
+ break;
3103
+ case "range":
3104
+ range = {
3105
+ from: op.anchor.from,
3106
+ to: op.anchor.to
3107
+ };
3108
+ break;
3109
+ default:
3110
+ op.anchor;
3111
+ return fail(op, "The comment anchor discriminator is invalid.");
3112
+ }
3113
+ if (range) {
3114
+ if (!sameStory(range.from.story, range.to.story)) return fail(op, "A comment range must stay in one story.", DOCUMENT_OP_REFUSAL_REASONS.CROSS_BLOCK_RANGE);
3115
+ const body = findStoryBody(document, range.from.story);
3116
+ if (!body) return fail(op, "The comment story does not exist.", DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND);
3117
+ const paragraphs = storyParagraphs(body).map(({ paragraph }) => paragraph);
3118
+ const fromIndex = paragraphs.findIndex(({ paraId }) => idKey(paraId ?? "") === idKey(range.from.blockId));
3119
+ const toIndex = paragraphs.findIndex(({ paraId }) => idKey(paraId ?? "") === idKey(range.to.blockId));
3120
+ const fromParagraph = paragraphs.at(fromIndex);
3121
+ const toParagraph = paragraphs.at(toIndex);
3122
+ if (fromIndex < 0 || toIndex < 0 || !fromParagraph || !toParagraph) return fail(op, "A comment boundary paragraph does not exist.", DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND);
3123
+ const fromGap = range.from.zeroWidthBefore === void 0 ? defaultInsertionGap(fromParagraph.content, range.from.offset) : {
3124
+ offset: range.from.offset,
3125
+ zeroWidthBefore: range.from.zeroWidthBefore
3126
+ };
3127
+ const toGap = range.to.zeroWidthBefore === void 0 ? defaultInsertionGap(toParagraph.content, range.to.offset) : {
3128
+ offset: range.to.offset,
3129
+ zeroWidthBefore: range.to.zeroWidthBefore
3130
+ };
3131
+ if (fromIndex > toIndex || fromIndex === toIndex && compareGaps(fromGap, toGap) > 0) return fail(op, "A comment range cannot run backwards.", DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET);
3132
+ positions = [{
3133
+ at: {
3134
+ ...range.to,
3135
+ zeroWidthBefore: toGap.zeroWidthBefore
3136
+ },
3137
+ content: [{
3138
+ type: "commentRangeEnd",
3139
+ id: comment.id
3140
+ }, {
3141
+ type: "commentReference",
3142
+ id: comment.id
3143
+ }]
3144
+ }, {
3145
+ at: {
3146
+ ...range.from,
3147
+ zeroWidthBefore: fromGap.zeroWidthBefore
3148
+ },
3149
+ content: [{
3150
+ type: "commentRangeStart",
3151
+ id: comment.id
3152
+ }]
3153
+ }];
3154
+ }
3155
+ let current = withComments(document, [...comments, comment]);
3156
+ for (const { at, content } of positions) {
3157
+ const inserted = applyOps(current, [{
3158
+ type: DOCUMENT_OP_TYPES.INSERT_CONTENT,
3159
+ at,
3160
+ slice: {
3161
+ content,
3162
+ openStart: 0,
3163
+ openEnd: 0
3164
+ },
3165
+ newIds: remainingIds(current, op.newIds)
3166
+ }]);
3167
+ if (inserted.isErr()) return Result.err(inserted.error);
3168
+ current = inserted.value.document;
3169
+ }
3170
+ return edited(document, current, op, /* @__PURE__ */ new Set([comment.id]));
3171
+ };
3172
+ const applyCommentOp = (document, op, applyOps) => {
3173
+ if (op.type === DOCUMENT_OP_TYPES.RESTORE_COMMENT_STATE) {
3174
+ if (!Array.isArray(op.ids) || !op.expected || !op.state || !Array.isArray(op.expected.relationships) || !Array.isArray(op.state.relationships) || !Array.isArray(op.expected.records) || !Array.isArray(op.expected.anchors) || !Array.isArray(op.state.records) || !Array.isArray(op.state.anchors)) return fail(op, "The comment inverse payload is invalid.");
3175
+ return restore(document, op);
3176
+ }
3177
+ const issue = commentDocumentIssue(document, "all");
3178
+ if (issue) return fail(op, issue);
3179
+ const orphans = orphanRootCommentIds(document);
3180
+ if (op.type === DOCUMENT_OP_TYPES.CREATE_COMMENT) {
3181
+ if (op.anchor?.kind === "reply" && orphans.has(op.anchor.parentId)) return fail(op, "A comment without a source anchor is preserved read-only.");
3182
+ if (!op.comment || typeof op.comment.author !== "string" || !Array.isArray(op.comment.content) || !op.anchor || typeof op.anchor !== "object") return fail(op, "The comment creation payload is invalid.");
3183
+ return create(document, op, applyOps);
3184
+ }
3185
+ const comments = document.package.document.comments ?? [];
3186
+ const comment = comments.find(({ id }) => id === op.id);
3187
+ if (!comment) return fail(op, "The comment does not exist.");
3188
+ if (orphans.has(comment.id)) return fail(op, "A comment without a source anchor is preserved read-only.");
3189
+ if (op.type === DOCUMENT_OP_TYPES.UPDATE_COMMENT_CONTENT) {
3190
+ if (!Array.isArray(op.content) || op.content.length === 0 || op.content.some(({ paraId }) => paraId === void 0 || !isParaId(paraId))) return fail(op, "Comment content needs explicit paragraph identities.", DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID);
3191
+ if (op.patch && Object.keys(op.patch).some((key) => key !== "author" && key !== "initials" && key !== "date")) return fail(op, "A content edit cannot change comment ownership.");
3192
+ if (op.patch && Object.hasOwn(op.patch, "author") && (op.patch.author === null || op.patch.author === void 0)) return fail(op, "A comment must retain an author.");
3193
+ const updated = {
3194
+ ...comment,
3195
+ ...applyFormattingPatch({
3196
+ author: comment.author,
3197
+ ...Object.hasOwn(comment, "initials") ? { initials: comment.initials } : {},
3198
+ ...Object.hasOwn(comment, "date") ? { date: comment.date } : {}
3199
+ }, op.patch ?? {}),
3200
+ content: cloneModel([...op.content])
3201
+ };
3202
+ if (op.patch?.initials === null) delete updated.initials;
3203
+ if (op.patch?.date === null) delete updated.date;
3204
+ return edited(document, withComments(document, comments.map((value) => value === comment ? updated : value)), op, /* @__PURE__ */ new Set([comment.id]));
3205
+ }
3206
+ if (op.type === DOCUMENT_OP_TYPES.SET_COMMENT_RESOLUTION) {
3207
+ if (op.status !== "open" && op.status !== "resolved") return fail(op, "Comment resolution status is invalid.");
3208
+ return edited(document, withComments(document, comments.map((value) => value === comment ? {
3209
+ ...comment,
3210
+ done: op.status === "resolved"
3211
+ } : value)), op, /* @__PURE__ */ new Set([comment.id]));
3212
+ }
3213
+ const parentIsComment = comment.parentId !== void 0 && comments.some(({ id }) => id === comment.parentId);
3214
+ if (op.scope !== "thread" && op.scope !== "reply" || op.scope === "reply" !== parentIsComment) return fail(op, "Comment deletion scope must match root or reply ownership.");
3215
+ const ids = /* @__PURE__ */ new Set([comment.id]);
3216
+ for (let previousSize = -1; previousSize !== ids.size;) {
3217
+ previousSize = ids.size;
3218
+ for (const value of comments) if (value.parentId !== void 0 && ids.has(value.parentId)) ids.add(value.id);
3219
+ }
3220
+ let current = document;
3221
+ for (const story of documentStories(document)) for (const { paragraph } of storyParagraphs(storyBody(document, story))) {
3222
+ const seams = new Set(ownedSeams(paragraph.content, ids));
3223
+ if (seams.size === 0) continue;
3224
+ const content = normalizedWithoutAnchors({
3225
+ content: paragraph.content,
3226
+ ids,
3227
+ seams
3228
+ });
3229
+ if (content === paragraph.content) continue;
3230
+ const changed = restoreAnchors({
3231
+ document: current,
3232
+ op,
3233
+ anchors: [{
3234
+ story,
3235
+ blockId: paragraph.paraId ?? "",
3236
+ content: asParagraphContent(content)
3237
+ }]
3238
+ });
3239
+ if (changed.isErr()) return changed;
3240
+ current = changed.value;
3241
+ }
3242
+ return edited(document, withComments(current, comments.filter(({ id }) => !ids.has(id)), comments.every(({ id }) => ids.has(id)) ? "absent" : "present"), op, ids);
3243
+ };
3244
+ //#endregion
2543
3245
  //#region src/ops/gaps.ts
2544
3246
  const isHighSurrogate = (code) => code >= 55296 && code <= 56319;
2545
3247
  const isLowSurrogate = (code) => code >= 56320 && code <= 57343;
@@ -9347,6 +10049,11 @@ const editNote = (document, op) => {
9347
10049
  };
9348
10050
  const dispatch = (document, op) => {
9349
10051
  switch (op.type) {
10052
+ case DOCUMENT_OP_TYPES.CREATE_COMMENT:
10053
+ case DOCUMENT_OP_TYPES.UPDATE_COMMENT_CONTENT:
10054
+ case DOCUMENT_OP_TYPES.SET_COMMENT_RESOLUTION:
10055
+ case DOCUMENT_OP_TYPES.DELETE_COMMENT:
10056
+ case DOCUMENT_OP_TYPES.RESTORE_COMMENT_STATE: return applyCommentOp(document, op, applyDocumentOps);
9350
10057
  case DOCUMENT_OP_TYPES.CREATE_HEADER_FOOTER:
9351
10058
  case DOCUMENT_OP_TYPES.REMOVE_HEADER_FOOTER:
9352
10059
  case DOCUMENT_OP_TYPES.SET_SECTION_PROPS:
@@ -9422,6 +10129,11 @@ const stampOf = (op) => {
9422
10129
  case DOCUMENT_OP_TYPES.SET_CELL_PROPS:
9423
10130
  case DOCUMENT_OP_TYPES.SET_ROW_PROPS:
9424
10131
  case DOCUMENT_OP_TYPES.SET_TABLE_PROPS: return op.revision;
10132
+ case DOCUMENT_OP_TYPES.CREATE_COMMENT:
10133
+ case DOCUMENT_OP_TYPES.UPDATE_COMMENT_CONTENT:
10134
+ case DOCUMENT_OP_TYPES.SET_COMMENT_RESOLUTION:
10135
+ case DOCUMENT_OP_TYPES.DELETE_COMMENT:
10136
+ case DOCUMENT_OP_TYPES.RESTORE_COMMENT_STATE:
9425
10137
  case DOCUMENT_OP_TYPES.CREATE_HEADER_FOOTER:
9426
10138
  case DOCUMENT_OP_TYPES.REMOVE_HEADER_FOOTER:
9427
10139
  case DOCUMENT_OP_TYPES.ADD_NOTE:
@@ -9521,7 +10233,7 @@ const applyDocumentOp = (document, input) => {
9521
10233
  };
9522
10234
  /** Apply a journal envelope only when its schema matches this reader. */
9523
10235
  const applyDocumentOpEnvelope = (document, envelope) => {
9524
- if (envelope.schema !== 9) return Result.err(refusal$1(envelope.op, DOCUMENT_OP_REFUSAL_REASONS.UNSUPPORTED_SCHEMA, `Document operation schema ${envelope.schema} is unsupported; this reader accepts 9.`));
10236
+ if (envelope.schema !== 10) return Result.err(refusal$1(envelope.op, DOCUMENT_OP_REFUSAL_REASONS.UNSUPPORTED_SCHEMA, `Document operation schema ${envelope.schema} is unsupported; this reader accepts 10.`));
9525
10237
  return applyDocumentOp(document, envelope.op);
9526
10238
  };
9527
10239
  /**
@@ -9874,6 +10586,7 @@ const usedIds = (document, space) => new Set(idsIn(packageIdentityKeys(document.
9874
10586
  /** The same operation with other new ids; one that takes none is returned as it is. */
9875
10587
  const withNewIds = (op, newIds) => {
9876
10588
  switch (op.type) {
10589
+ case DOCUMENT_OP_TYPES.CREATE_COMMENT:
9877
10590
  case DOCUMENT_OP_TYPES.DELETE_BLOCKS:
9878
10591
  case DOCUMENT_OP_TYPES.INSERT_BLOCKS:
9879
10592
  case DOCUMENT_OP_TYPES.INSERT_TEXT:
@@ -9898,6 +10611,10 @@ const withNewIds = (op, newIds) => {
9898
10611
  ...op,
9899
10612
  newIds
9900
10613
  };
10614
+ case DOCUMENT_OP_TYPES.UPDATE_COMMENT_CONTENT:
10615
+ case DOCUMENT_OP_TYPES.SET_COMMENT_RESOLUTION:
10616
+ case DOCUMENT_OP_TYPES.DELETE_COMMENT:
10617
+ case DOCUMENT_OP_TYPES.RESTORE_COMMENT_STATE:
9901
10618
  case DOCUMENT_OP_TYPES.CREATE_HEADER_FOOTER:
9902
10619
  case DOCUMENT_OP_TYPES.REMOVE_HEADER_FOOTER:
9903
10620
  case DOCUMENT_OP_TYPES.ADD_NOTE:
@@ -9942,6 +10659,68 @@ const trimAppliedNewIds = ({ before, op, applied, story }) => {
9942
10659
  return !known.has(key) && (identities.has(key) || space === IDENTITY_SPACES.REVISION && revisions.has(id));
9943
10660
  });
9944
10661
  };
10662
+ /** Package-aware explicit pools for every semantic comment anchor cut, including replies. */
10663
+ const allocateCommentAnchorIds = (document, op) => {
10664
+ const keys = [...packageIdentityKeys(document.package), ...identityKeysIn(op)];
10665
+ const firstIn = (space) => {
10666
+ let largest = 0;
10667
+ for (const id of idsIn(keys, space)) largest = Math.max(largest, id);
10668
+ return largest + 1;
10669
+ };
10670
+ const firstRevision = Math.max(firstIn(IDENTITY_SPACES.REVISION), op.comment.id + 1);
10671
+ const firstControl = firstIn(IDENTITY_SPACES.CONTROL);
10672
+ const pool = (first, count) => Array.from({ length: count }, (_, index) => first + index);
10673
+ const attempt = (counts) => applyDocumentOp(document, {
10674
+ ...op,
10675
+ newIds: {
10676
+ revision: pool(firstRevision, counts.revision),
10677
+ control: pool(firstControl, counts.control)
10678
+ }
10679
+ });
10680
+ const capacity = {
10681
+ revision: Math.max(0, MAX_REVISION_ID - firstRevision + 1),
10682
+ control: Math.max(0, MAX_REVISION_ID - firstControl + 1)
10683
+ };
10684
+ let count = 0;
10685
+ for (;;) {
10686
+ const trial = attempt({
10687
+ revision: Math.min(count, capacity.revision),
10688
+ control: Math.min(count, capacity.control)
10689
+ });
10690
+ if (trial.isOk()) break;
10691
+ if (trial.error.reason !== DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS) return Result.err(trial.error);
10692
+ const next = count === 0 ? 1 : count * 2;
10693
+ if (next > MAX_DEMAND || count >= Math.max(capacity.revision, capacity.control)) return Result.err(new DocumentOpRefusal({
10694
+ opType: op.type,
10695
+ reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
10696
+ message: "Comment anchor cuts exhaust the package identity space."
10697
+ }));
10698
+ count = next;
10699
+ }
10700
+ const counts = {
10701
+ revision: Math.min(count, capacity.revision),
10702
+ control: Math.min(count, capacity.control)
10703
+ };
10704
+ for (const space of [IDENTITY_SPACES.REVISION, IDENTITY_SPACES.CONTROL]) {
10705
+ let low = 0;
10706
+ let high = counts[space];
10707
+ while (low < high) {
10708
+ const middle = Math.floor((low + high) / 2);
10709
+ const trial = attempt({
10710
+ ...counts,
10711
+ [space]: middle
10712
+ });
10713
+ if (trial.isOk()) high = middle;
10714
+ else if (trial.error.reason === DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS) low = middle + 1;
10715
+ else return Result.err(trial.error);
10716
+ }
10717
+ counts[space] = low;
10718
+ }
10719
+ return Result.ok({
10720
+ revision: pool(firstRevision, counts.revision),
10721
+ control: pool(firstControl, counts.control)
10722
+ });
10723
+ };
9945
10724
  /** The largest id count {@link revisionIdDemand} searches before giving up. */
9946
10725
  const MAX_DEMAND = 65536;
9947
10726
  /**
@@ -10957,16 +11736,18 @@ const editorParagraphGroups = (document, story) => {
10957
11736
  return groups;
10958
11737
  };
10959
11738
  const paragraphAt = (document, at) => storyParagraphs(storyBody(document, at.story)).find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(at.blockId))?.paragraph;
11739
+ /** Zero-width markers and empty leaves never supply the formatting of typed content. */
11740
+ const visibleFormattingSpans = (paragraph) => leafSpans(paragraph.content).filter(({ ancestors, before, after }) => after.offset > before.offset && !ancestors.some(isRemovedRevisionNode));
10960
11741
  /** Capture authored formatting before deletion, using only visible runs. */
10961
11742
  const formattingAt = (paragraph, offset) => {
10962
- const spans = leafSpans(paragraph.content).filter(({ ancestors }) => !ancestors.some(isRemovedRevisionNode));
11743
+ const spans = visibleFormattingSpans(paragraph);
10963
11744
  return (spans.find(({ before, after }) => before.offset <= offset && offset < after.offset) ?? spans.findLast(({ after }) => after.offset <= offset) ?? spans.find(({ before }) => before.offset > offset))?.ancestors.findLast((ancestor) => ancestor.type === "run")?.formatting;
10964
11745
  };
10965
11746
  const authoredFormatting = (document, from, to) => {
10966
11747
  const paragraph = paragraphAt(document, from);
10967
11748
  if (paragraph === void 0) panic("A validated input paragraph must exist when reading authored formatting.");
10968
11749
  if (!(from.blockId === to.blockId && from.offset === to.offset)) return formattingAt(paragraph, from.offset);
10969
- if (leafSpans(paragraph.content).some(({ ancestors, before }) => !ancestors.some(isRemovedRevisionNode) && before.offset < from.offset)) return formattingAt(paragraph, from.offset - 1);
11750
+ if (visibleFormattingSpans(paragraph).some(({ before }) => before.offset < from.offset)) return formattingAt(paragraph, from.offset - 1);
10970
11751
  const group = editorParagraphGroups(document, from.story).find(({ paragraphs }) => paragraphs.some(({ paraId }) => idKey(paraId ?? "") === idKey(from.blockId)));
10971
11752
  const index = group?.paragraphs.findIndex(({ paraId }) => idKey(paraId ?? "") === idKey(from.blockId)) ?? 0;
10972
11753
  const previous = group?.paragraphs.slice(0, index).findLast((item) => paragraphVisibleText(item) !== "");
@@ -12531,6 +13312,11 @@ const operationFields = {
12531
13312
  createNumberingInstance: void 0,
12532
13313
  deleteNumberingInstance: void 0,
12533
13314
  setSectionEndpoint: void 0,
13315
+ createComment: void 0,
13316
+ updateCommentContent: void 0,
13317
+ setCommentResolution: void 0,
13318
+ deleteComment: void 0,
13319
+ restoreCommentState: void 0,
12534
13320
  setPackageResources: void 0,
12535
13321
  addNote: void 0,
12536
13322
  createHeaderFooter: void 0,
@@ -12588,7 +13374,7 @@ const isJsonData = ({ value, ancestors, depth, budget }) => {
12588
13374
  return valid;
12589
13375
  };
12590
13376
  const isDocumentBatch = (value) => object({
12591
- schema: literal(9),
13377
+ schema: literal(10),
12592
13378
  opId: nonemptyString,
12593
13379
  actor: nonemptyString,
12594
13380
  baseRev: natural,
@@ -12645,7 +13431,7 @@ const validateDocumentBatch = (value) => {
12645
13431
  return decoded;
12646
13432
  };
12647
13433
  const decodeDocumentBatch = (value) => {
12648
- if (value["schema"] !== 9) return Result.err(new BatchRejection({
13434
+ if (value["schema"] !== 10) return Result.err(new BatchRejection({
12649
13435
  reason: BATCH_REJECTION_REASONS.UNSUPPORTED_SCHEMA,
12650
13436
  message: "Unsupported document operation schema"
12651
13437
  }));
@@ -12747,6 +13533,11 @@ const operationStory = (op) => {
12747
13533
  case DOCUMENT_OP_TYPES.SET_ROW_PROPS:
12748
13534
  case DOCUMENT_OP_TYPES.SET_TABLE_PROPS:
12749
13535
  case DOCUMENT_OP_TYPES.SET_TABLE: return op.story;
13536
+ case DOCUMENT_OP_TYPES.CREATE_COMMENT:
13537
+ case DOCUMENT_OP_TYPES.UPDATE_COMMENT_CONTENT:
13538
+ case DOCUMENT_OP_TYPES.SET_COMMENT_RESOLUTION:
13539
+ case DOCUMENT_OP_TYPES.DELETE_COMMENT:
13540
+ case DOCUMENT_OP_TYPES.RESTORE_COMMENT_STATE:
12750
13541
  case DOCUMENT_OP_TYPES.CREATE_NUMBERING_INSTANCE:
12751
13542
  case DOCUMENT_OP_TYPES.DELETE_NUMBERING_INSTANCE:
12752
13543
  case DOCUMENT_OP_TYPES.SET_SECTION_ENDPOINT:
@@ -13484,4 +14275,4 @@ const createClient = (document) => {
13484
14275
  };
13485
14276
  };
13486
14277
  //#endregion
13487
- export { BATCH_REJECTION_REASONS, BATCH_WIRE_OP_TYPES, BatchRejection, DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, DocumentOpRefusal, DocumentOpsContractError, EMPTY_PROPERTY_SETS, INHERIT_RUN_PROPS, MAX_BATCH_WIRE_BYTES, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, PARAGRAPH_MARK_FORMATTING_KEYS, PROPERTY_REVIEW_POLICIES, REVISION_DECISIONS, SPLIT_HALVES, applyDocumentOp, applyDocumentOpEnvelope, applyDocumentOps, captureDocumentOp, combineEdits, compareGaps, compileEditorIntent, createClient, createEditorIntentIdAllocator, createSequencer, defaultInsertionGap, documentStories, editorParagraphGroups, findStoryBody, formattingEquals, idKey, inlineLeafSpans, isTextOnlyRun, mapTocBookmarkPosition, mergeRunContent, normalizeForOps, noteUsesCustomMark, packageParagraphIds, packageResourcesOpOf, paragraphLength, paragraphLogicalText, paragraphVisibleText, parseDocumentBatch, physicalOffsetAtVisibleOffset, planTrackedDeletion, planTrackedReplace, revisionIdDemand, runsMergeable, sameStory, sectionPropertiesAt, storyBody, toOpEnvelope, transformBatch, validateDocumentBatch, validateOpsDocument, validateSequencedBatch, zeroWidthLeavesAt };
14278
+ export { BATCH_REJECTION_REASONS, BATCH_WIRE_OP_TYPES, BatchRejection, DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, DocumentOpRefusal, DocumentOpsContractError, EMPTY_PROPERTY_SETS, INHERIT_RUN_PROPS, MAX_BATCH_WIRE_BYTES, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, PARAGRAPH_MARK_FORMATTING_KEYS, PROPERTY_REVIEW_POLICIES, REVISION_DECISIONS, SPLIT_HALVES, allocateCommentAnchorIds, applyDocumentOp, applyDocumentOpEnvelope, applyDocumentOps, captureDocumentOp, combineEdits, commentDocumentIssue, compareGaps, compileEditorIntent, createClient, createEditorIntentIdAllocator, createSequencer, defaultInsertionGap, documentStories, editorParagraphGroups, findStoryBody, formattingEquals, freshCommentId, idKey, inlineLeafSpans, isTextOnlyRun, mapTocBookmarkPosition, mergeRunContent, normalizeForOps, noteUsesCustomMark, packageParagraphIds, packageResourcesOpOf, paragraphLength, paragraphLogicalText, paragraphVisibleText, parseDocumentBatch, physicalOffsetAtVisibleOffset, planTrackedDeletion, planTrackedReplace, revisionIdDemand, runsMergeable, sameStory, sectionPropertiesAt, storyBody, toOpEnvelope, transformBatch, validateDocumentBatch, validateOpsDocument, validateSequencedBatch, zeroWidthLeavesAt };