@stll/folio-core 0.74.0 → 0.76.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.
Files changed (174) hide show
  1. package/dist/ai-edits/clean-text.d.ts +4 -1
  2. package/dist/ai-edits/clean-text.js +21 -7
  3. package/dist/ai-edits/headless.d.ts +7 -3
  4. package/dist/ai-edits/headless.js +36 -21
  5. package/dist/ai-edits/note-references.d.ts +1 -1
  6. package/dist/ai-edits/note-references.js +1 -1
  7. package/dist/ai-edits/pending-suggestions.d.ts +9 -7
  8. package/dist/ai-edits/pending-suggestions.js +135 -90
  9. package/dist/ai-edits/pendingJoin.d.ts +5 -1
  10. package/dist/ai-edits/pendingJoin.js +6 -2
  11. package/dist/ai-edits/read.js +9 -3
  12. package/dist/ai-edits/retired-comment-receipts.d.ts +2 -2
  13. package/dist/ai-edits/retired-comment-receipts.js +3 -18
  14. package/dist/ai-edits/tracked-batch-fidelity.d.ts +6 -10
  15. package/dist/ai-edits/tracked-batch-fidelity.js +3 -182
  16. package/dist/ai-edits/types.d.ts +9 -4
  17. package/dist/canonical/batchCommentReferences.js +2 -1
  18. package/dist/canonical/canonicalBatchReview.d.ts +4 -1
  19. package/dist/canonical/canonicalBatchReview.js +37 -22
  20. package/dist/canonical/canonicalComments.d.ts +6 -2
  21. package/dist/canonical/canonicalComments.js +16 -6
  22. package/dist/canonical/canonicalCompilerRefusal.d.ts +2 -4
  23. package/dist/canonical/canonicalCompilerRefusal.js +20 -14
  24. package/dist/canonical/canonicalPublicOperations.js +231 -79
  25. package/dist/canonical/canonicalRefusalGrounds.d.ts +4 -0
  26. package/dist/canonical/canonicalRefusalGrounds.js +56 -0
  27. package/dist/canonical/canonicalSession.d.ts +12 -6
  28. package/dist/canonical/canonicalSession.js +119 -122
  29. package/dist/canonical/canonicalTrackedBatchFidelity.js +3 -3
  30. package/dist/compare/inline-atoms.d.ts +35 -41
  31. package/dist/compare/inline-atoms.js +2 -465
  32. package/dist/compare/section-boundary-properties.d.ts +3 -30
  33. package/dist/compare/section-boundary-properties.js +4 -72
  34. package/dist/controller/canonicalClipboard.d.ts +1 -1
  35. package/dist/controller/canonicalClipboard.js +110 -55
  36. package/dist/controller/canonicalComposition.d.ts +1 -1
  37. package/dist/controller/canonicalComposition.js +5 -5
  38. package/dist/controller/canonicalContentControlValue.js +7 -7
  39. package/dist/controller/canonicalInput.d.ts +4 -2
  40. package/dist/controller/canonicalInput.js +33 -16
  41. package/dist/controller/canonicalReview.d.ts +21 -0
  42. package/dist/controller/canonicalReview.js +44 -9
  43. package/dist/controller/canonicalStoryEditor.d.ts +2 -3
  44. package/dist/controller/canonicalStoryEditor.js +43 -25
  45. package/dist/controller/canonicalStructure.d.ts +19 -3
  46. package/dist/controller/canonicalStructure.js +182 -58
  47. package/dist/controller/deferredDisplayListPainter.d.ts +8 -0
  48. package/dist/controller/deferredDisplayListPainter.js +34 -0
  49. package/dist/controller/folioEditor.js +4 -2
  50. package/dist/controller/fontReadiness.js +50 -23
  51. package/dist/controller/headerFooterEditorManager.js +3 -17
  52. package/dist/controller/hiddenEditorApi.d.ts +24 -3
  53. package/dist/controller/hiddenEditorApi.js +2 -0
  54. package/dist/controller/hiddenEditorManager.js +135 -207
  55. package/dist/controller/layoutPipeline.d.ts +4 -86
  56. package/dist/controller/layoutPipeline.js +8 -727
  57. package/dist/controller/layoutPipelineExecution.d.ts +94 -0
  58. package/dist/controller/layoutPipelineExecution.js +730 -0
  59. package/dist/controller/noteEditorManager.js +3 -16
  60. package/dist/docx/blockContentParser.d.ts +1 -3
  61. package/dist/docx/blockContentParser.js +3 -10
  62. package/dist/docx/bulletMarkers.d.ts +8 -0
  63. package/dist/docx/bulletMarkers.js +9 -1
  64. package/dist/docx/canonicalSave.d.ts +4 -3
  65. package/dist/docx/canonicalSave.js +4 -3
  66. package/dist/docx/canonicalSessionInput.js +25 -11
  67. package/dist/docx/ensureParaIds.d.ts +31 -0
  68. package/dist/docx/ensureParaIds.js +57 -32
  69. package/dist/docx/ensureUniqueControlIds.d.ts +13 -0
  70. package/dist/docx/ensureUniqueControlIds.js +47 -29
  71. package/dist/docx/ensureUniqueRevisionIds.d.ts +13 -0
  72. package/dist/docx/ensureUniqueRevisionIds.js +52 -29
  73. package/dist/docx/listMarkerComputation.d.ts +24 -17
  74. package/dist/docx/listMarkerComputation.js +31 -60
  75. package/dist/docx/listModelNormalization.js +8 -15
  76. package/dist/docx/rezip.d.ts +16 -3
  77. package/dist/docx/rezip.js +35 -9
  78. package/dist/docx/selectiveSave.js +13 -5
  79. package/dist/docx/server/templatePlan/apply.js +96 -7
  80. package/dist/docx/server/templatePlan/blocks.d.ts +70 -3
  81. package/dist/docx/server/templatePlan/blocks.js +272 -10
  82. package/dist/docx/server/templatePlan/builders.d.ts +52 -2
  83. package/dist/docx/server/templatePlan/builders.js +224 -5
  84. package/dist/docx/server/templatePlan/effects.d.ts +27 -0
  85. package/dist/docx/server/templatePlan/effects.js +188 -0
  86. package/dist/docx/server/templatePlan/emit.d.ts +4 -1
  87. package/dist/docx/server/templatePlan/emit.js +46 -2
  88. package/dist/docx/server/templatePlan/inspect.js +39 -52
  89. package/dist/docx/server/templatePlan/labels.d.ts +7 -2
  90. package/dist/docx/server/templatePlan/labels.js +120 -23
  91. package/dist/docx/server/templatePlan/plan.d.ts +24 -3
  92. package/dist/docx/server/templatePlan/plan.js +54 -15
  93. package/dist/docx/server/templatePlan/planShape.js +76 -22
  94. package/dist/docx/server/templatePlan/revisions.d.ts +46 -0
  95. package/dist/docx/server/templatePlan/revisions.js +407 -0
  96. package/dist/docx/server/templatePlan/story.d.ts +23 -1
  97. package/dist/docx/server/templatePlan/story.js +60 -2
  98. package/dist/docx/server/templatePlan/types.d.ts +354 -16
  99. package/dist/docx/server/templatePlan/verify.js +164 -14
  100. package/dist/docx/server/templatePlan/xml.d.ts +3 -0
  101. package/dist/docx/server/templatePlan/xml.js +4 -1
  102. package/dist/i18n/messages/ar.gen.js +1 -0
  103. package/dist/i18n/messages/catalogs.gen.d.ts +17 -0
  104. package/dist/i18n/messages/catalogs.gen.js +17 -0
  105. package/dist/i18n/messages/cs.gen.js +1 -0
  106. package/dist/i18n/messages/de.gen.js +1 -0
  107. package/dist/i18n/messages/en.gen.js +1 -0
  108. package/dist/i18n/messages/es.gen.js +1 -0
  109. package/dist/i18n/messages/et.gen.js +1 -0
  110. package/dist/i18n/messages/fr.gen.js +1 -0
  111. package/dist/i18n/messages/he.gen.js +1 -0
  112. package/dist/i18n/messages/hi.gen.js +1 -0
  113. package/dist/i18n/messages/hu.gen.js +1 -0
  114. package/dist/i18n/messages/lt.gen.js +1 -0
  115. package/dist/i18n/messages/lv.gen.js +1 -0
  116. package/dist/i18n/messages/messages.gen.d.ts +1 -0
  117. package/dist/i18n/messages/pl.gen.js +1 -0
  118. package/dist/i18n/messages/pt-BR.gen.js +1 -0
  119. package/dist/i18n/messages/sk.gen.js +1 -0
  120. package/dist/i18n/messages/tr.gen.js +1 -0
  121. package/dist/i18n/messages/zh-CN.gen.js +1 -0
  122. package/dist/internal/revisionResolutionStep.d.ts +2 -31
  123. package/dist/internal/revisionResolutionStep.js +2 -171
  124. package/dist/layout-bridge/convert/toFlowBlocks.js +0 -12
  125. package/dist/layout-bridge/convert/topLevelConversion.js +1 -10
  126. package/dist/prosemirror/commands/comments.d.ts +6 -234
  127. package/dist/prosemirror/commands/comments.js +5 -2464
  128. package/dist/prosemirror/commands/index.d.ts +4 -2
  129. package/dist/prosemirror/commands/index.js +4 -2
  130. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +1 -11
  131. package/dist/prosemirror/commands/tableCellMergeResolution.js +3 -154
  132. package/dist/prosemirror/extensions/features/ImagePasteExtension.js +1 -1
  133. package/dist/prosemirror/extensions/marks/HyperlinkExtension.js +6 -8
  134. package/dist/prosemirror/hyperlinkRemoval.d.ts +11 -8
  135. package/dist/prosemirror/hyperlinkRemoval.js +24 -15
  136. package/dist/prosemirror/listMarker.d.ts +1 -6
  137. package/dist/prosemirror/listMarker.js +4 -56
  138. package/dist/prosemirror/paraIds.d.ts +1 -14
  139. package/dist/prosemirror/paraIds.js +1 -14
  140. package/dist/prosemirror/paragraphMarkJoin.d.ts +0 -16
  141. package/dist/prosemirror/paragraphMarkJoin.js +3 -46
  142. package/dist/prosemirror/projectionReview.d.ts +49 -0
  143. package/dist/prosemirror/projectionReview.js +292 -0
  144. package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -13
  145. package/dist/prosemirror/rebaseParagraphRunFormatting.js +1 -16
  146. package/dist/prosemirror/replacedAnnotations.d.ts +2 -5
  147. package/dist/prosemirror/replacedAnnotations.js +1 -10
  148. package/dist/prosemirror/revisionCarriers.d.ts +9 -1
  149. package/dist/prosemirror/revisionCarriers.js +15 -1
  150. package/dist/prosemirror/revisionRangeQueries.d.ts +32 -0
  151. package/dist/prosemirror/revisionRangeQueries.js +76 -0
  152. package/dist/prosemirror/runFormattingMarkNames.d.ts +1 -1
  153. package/dist/prosemirror/runFormattingMarkNames.js +1 -1
  154. package/dist/prosemirror/suggestionQueries.d.ts +114 -0
  155. package/dist/prosemirror/suggestionQueries.js +320 -0
  156. package/dist/prosemirror/tableGridMutation.d.ts +1 -16
  157. package/dist/prosemirror/tableGridMutation.js +1 -78
  158. package/dist/prosemirror/tableRowRevisionOwnership.d.ts +18 -0
  159. package/dist/prosemirror/tableRowRevisionOwnership.js +7 -0
  160. package/dist/prosemirror/utils/extractTrackedChanges.js +14 -4
  161. package/dist/server.d.ts +2 -2
  162. package/dist/types/canonicalCapabilities.d.ts +40 -69
  163. package/dist/types/canonicalCapabilities.js +51 -65
  164. package/dist/types/canonicalComments.d.ts +2 -2
  165. package/dist/types/canonicalSections.d.ts +2 -2
  166. package/dist/utils/clipboard.d.ts +2 -28
  167. package/dist/utils/clipboard.js +1 -96
  168. package/dist/utils/clipboardFiles.d.ts +27 -0
  169. package/dist/utils/clipboardFiles.js +98 -0
  170. package/dist/utils/rulerControl.d.ts +1 -0
  171. package/dist/utils/rulerControl.js +2 -1
  172. package/package.json +2 -2
  173. package/dist/internal/headlessRevisionResolutionGuard.d.ts +0 -3
  174. package/dist/internal/headlessRevisionResolutionGuard.js +0 -18
@@ -4,7 +4,7 @@ import { describeCharacterSplit } from "../ai-edits/character-boundaries.js";
4
4
  import { buildCleanBlockText, resolveCleanTextRange } from "../ai-edits/clean-text.js";
5
5
  import { directJoinSurvivor, directJoinTakes } from "../ai-edits/directJoin.js";
6
6
  import { EXISTING_REVISION_CONFLICT_MESSAGE, createExistingRevisionGuard } from "../ai-edits/existingRevisions.js";
7
- import { parseInlineEmphasisRuns, stripInlineEmphasisMarkers } from "../ai-edits/inline-emphasis.js";
7
+ import { hasInlineEmphasis, parseInlineEmphasisRuns, stripInlineEmphasisMarkers } from "../ai-edits/inline-emphasis.js";
8
8
  import { compileMarkdownInsertion } from "../ai-edits/markdownInsertion.js";
9
9
  import { BACKGROUND_MARK_NAMES, changesFromSegments, cutAroundRepeatedSeparators, planReplacementChanges, planTextChanges, touchedBackgroundStretches } from "../ai-edits/minimal-replacement.js";
10
10
  import { createBatchListMinter } from "../ai-edits/newListNumbering.js";
@@ -35,7 +35,7 @@ import { preservesReplacementCommentAlignment, splitAtKeptCommentBoundaries, sur
35
35
  import { createStyleResolver } from "../prosemirror/styles/styleResolver.js";
36
36
  import { insertedColumnWidth, omittedSlotTakingColumn } from "../prosemirror/tableGridMutation.js";
37
37
  import { paragraphGoes, tableGoes } from "../prosemirror/tableRunIn.js";
38
- import { CANONICAL_GAP } from "../types/canonicalCapabilities.js";
38
+ import { CANONICAL_CONDITION, CANONICAL_GAP, CANONICAL_RULE } from "../types/canonicalCapabilities.js";
39
39
  import { readModel } from "../types/documentModel.js";
40
40
  import { batchCommentReferenceShift, mapIntentPositions } from "./batchCommentReferences.js";
41
41
  import { createCanonicalBatchReview } from "./canonicalBatchReview.js";
@@ -45,6 +45,7 @@ import { insertedCommentRange, plainInsertedParagraphIds } from "./canonicalInse
45
45
  import { planReplayParagraphIds, startParagraphAdmissionCursor } from "./canonicalInsertionReplayIds.js";
46
46
  import { addJoinedParagraphReceipts } from "./canonicalJoinedReceipts.js";
47
47
  import { lockViolationBetween } from "./canonicalLockGuard.js";
48
+ import { groundForDocumentOpRefusal } from "./canonicalRefusalGrounds.js";
48
49
  import { keepStandingRevisionReceipts } from "./canonicalRevisionReceipts.js";
49
50
  import { CANONICAL_ADMISSION } from "./canonicalSession.js";
50
51
  import { canonicalTrackedBatchFidelityError } from "./canonicalTrackedBatchFidelity.js";
@@ -55,7 +56,7 @@ import { replacementRunSources } from "./replacementRunSources.js";
55
56
  import { Result, TaggedError, panic } from "better-result";
56
57
  import { commentAuthorIssue, trackedChangeAuthorIssue } from "@stll/docx-core";
57
58
  import { CONTENT_CONTROL_LOCK, MAX_REVISION_ID, lockedControlMessage, paragraphNumberingReference } from "@stll/docx-core/model";
58
- import { BATCH_ANNOTATION_KINDS, DOCUMENT_OP_TYPES, ID_KIND_LIMITS, ID_LEASE_KINDS, OP_STORIES, SPLIT_HALVES, TYPED_TEXT_FORMATTING, applyDocumentOps, combineRecordedRevisions, compileEditorIntent, contentRank, createEditorIntentIdAllocator, deletionRemovesBlock, documentStories, finalBreakCarrier, findStoryBody, formatParaId, freshCommentId, groupInsertionRuns, idKey, introducedDocumentIds, isBlockBoundary, isCommentAnchorCarrierType, joinPropertyChangeLink, leasedIdCensus, locateParagraphThroughTextBoxes, noteDeletionOps, orderAddressingBeforeRemoval, orderBatchOperations, packageResourcesOpOf, paragraphHoldsContent, paragraphHoldsContentOnceAccepted, paragraphLength, paragraphsThroughTextBoxes, pendingSuggestionIdsIn, revisionSpan } from "@stll/docx-core/ops";
59
+ import { BATCH_ANNOTATION_KINDS, DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_TYPES, DocumentOpRefusal, ID_KIND_LIMITS, ID_LEASE_KINDS, OP_STORIES, SPLIT_HALVES, TYPED_TEXT_FORMATTING, applyDocumentOps, combineRecordedRevisions, compileEditorIntent, contentRank, createEditorIntentIdAllocator, deletionRemovesBlock, documentStories, finalBreakCarrier, findStoryBody, formatParaId, freshCommentId, groupInsertionRuns, idKey, introducedDocumentIds, isBlockBoundary, isCommentAnchorCarrierType, joinPropertyChangeLink, leasedIdCensus, locateParagraphThroughTextBoxes, noteDeletionOps, orderAddressingBeforeRemoval, orderBatchOperations, packageResourcesOpOf, paragraphHoldsContent, paragraphHoldsContentOnceAccepted, paragraphLength, paragraphsThroughTextBoxes, pendingSuggestionIdsIn, revisionSpan } from "@stll/docx-core/ops";
59
60
  import { EditorState } from "prosemirror-state";
60
61
  import { TableMap } from "prosemirror-tables";
61
62
  import { Mark } from "prosemirror-model";
@@ -604,6 +605,28 @@ const CANONICAL_PUBLIC_OPERATION_DISPOSITIONS = {
604
605
  mergeTableCells: "compile",
605
606
  splitTableCell: "compile"
606
607
  };
608
+ /**
609
+ * A request the operation vocabulary does not take, or names a place the
610
+ * document has no address for: refused as the request, not as a capability
611
+ * the session lacks.
612
+ */
613
+ const INVALID_REQUEST = { condition: CANONICAL_CONDITION.invalidRequest };
614
+ /** A place the operation named that an earlier change of its batch moved on. */
615
+ const STALE = { condition: CANONICAL_CONDITION.stale };
616
+ /** A shape the session built itself and then could not read back: a defect. */
617
+ const INTERNAL = { condition: CANONICAL_CONDITION.internal };
618
+ /**
619
+ * The public reason a batch the session refused to stage reports: a no-op
620
+ * for one that changes nothing, a content control's lock as the lock, a
621
+ * document that moved on as a stale range, and any other refusal as a block
622
+ * the session does not take, under the session's own ground.
623
+ */
624
+ const stagingRefusalReason = (reason, ground) => {
625
+ if (reason === "noChange") return "noopOperation";
626
+ if (ground.rule === CANONICAL_RULE.contentControlLock) return "contentControlLock";
627
+ if (ground.condition === CANONICAL_CONDITION.stale) return "staleRange";
628
+ return "unsupportedBlock";
629
+ };
607
630
  const resolveComment = ({ operation, from, to }) => {
608
631
  if ("comment" in operation && operation.comment !== void 0) return {
609
632
  type: "commented",
@@ -690,7 +713,7 @@ const resolveParagraphProperties = ({ operation, paragraph, projection, mintList
690
713
  });
691
714
  if (Object.keys(patch).length === 0) return refusal("emptyOperation");
692
715
  const at = projection.addressAt(paragraph.start);
693
- if (at.isErr()) return refusal("unsupportedBlock");
716
+ if (at.isErr()) return refusal("unsupportedBlock", void 0, at.error.ground);
694
717
  const intents = [{
695
718
  type: "formatParagraph",
696
719
  at: at.value,
@@ -1017,7 +1040,7 @@ const resolveBlockInsertion = ({ operation, listStart, paragraph, named, formatt
1017
1040
  };
1018
1041
  const stated = statedNumbering(requested, mintList);
1019
1042
  const inline = operation.lineBreakMode === "inline";
1020
- if (markdown === void 0 && !noteReferenceEditsAllowed() && /\[\^(?:e)?\d+\]/u.test(text)) return refusal("unsupportedBlock", "Canonical block insertion requires plain text.");
1043
+ if (markdown === void 0 && !noteReferenceEditsAllowed() && /\[\^(?:e)?\d+\]/u.test(text)) return refusal("protectedReference", "An insertion writes no note marker of its own.");
1021
1044
  const split = markdown === void 0 && !inline && LINE_BREAK_PATTERN.test(text);
1022
1045
  const lines = split ? text.split(LINE_BREAK_PATTERN).filter((line) => line.trim().length > 0) : [text];
1023
1046
  const texts = lines.length === 0 ? [""] : lines;
@@ -1081,7 +1104,7 @@ const resolveBlockInsertion = ({ operation, listStart, paragraph, named, formatt
1081
1104
  },
1082
1105
  position: listStart.position
1083
1106
  };
1084
- if (place === void 0) return refusal("unsupportedBlock", "Canonical insertion beside a table needs a paragraph on that side of it.");
1107
+ if (place === void 0) return refusal("unsupportedBlock", "Canonical insertion beside a table needs a paragraph on that side of it.", INVALID_REQUEST);
1085
1108
  const intents = [{
1086
1109
  type: "insertParagraphs",
1087
1110
  story,
@@ -1090,7 +1113,7 @@ const resolveBlockInsertion = ({ operation, listStart, paragraph, named, formatt
1090
1113
  ...stated.newList === void 0 ? {} : { newList: stated.newList }
1091
1114
  }];
1092
1115
  const { position } = place;
1093
- if (operation.comment !== void 0 && texts.every((line) => line.length === 0)) return refusal("unsupportedBlock");
1116
+ if (operation.comment !== void 0 && texts.every((line) => line.length === 0)) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
1094
1117
  const resolved = {
1095
1118
  intents,
1096
1119
  normalizations: split ? [{
@@ -1118,13 +1141,17 @@ const resolveBlockInsertion = ({ operation, listStart, paragraph, named, formatt
1118
1141
  blockId: place.at.blockId,
1119
1142
  offset: 0
1120
1143
  };
1144
+ const beside = place.at.type === "after" ? projection.paragraph(place.at.blockId) : void 0;
1121
1145
  return Result.ok({
1122
1146
  type: "commented",
1123
1147
  operation,
1124
1148
  comment: {
1125
1149
  text: operation.comment.text,
1126
1150
  from: anchor,
1127
- to: anchor,
1151
+ to: beside === void 0 ? anchor : {
1152
+ ...anchor,
1153
+ offset: paragraphLength(beside.source)
1154
+ },
1128
1155
  inserted: true
1129
1156
  },
1130
1157
  ...resolved
@@ -1705,7 +1732,7 @@ const resolveTableInsertion = ({ operation, listStart, paragraph, projection, st
1705
1732
  parties: operation.parties
1706
1733
  });
1707
1734
  }
1708
- if (node === null) return refusal("unsupportedBlock");
1735
+ if (node === null) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
1709
1736
  const attrs = expectTableAttrs(node);
1710
1737
  const formatting = tableAttrsToFormatting(attrs);
1711
1738
  const table = {
@@ -1780,7 +1807,15 @@ const resolveTableInsertion = ({ operation, listStart, paragraph, projection, st
1780
1807
  noteReferences
1781
1808
  });
1782
1809
  const pendingJoinRefusal = () => refusal(PENDING_JOIN_INSERTION_REFUSAL.reason, PENDING_JOIN_INSERTION_REFUSAL.message);
1783
- const followsDeletedBreak = (previous) => previous?.type.name === "paragraph" && isDeletedPPrMark(previous.attrs["pPrMark"]) && !paragraphGoes(previous, "accept");
1810
+ const followsDeletedBreak = (position) => {
1811
+ const $position = projection.doc.resolve(position);
1812
+ for (let index = $position.index() - 1; index >= 0; index--) {
1813
+ const previous = $position.parent.child(index);
1814
+ if (previous.type.name !== "paragraph" || !isDeletedPPrMark(previous.attrs["pPrMark"])) return false;
1815
+ if (!paragraphGoes(previous, "accept")) return true;
1816
+ }
1817
+ return false;
1818
+ };
1784
1819
  const pendingBreakRefusal = () => refusal(PENDING_BREAK_TABLE_REFUSAL.reason, PENDING_BREAK_TABLE_REFUSAL.message);
1785
1820
  const outer = findOutermostTableBoundary(projection.doc, paragraph.start - 1);
1786
1821
  if (outer !== null) {
@@ -1790,7 +1825,7 @@ const resolveTableInsertion = ({ operation, listStart, paragraph, projection, st
1790
1825
  table: outerTable,
1791
1826
  tableStart: outer.before + 1
1792
1827
  });
1793
- if (blockId === void 0) return refusal("unsupportedBlock");
1828
+ if (blockId === void 0) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
1794
1829
  return besideTable(blockId, outer[side]);
1795
1830
  }
1796
1831
  const { place } = besidePendingJoin({
@@ -1803,7 +1838,7 @@ const resolveTableInsertion = ({ operation, listStart, paragraph, projection, st
1803
1838
  const neighbour = $place.parent.maybeChild($place.index() + (side === "after" ? 1 : -1));
1804
1839
  const gap = side === "after" ? place.start - 1 + place.node.nodeSize : place.start - 1;
1805
1840
  if (stopsPendingJoin(gap)) return pendingJoinRefusal();
1806
- if (side === "after" && followsDeletedBreak(place.node)) return pendingBreakRefusal();
1841
+ if (side === "after" && followsDeletedBreak(gap)) return pendingBreakRefusal();
1807
1842
  if (side === "before") {
1808
1843
  const start = insertionGap(projection.doc, gap, side);
1809
1844
  const pending = start < gap ? projection.doc.nodeAt(start) : null;
@@ -1814,7 +1849,7 @@ const resolveTableInsertion = ({ operation, listStart, paragraph, projection, st
1814
1849
  });
1815
1850
  if (address !== void 0) {
1816
1851
  if (stopsPendingJoin(start)) return pendingJoinRefusal();
1817
- if (followsDeletedBreak(projection.doc.resolve(start).nodeBefore)) return pendingBreakRefusal();
1852
+ if (followsDeletedBreak(start)) return pendingBreakRefusal();
1818
1853
  return besideTable(address, start);
1819
1854
  }
1820
1855
  }
@@ -2085,7 +2120,7 @@ const resolveTableStructure = ({ operation, paragraph, projection, story, refusa
2085
2120
  bottom: 0
2086
2121
  }, column);
2087
2122
  const addressed = at === void 0 ? void 0 : projection.addressAt(at);
2088
- if (addressed === void 0 || addressed.isErr()) return refusal("unsupportedBlock");
2123
+ if (addressed === void 0 || addressed.isErr()) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
2089
2124
  const address = addressed.value;
2090
2125
  const blockId = deleted.has(address.blockId) ? keptTableAddress({
2091
2126
  projection,
@@ -2123,7 +2158,7 @@ const resolveTableStructure = ({ operation, paragraph, projection, story, refusa
2123
2158
  if (overflow !== null) return refusal("payloadDoesNotFit", overflow);
2124
2159
  if (tracked && columnInsertionWidensCell(row.table, insertion.columnIndex)) return skipTracked("A suggested column cannot widen a cell that spans other columns.");
2125
2160
  const blockId = tableBlockAddress(projection, row, deleted);
2126
- if (blockId === void 0) return refusal("unsupportedBlock");
2161
+ if (blockId === void 0) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
2127
2162
  return resolved({
2128
2163
  type: "table",
2129
2164
  operation: {
@@ -2167,7 +2202,7 @@ const resolveTableStructure = ({ operation, paragraph, projection, story, refusa
2167
2202
  if (new Set(cellsIn(map, rectangle)).size < 2) return skipAlike("unsupportedBlock", "The merge covers a single merged cell.");
2168
2203
  if (tracked && !mergesDownOverEmptyCells(row.table, map, rectangle)) return skipTracked("A suggested merge takes one column over empty cells.");
2169
2204
  const blockId = tableBlockAddress(projection, row, deleted);
2170
- if (blockId === void 0) return refusal("unsupportedBlock");
2205
+ if (blockId === void 0) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
2171
2206
  return resolved({
2172
2207
  type: "table",
2173
2208
  operation: {
@@ -2213,12 +2248,12 @@ const resolveTableStructure = ({ operation, paragraph, projection, story, refusa
2213
2248
  revision: null,
2214
2249
  ...template === void 0 ? {} : { template }
2215
2250
  });
2216
- if (built.type !== "applied") return refusal("unsupportedBlock");
2251
+ if (built.type !== "applied") return refusal("unsupportedBlock", void 0, INTERNAL);
2217
2252
  const table = built.transaction.doc.nodeAt(built.transaction.mapping.map(row.tablePosition, -1));
2218
- if (table === null || table.type.name !== "table") return refusal("unsupportedBlock");
2253
+ if (table === null || table.type.name !== "table") return refusal("unsupportedBlock", void 0, INTERNAL);
2219
2254
  const index = side === "before" ? row.rowIndex : row.rowIndex + 1;
2220
2255
  const inserted = standaloneTableRowsFromProseMirror(table)[index];
2221
- if (inserted === void 0) return refusal("unsupportedBlock");
2256
+ if (inserted === void 0) return refusal("unsupportedBlock", void 0, INTERNAL);
2222
2257
  const { structuralChange: _structuralChange, propertyChanges: _propertyChanges, ...plain } = inserted;
2223
2258
  return resolved({
2224
2259
  type: "tableRow",
@@ -2286,6 +2321,49 @@ const emphasisRuns = (line) => parseInlineEmphasisRuns(line).flatMap(({ text, bo
2286
2321
  }
2287
2322
  }];
2288
2323
  });
2324
+ /**
2325
+ * The spans of the words a replacement writes that its paired `**bold**` and
2326
+ * `***bold italic***` markers mark, and the emphasis each states.
2327
+ */
2328
+ const emphasizedSpans = (emphasis) => {
2329
+ const spans = [];
2330
+ let offset = 0;
2331
+ for (const { text, bold, italic } of emphasis ?? []) {
2332
+ const end = offset + text.length;
2333
+ if (end > offset && (bold || italic)) spans.push({
2334
+ start: offset,
2335
+ end,
2336
+ patch: {
2337
+ ...bold ? { bold: true } : {},
2338
+ ...italic ? { italic: true } : {}
2339
+ }
2340
+ });
2341
+ offset = end;
2342
+ }
2343
+ return spans;
2344
+ };
2345
+ /** A plan that replaces the whole match, its words standing together. */
2346
+ const rewriteWhole = (source, target) => [{
2347
+ start: 0,
2348
+ end: source.length,
2349
+ text: target
2350
+ }];
2351
+ /**
2352
+ * Paragraph properties kept by a replacement that drops the paragraph's
2353
+ * formatting: the review records of its numbering, which only resolving
2354
+ * them retires.
2355
+ */
2356
+ const NUMBERING_REVIEW_RECORDS = /* @__PURE__ */ new Set(["numberingChangeXml", "numberingInsertionXml"]);
2357
+ /**
2358
+ * The patch a replacement that drops the paragraph's formatting writes:
2359
+ * every property the paragraph states goes, as the default engine writes a
2360
+ * fresh paragraph, save the review records of its numbering.
2361
+ */
2362
+ const droppedParagraphFormatting = (formatting) => {
2363
+ const patch = {};
2364
+ for (const key of Object.keys(formatting ?? {})) if (!NUMBERING_REVIEW_RECORDS.has(key)) patch[key] = null;
2365
+ return patch;
2366
+ };
2289
2367
  const inlineText = (line) => line.split(/(\t|\r\n|\r|\n)/u).flatMap((part) => {
2290
2368
  if (part === " ") return [{ type: "tab" }];
2291
2369
  if (LINE_BREAK_PATTERN.test(part)) return [{ type: "break" }];
@@ -2294,6 +2372,15 @@ const inlineText = (line) => line.split(/(\t|\r\n|\r|\n)/u).flatMap((part) => {
2294
2372
  text: part
2295
2373
  }];
2296
2374
  });
2375
+ const PROPERTY_FOLDING_INTENTS = /* @__PURE__ */ new Set([
2376
+ "joinParagraphs",
2377
+ "splitParagraph",
2378
+ "formatParagraph",
2379
+ "setList",
2380
+ "deleteParagraphs"
2381
+ ]);
2382
+ /** Each paragraph property change of the story, by revision id. */
2383
+ const propertyChangesById = (document, story) => new Map(paragraphsThroughTextBoxes(document, story).flatMap(({ paragraph }) => paragraph.propertyChanges?.map((change) => [change.info.id, change]) ?? []));
2297
2384
  /**
2298
2385
  * Room past the highest revision or annotation id below which a batch draws
2299
2386
  * its revision ids from the free ones instead: more than any one batch asks.
@@ -2351,12 +2438,13 @@ const primaryRevisionId = ({ operation, intents, document, revisionIds }) => {
2351
2438
  const deletion = mark?.kind === "del" ? mark.info.id : mark?.deletion?.info.id;
2352
2439
  return deletion !== void 0 && revisionIds.includes(deletion) ? deletion : revisionIds.at(0);
2353
2440
  };
2354
- const compilePublicIntents = ({ document, intents, mode, author, date, suggestionId, nextRevisionId, allocate, reservedBlockIds, idLease, paragraphAllocationLease, allocations: admittedAllocations, verifyOperation }) => {
2441
+ const compilePublicIntents = ({ document, intents, mode, author, date, suggestionId, nextRevisionId, allocate, reservedBlockIds, idLease, paragraphAllocationLease, allocations: admittedAllocations, verifyOperation, story }) => {
2355
2442
  const ops = [];
2356
2443
  const recorded = [];
2357
2444
  let verifiedOperation;
2358
2445
  const absorbed = [];
2359
2446
  const source = document;
2447
+ const standing = mode === "direct" || !intents.some((intent) => PROPERTY_FOLDING_INTENTS.has(intent.type)) ? [] : [...propertyChangesById(source, story)].flatMap(([id, change]) => change.resolvesWith !== void 0 && change.info.author === author && change.info.date === date && change.info.suggestionId === suggestionId ? [[id, JSON.stringify(change)]] : []);
2360
2448
  const joinedInto = /* @__PURE__ */ new Map();
2361
2449
  const allocated = /* @__PURE__ */ new Map();
2362
2450
  const allocations = [];
@@ -2452,6 +2540,12 @@ const compilePublicIntents = ({ document, intents, mode, author, date, suggestio
2452
2540
  appliedRevisions.push(...notes.revisions);
2453
2541
  }
2454
2542
  document = after;
2543
+ const now = standing.length === 0 ? void 0 : propertyChangesById(after, story);
2544
+ if (now !== void 0 && standing.some(([id, change]) => JSON.stringify(now.get(id)) !== change)) return Result.err(new DocumentOpRefusal({
2545
+ reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_PARAGRAPH_PROPERTY_CHANGE,
2546
+ message: "Resolve the pending paragraph join before tracking a different change to its properties.",
2547
+ opType: void 0
2548
+ }));
2455
2549
  ops.push(...compiled.value.ops, ...notes?.ops ?? []);
2456
2550
  recorded.push({
2457
2551
  revisions: appliedRevisions,
@@ -2931,8 +3025,7 @@ var CanonicalPublicOperations = class {
2931
3025
  });
2932
3026
  };
2933
3027
  const refuseResolution = (id, error) => {
2934
- const gap = error.gap === null ? void 0 : error.gap ?? (error.reason === "unsupportedBlock" ? CANONICAL_GAP.publicUnsupportedInline : void 0);
2935
- if (gap !== void 0) refusals.set(id, { gap });
3028
+ if (error.ground !== void 0) refusals.set(id, error.ground);
2936
3029
  skip(id, error.reason, error.detail);
2937
3030
  };
2938
3031
  const result = (applied, undoHandle, disposition = "normal") => {
@@ -3046,12 +3139,6 @@ var CanonicalPublicOperations = class {
3046
3139
  skip(operation.id, undefinedReference.reason, undefinedReference.message);
3047
3140
  continue;
3048
3141
  }
3049
- const disposition = CANONICAL_PUBLIC_OPERATION_DISPOSITIONS[operation.type];
3050
- if (disposition !== "compile") {
3051
- refusals.set(operation.id, { gap: disposition });
3052
- skip(operation.id, "unsupportedBlock");
3053
- continue;
3054
- }
3055
3142
  const compiled = this.resolve({
3056
3143
  operation,
3057
3144
  options,
@@ -3307,6 +3394,7 @@ var CanonicalPublicOperations = class {
3307
3394
  };
3308
3395
  const compiled = compilePublicIntents({
3309
3396
  document: withHeadings,
3397
+ story,
3310
3398
  intents: mappedIntents,
3311
3399
  allocate,
3312
3400
  reservedBlockIds,
@@ -3351,8 +3439,13 @@ var CanonicalPublicOperations = class {
3351
3439
  story,
3352
3440
  ops: compiled.value.ops
3353
3441
  });
3442
+ if (id.isErr()) return declined({
3443
+ reason: "unsupportedBlock",
3444
+ message: id.error.message,
3445
+ refusal: groundForDocumentOpRefusal(id.error.reason)
3446
+ });
3354
3447
  const commentContent = admittedComment?.content ?? canonicalCommentBody(nextDocument, comment.text, commentLease);
3355
- const commented = id.isErr() || firstAdded?.paraId === void 0 || lastAdded?.paraId === void 0 ? void 0 : compileCanonicalComments({
3448
+ const commented = compileCanonicalComments({
3356
3449
  document: nextDocument,
3357
3450
  idLease,
3358
3451
  command: {
@@ -3365,7 +3458,10 @@ var CanonicalPublicOperations = class {
3365
3458
  content: commentContent,
3366
3459
  ...proposedBy
3367
3460
  },
3368
- anchor: {
3461
+ anchor: firstAdded?.paraId === void 0 || lastAdded?.paraId === void 0 ? {
3462
+ kind: "point",
3463
+ at: comment.to
3464
+ } : {
3369
3465
  kind: "range",
3370
3466
  from: {
3371
3467
  story,
@@ -3380,10 +3476,10 @@ var CanonicalPublicOperations = class {
3380
3476
  }
3381
3477
  }
3382
3478
  });
3383
- if (commented === void 0 || commented.isErr() || id.isErr()) return declined({
3479
+ if (commented.isErr()) return declined({
3384
3480
  reason: "unsupportedBlock",
3385
- message: commented?.isErr() === true ? commented.error.message : "The inserted paragraphs cannot carry the comment.",
3386
- refusal: { gap: CANONICAL_GAP.publicComments }
3481
+ message: commented.error.message,
3482
+ refusal: commented.error.ground
3387
3483
  });
3388
3484
  nextDocument = commented.value.document;
3389
3485
  operationOps.push(...commented.value.ops);
@@ -3401,10 +3497,15 @@ var CanonicalPublicOperations = class {
3401
3497
  });
3402
3498
  const before = anchorIn(sourceDocument);
3403
3499
  const after = anchorIn(nextDocument);
3404
- if (id.isErr() || before === void 0 || after === void 0) return declined({
3500
+ if (id.isErr()) return declined({
3405
3501
  reason: "unsupportedBlock",
3406
- message: id.isErr() ? id.error.message : "The comment anchor no longer exists.",
3407
- refusal: { gap: CANONICAL_GAP.publicComments }
3502
+ message: id.error.message,
3503
+ refusal: groundForDocumentOpRefusal(id.error.reason)
3504
+ });
3505
+ if (before === void 0 || after === void 0) return declined({
3506
+ reason: "missingBlock",
3507
+ message: "The comment anchor no longer exists.",
3508
+ refusal: STALE
3408
3509
  });
3409
3510
  const changed = batch.mode === "direct" ? void 0 : revisionSpan(after.content, new Set(compiled.value.revisions));
3410
3511
  const from = changed === void 0 ? shift(comment.from) : {
@@ -3447,7 +3548,7 @@ var CanonicalPublicOperations = class {
3447
3548
  if (commented.isErr()) return declined({
3448
3549
  reason: "unsupportedBlock",
3449
3550
  message: commented.error.message,
3450
- refusal: { gap: CANONICAL_GAP.publicComments }
3551
+ refusal: commented.error.ground
3451
3552
  });
3452
3553
  nextDocument = commented.value.document;
3453
3554
  operationOps.push(...commented.value.ops);
@@ -3868,10 +3969,11 @@ var CanonicalPublicOperations = class {
3868
3969
  if (ops.length === 0) return result([], null);
3869
3970
  const prepared = projected.value.selectionAt(state).andThen((selection) => reuseStaging ? operationStaging.prepare(state, selection) : operationStaging.prepareOps(state, ops, selection));
3870
3971
  if (prepared.isErr()) {
3871
- const noChange = prepared.error.reason === "noChange";
3972
+ const { reason, ground, message } = prepared.error;
3973
+ const skipReason = stagingRefusalReason(reason, ground);
3872
3974
  for (const { id } of appliedById.values()) {
3873
- if (!noChange) refusals.set(id, { gap: CANONICAL_GAP.publicUnsupportedInline });
3874
- skip(id, noChange ? "noopOperation" : "unsupportedBlock", prepared.error.message);
3975
+ if (reason !== "noChange") refusals.set(id, ground);
3976
+ skip(id, skipReason, message);
3875
3977
  }
3876
3978
  return result([], null);
3877
3979
  }
@@ -4017,7 +4119,7 @@ var CanonicalPublicOperations = class {
4017
4119
  * the mark are marked deleted.
4018
4120
  */
4019
4121
  resolveBlockDeletion({ operation, paragraph, projection, projectionStory, doc, tracked, deletesJoinedWords, gainsFollower, keepsTablesApart, followsInsertedTable, precedesInsertedTable, bordersRemovedTable, previousGainsFollower, tableBeforeGainsFollower, endsOnceAccepted, deletedRun, deletedByBatch, refusal }) {
4020
- if (operation.comment !== void 0 && !tracked) return refusal("unsupportedBlock");
4122
+ if (operation.comment !== void 0 && !tracked) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
4021
4123
  if (tracked && goesWholeOnAcceptance(paragraph.node)) return refusal("noopOperation");
4022
4124
  const end = paragraph.start + paragraph.node.content.size;
4023
4125
  const after = doc.resolve(end + 1).nodeAfter;
@@ -4030,7 +4132,7 @@ var CanonicalPublicOperations = class {
4030
4132
  const previous = followsInsertedTable ? void 0 : neighbour(before);
4031
4133
  const commentFrom = projection.addressAt(paragraph.start);
4032
4134
  const commentTo = projection.addressAt(end);
4033
- if (commentFrom.isErr() || commentTo.isErr()) return refusal("unsupportedBlock");
4135
+ if (commentFrom.isErr() || commentTo.isErr()) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
4034
4136
  const tracking = (resolved) => Result.ok(operation.comment === void 0 ? {
4035
4137
  type: "plain",
4036
4138
  operation,
@@ -4053,12 +4155,12 @@ var CanonicalPublicOperations = class {
4053
4155
  paragraph.node.descendants((node) => {
4054
4156
  if (node.isText && !node.marks.some(({ type }) => type.name === "insertion" || type.name === "deletion")) holdsOriginalWords = true;
4055
4157
  });
4056
- if (operation.moveId === void 0 && !gainsFollower && (keepsTablesApart || tracked && (after?.type.name === "table" || precedesInsertedTable) && isInsertedPPrMark(paragraph.node.attrs["pPrMark"]) && holdsOriginalWords)) {
4158
+ if (operation.moveId === void 0 && !gainsFollower && (keepsTablesApart || tracked && (after?.type.name === "table" || precedesInsertedTable) && isInsertedPPrMark(paragraph.node.attrs["pPrMark"]) && holdsOriginalWords && joinedWordsStart === void 0)) {
4057
4159
  if (paragraph.start === end) return refusal("noopOperation");
4058
4160
  const start = keepsTablesApart ? paragraph.start : joinedWordsStart ?? paragraph.start;
4059
4161
  const from = projection.addressAt(start);
4060
4162
  const to = projection.addressAt(end);
4061
- if (from.isErr() || to.isErr()) return refusal("unsupportedBlock");
4163
+ if (from.isErr() || to.isErr()) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
4062
4164
  return tracking({
4063
4165
  intents: [{
4064
4166
  type: "replaceText",
@@ -4113,7 +4215,7 @@ var CanonicalPublicOperations = class {
4113
4215
  const own = (from, to) => {
4114
4216
  const start = projection.addressAt(from);
4115
4217
  const stop = projection.addressAt(to);
4116
- return start.isErr() || stop.isErr() ? refusal("unsupportedBlock") : Result.ok(from === to ? [] : [{
4218
+ return start.isErr() || stop.isErr() ? refusal("unsupportedBlock", void 0, INVALID_REQUEST) : Result.ok(from === to ? [] : [{
4117
4219
  type: "replaceText",
4118
4220
  from: start.value,
4119
4221
  to: stop.value,
@@ -4202,7 +4304,7 @@ var CanonicalPublicOperations = class {
4202
4304
  if (previousGainsFollower && noDeletedRunBefore(deletedRun)) {
4203
4305
  const from = projection.addressAt(range.from);
4204
4306
  const to = projection.addressAt(end);
4205
- if (from.isErr() || to.isErr()) return refusal("unsupportedBlock");
4307
+ if (from.isErr() || to.isErr()) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
4206
4308
  return tracking({
4207
4309
  intents: [{
4208
4310
  type: "replaceText",
@@ -4220,7 +4322,7 @@ var CanonicalPublicOperations = class {
4220
4322
  if (after === null && tableBeforeGainsFollower) {
4221
4323
  const from = projection.addressAt(paragraph.start);
4222
4324
  const to = projection.addressAt(end);
4223
- if (from.isErr() || to.isErr()) return refusal("unsupportedBlock");
4325
+ if (from.isErr() || to.isErr()) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
4224
4326
  return tracking({
4225
4327
  intents: [{
4226
4328
  type: "replaceText",
@@ -4243,7 +4345,7 @@ var CanonicalPublicOperations = class {
4243
4345
  }
4244
4346
  const from = projection.addressAt(range.from);
4245
4347
  const to = projection.addressAt(range.to);
4246
- if (from.isErr() || to.isErr()) return refusal("unsupportedBlock");
4348
+ if (from.isErr() || to.isErr()) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
4247
4349
  return tracking({
4248
4350
  intents: [{
4249
4351
  type: "replaceText",
@@ -4284,10 +4386,11 @@ var CanonicalPublicOperations = class {
4284
4386
  if (anchor === void 0 || projection.isErr() || projection.value.paragraph(blockId) !== void 0) return Result.ok({ operation });
4285
4387
  const control = emptyControlOfFiller(state.doc, blockId);
4286
4388
  if (control === void 0) return Result.ok({ operation });
4287
- const refusal = (reason, message) => Result.err(new CanonicalPublicOperationResolutionError({
4389
+ const refusal = (reason, message, ground) => Result.err(new CanonicalPublicOperationResolutionError({
4288
4390
  reason,
4289
4391
  message: message ?? `The operation was refused: ${reason}.`,
4290
- detail: message
4392
+ detail: message,
4393
+ ...ground === void 0 ? {} : { ground }
4291
4394
  }));
4292
4395
  const fillerHash = hashFolioAIBlockContent("");
4293
4396
  if (operation.precondition && fillerHash !== operation.precondition.blockTextHash) return refusal("preconditionFailed");
@@ -4298,7 +4401,7 @@ var CanonicalPublicOperations = class {
4298
4401
  projection: projection.value
4299
4402
  });
4300
4403
  switch (beside.type) {
4301
- case "refused": return refusal("unsupportedBlock", beside.message);
4404
+ case "refused": return refusal("unsupportedBlock", beside.message, INVALID_REQUEST);
4302
4405
  case "beside": return Result.ok({ operation: beside.operation });
4303
4406
  case "listStart": return Result.ok({
4304
4407
  operation: beside.operation,
@@ -4308,22 +4411,21 @@ var CanonicalPublicOperations = class {
4308
4411
  }
4309
4412
  }
4310
4413
  resolveOperation({ operation, listStart, options, state, story, diff, tracked, suggested, mintList, besideDeletions, batchComments }) {
4311
- const refusal = (reason, message) => Result.err(new CanonicalPublicOperationResolutionError({
4414
+ const refusal = (reason, message, ground) => Result.err(new CanonicalPublicOperationResolutionError({
4312
4415
  reason,
4313
4416
  message: message ?? `The operation was refused: ${reason}.`,
4314
- detail: message
4417
+ detail: message,
4418
+ ...ground === void 0 ? {} : { ground }
4315
4419
  }));
4316
4420
  const skipAlike = (reason, message) => Result.err(new CanonicalPublicOperationResolutionError({
4317
4421
  reason,
4318
4422
  message,
4319
- detail: message,
4320
- gap: null
4423
+ detail: message
4321
4424
  }));
4322
4425
  const skipTracked = (message) => Result.err(new CanonicalPublicOperationResolutionError({
4323
4426
  reason: "unsupportedBlock",
4324
4427
  message,
4325
4428
  detail: message,
4326
- gap: null,
4327
4429
  refusedIn: "trackedMode"
4328
4430
  }));
4329
4431
  const notInTable = () => skipAlike("unsupportedBlock", "The block is not in a table.");
@@ -4356,7 +4458,7 @@ var CanonicalPublicOperations = class {
4356
4458
  const projection = this.options.session.projectStory(story);
4357
4459
  if (!anchor || projection.isErr()) return refusal("missingBlock");
4358
4460
  const paragraph = projection.value.paragraph(blockId);
4359
- if (!paragraph) return holdsParagraph(state.doc, blockId) ? refusal("unsupportedBlock", "The canonical session holds no address in this paragraph, such as one in a text box.") : refusal("missingBlock");
4461
+ if (!paragraph) return holdsParagraph(state.doc, blockId) ? refusal("unsupportedBlock", "The canonical session holds no address in this paragraph.", INVALID_REQUEST) : refusal("missingBlock");
4360
4462
  if ((operation.type === "insertTable" || operation.type === "insertSignatureTable") && !supportsTableInsertionMode(operation.type, options.batch.mode ?? "tracked-changes")) return refusal("unsupportedMode");
4361
4463
  const noteReferences = collectNoteReferenceLabels(state.doc);
4362
4464
  const clean = buildCleanBlockText(paragraph.node, paragraph.start - 1, {
@@ -4375,7 +4477,7 @@ var CanonicalPublicOperations = class {
4375
4477
  reason: pendingRefusal.reason,
4376
4478
  message: pendingRefusal.message ?? `The operation was refused: ${pendingRefusal.reason}.`,
4377
4479
  detail: pendingRefusal.message,
4378
- ...pendingRefusal.canonicalRefusal === void 0 ? {} : { gap: pendingRefusal.canonicalRefusal.gap }
4480
+ ...pendingRefusal.canonicalRefusal === void 0 ? {} : { ground: pendingRefusal.canonicalRefusal }
4379
4481
  }));
4380
4482
  const hash = hashFolioAIBlockContent(clean.text);
4381
4483
  if (operation.precondition && hash !== operation.precondition.blockTextHash) return refusal("preconditionFailed");
@@ -4581,7 +4683,7 @@ var CanonicalPublicOperations = class {
4581
4683
  if (start <= 0 || start >= clean.text.length || clean.text.slice(start, end) !== (operation.separator ?? "")) return refusal("staleRange");
4582
4684
  break;
4583
4685
  case "mergeBlockWithNext":
4584
- if (/[\t\r\n]/u.test(operation.separator ?? "")) return refusal("unsupportedBlock", "Canonical public join separators require plain text.");
4686
+ if (/\r/u.test(operation.separator ?? "")) return refusal("unsupportedBlock", "Canonical public join separators hold no carriage return.", INVALID_REQUEST);
4585
4687
  start = clean.text.length;
4586
4688
  end = start;
4587
4689
  break;
@@ -4600,12 +4702,15 @@ var CanonicalPublicOperations = class {
4600
4702
  if (!range) return Result.err(new CanonicalPublicOperationResolutionError({
4601
4703
  reason: "unsupportedBlock",
4602
4704
  message: "The range begins or ends inside a field result or holds a page-break run.",
4603
- detail: void 0,
4604
- gap: null
4705
+ detail: void 0
4605
4706
  }));
4606
4707
  const dropsFormatting = operation.type === "replaceBlock" && operation.preserveFormatting === false;
4607
- if (replacesText && references.length > 0 && (dropsFormatting || stripInlineEmphasisMarkers(text) !== text)) return refusal("protectedReference");
4608
- if (dropsFormatting) return refusal("unsupportedBlock", "Canonical replacements that drop the paragraph's formatting are unavailable.");
4708
+ const emphasis = replacesText && hasInlineEmphasis(text) ? parseInlineEmphasisRuns(text) : void 0;
4709
+ if (replacesText && references.length > 0 && (dropsFormatting || emphasis !== void 0)) return refusal("protectedReference");
4710
+ if (emphasis !== void 0) text = stripInlineEmphasisMarkers(text);
4711
+ const rebuilds = !tracked && dropsFormatting;
4712
+ const emphasized = tracked ? [] : emphasizedSpans(emphasis);
4713
+ const rewritesWhole = rebuilds || emphasized.length > 0;
4609
4714
  const kept = segmentsAroundNoteReferences(clean.text.slice(start, end), replacesText ? text : clean.text.slice(start, end), references);
4610
4715
  const editsReferences = kept === null && replacesText && noteReferenceEditsAllowed();
4611
4716
  const segments = editsReferences ? {
@@ -4617,11 +4722,11 @@ var CanonicalPublicOperations = class {
4617
4722
  } : kept;
4618
4723
  if (segments === null) return refusal("protectedReference");
4619
4724
  const prose = replacesText ? segments.replacement.join("") : "";
4620
- if (stripInlineEmphasisMarkers(text) !== text) return refusal("unsupportedBlock", "Canonical public emphasis replacements are unavailable.");
4621
- if (!editsReferences && /\[\^(?:e)?\d+\]/u.test(prose) || /\r/u.test(prose)) return refusal("unsupportedBlock", "Canonical public replacements require plain text.");
4725
+ if (!editsReferences && /\[\^(?:e)?\d+\]/u.test(prose)) return refusal("protectedReference", "A replacement writes no note marker of its own.");
4726
+ if (/\r/u.test(prose)) return refusal("unsupportedBlock", "Canonical public replacements require plain text.", INVALID_REQUEST);
4622
4727
  const from = projection.value.addressAt(range.from);
4623
4728
  const to = projection.value.addressAt(range.to);
4624
- if (from.isErr() || to.isErr()) return refusal("unsupportedBlock");
4729
+ if (from.isErr() || to.isErr()) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
4625
4730
  const resolvedComment = resolveComment({
4626
4731
  operation,
4627
4732
  from: from.value,
@@ -4643,7 +4748,7 @@ var CanonicalPublicOperations = class {
4643
4748
  properties: { styleId: operation.styleId },
4644
4749
  mintList
4645
4750
  }) : [];
4646
- if (resolvedComment.type === "plain" && operation.type !== "splitBlock" && operation.type !== "formatRange" && operation.type !== "mergeBlockWithNext" && restyle.length === 0 && clean.text.slice(start, end) === text) return refusal("noopOperation");
4751
+ if (resolvedComment.type === "plain" && operation.type !== "splitBlock" && operation.type !== "formatRange" && operation.type !== "mergeBlockWithNext" && restyle.length === 0 && !rewritesWhole && clean.text.slice(start, end) === text) return refusal("noopOperation");
4647
4752
  let intent;
4648
4753
  switch (operation.type) {
4649
4754
  case "splitBlock":
@@ -4727,22 +4832,37 @@ var CanonicalPublicOperations = class {
4727
4832
  length: boundary.length
4728
4833
  }] : [])
4729
4834
  };
4835
+ let planChanges = planTextChanges;
4836
+ if (tracked) planChanges = (source, target) => changesFromSegments(diff(source, target));
4837
+ if (rewritesWhole) planChanges = rewriteWhole;
4730
4838
  let planned = planReplacementChanges({
4731
4839
  ...replacementSource,
4732
- planChanges: tracked ? (source, target) => changesFromSegments(diff(source, target)) : planTextChanges,
4840
+ planChanges,
4733
4841
  ...tracked ? { keepFieldsOf: planTextChanges } : {}
4734
4842
  });
4735
4843
  const addedComments = tracked ? batchCommentSpans(batchComments, blockId, clean.text) : [];
4736
- const changesCommentedWords = (changes) => changes?.some((change) => clean.offsets.slice(start + change.start, start + change.end).some((position) => paragraph.node.nodeAt(position - paragraph.start)?.marks.some((mark) => mark.type.name === "comment")) || change.end > change.start && addedComments.some((span) => span.start < start + change.end && start + change.start < span.end)) === true;
4737
- if (tracked && changesCommentedWords([{
4844
+ const commentedAt = (index) => {
4845
+ const position = clean.offsets[index];
4846
+ return position !== void 0 && paragraph.node.nodeAt(position - paragraph.start)?.marks.some((mark) => mark.type.name === "comment") === true;
4847
+ };
4848
+ const commentTouchesGap = (gap) => commentedAt(gap - 1) || commentedAt(gap) || addedComments.some((span) => span.start <= gap && gap <= span.end);
4849
+ const touchesComment = (changes) => changes?.some((change) => {
4850
+ const changeStart = start + change.start;
4851
+ const changeEnd = start + change.end;
4852
+ for (let index = changeStart; index < changeEnd; index++) if (commentedAt(index)) return true;
4853
+ if (changeEnd > changeStart && addedComments.some((span) => span.start < changeEnd && changeStart < span.end)) return true;
4854
+ return change.text.length > 0 && (commentTouchesGap(changeStart) || commentTouchesGap(changeEnd));
4855
+ }) === true;
4856
+ if (tracked && touchesComment([{
4738
4857
  start: 0,
4739
- end: end - start
4858
+ end: end - start,
4859
+ text
4740
4860
  }])) {
4741
4861
  const directCuts = planReplacementChanges({
4742
4862
  ...replacementSource,
4743
4863
  planChanges: planTextChanges
4744
4864
  });
4745
- if (changesCommentedWords(planned) || changesCommentedWords(directCuts)) planned = directCuts;
4865
+ if (touchesComment(planned) || touchesComment(directCuts)) planned = directCuts;
4746
4866
  }
4747
4867
  if (planned === null) return panic("A replacement's planned changes must reproduce it.");
4748
4868
  const changes = cutAroundRepeatedSeparators(replacementSource.source, planned).map((change) => ({
@@ -4773,7 +4893,7 @@ var CanonicalPublicOperations = class {
4773
4893
  };
4774
4894
  const addressable = (placed) => placed.every(({ from: changeFrom, to: changeTo }) => projection.value.addressAt(changeFrom, changeFrom < changeTo ? "afterMarkers" : void 0).isOk() && projection.value.addressAt(changeTo, changeFrom < changeTo ? "beforeMarkers" : void 0).isOk());
4775
4895
  let replacementChanges = placeChanges(changes);
4776
- if (replacementChanges === void 0) return refusal("unsupportedBlock");
4896
+ if (replacementChanges === void 0) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
4777
4897
  if (!addressable(replacementChanges)) {
4778
4898
  const whole = placeChanges(segments.source.flatMap((piece, index) => {
4779
4899
  const replacement = segments.replacement[index] ?? "";
@@ -4785,7 +4905,7 @@ var CanonicalPublicOperations = class {
4785
4905
  text: replacement
4786
4906
  }];
4787
4907
  }));
4788
- if (whole === void 0) return refusal("unsupportedBlock");
4908
+ if (whole === void 0) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
4789
4909
  replacementChanges = whole;
4790
4910
  }
4791
4911
  const comments = readModel(this.options.session.document).package.document.comments ?? [];
@@ -4813,7 +4933,7 @@ var CanonicalPublicOperations = class {
4813
4933
  }
4814
4934
  })) return Result.err(new CanonicalPublicOperationResolutionError({
4815
4935
  reason: "unsupportedBlock",
4816
- gap: CANONICAL_GAP.commentReplacementAlignment,
4936
+ ground: { gap: CANONICAL_GAP.commentReplacementAlignment },
4817
4937
  message: "Canonical replacement cannot preserve the aligned comment ranges.",
4818
4938
  detail: "Canonical replacement cannot preserve the aligned comment ranges."
4819
4939
  }));
@@ -4850,7 +4970,7 @@ var CanonicalPublicOperations = class {
4850
4970
  });
4851
4971
  const clearedFrom = cleared && projection.value.addressAt(cleared.from, "afterMarkers");
4852
4972
  const clearedTo = cleared && projection.value.addressAt(cleared.to, "beforeMarkers");
4853
- if (!clearedFrom || !clearedTo || clearedFrom.isErr() || clearedTo.isErr()) return refusal("unsupportedBlock");
4973
+ if (!clearedFrom || !clearedTo || clearedFrom.isErr() || clearedTo.isErr()) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
4854
4974
  intents.push({
4855
4975
  type: "formatRun",
4856
4976
  from: clearedFrom.value,
@@ -4899,6 +5019,7 @@ var CanonicalPublicOperations = class {
4899
5019
  });
4900
5020
  }
4901
5021
  }
5022
+ let wordsStart;
4902
5023
  for (const [index, change] of [...replacementChanges.entries()].reverse()) {
4903
5024
  let gap = {
4904
5025
  from: change.from,
@@ -4911,7 +5032,7 @@ var CanonicalPublicOperations = class {
4911
5032
  const tailStart = sourceHolder.after();
4912
5033
  const tailFrom = projection.value.addressAt(tailStart, "afterMarkers");
4913
5034
  const tailTo = projection.value.addressAt(gap.to, "beforeMarkers");
4914
- if (tailFrom.isErr() || tailTo.isErr()) return refusal("unsupportedBlock");
5035
+ if (tailFrom.isErr() || tailTo.isErr()) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
4915
5036
  intents.push({
4916
5037
  type: "replaceText",
4917
5038
  from: tailFrom.value,
@@ -4931,7 +5052,7 @@ var CanonicalPublicOperations = class {
4931
5052
  } : void 0;
4932
5053
  const changeFrom = projection.value.addressAt(gap.from, edges?.start);
4933
5054
  const changeTo = projection.value.addressAt(gap.to, edges?.end);
4934
- if (changeFrom.isErr() || changeTo.isErr()) return refusal("unsupportedBlock");
5055
+ if (changeFrom.isErr() || changeTo.isErr()) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
4935
5056
  let inside = controlEdgesAt(projection.value.doc, gap.from, gap.to);
4936
5057
  if (gap.from === gap.to && (inside.start === true || inside.end === true)) {
4937
5058
  const edge = projection.value.doc.resolve(gap.from);
@@ -4941,6 +5062,7 @@ var CanonicalPublicOperations = class {
4941
5062
  ...inside,
4942
5063
  ...change.start === start ? { start: true } : { end: true }
4943
5064
  };
5065
+ if (index === 0) wordsStart = changeFrom.value;
4944
5066
  intents.push({
4945
5067
  type: "replaceText",
4946
5068
  from: changeFrom.value,
@@ -4948,15 +5070,45 @@ var CanonicalPublicOperations = class {
4948
5070
  text: change.text,
4949
5071
  ...sources === void 0 ? {} : { formattingSources: sources },
4950
5072
  ...Object.keys(inside).length === 0 ? {} : { inside },
5073
+ ...rebuilds ? { runProps: {} } : {},
4951
5074
  ...intent.runPropsPatch === void 0 ? {} : { runPropsPatch: intent.runPropsPatch }
4952
5075
  });
4953
5076
  }
5077
+ if (wordsStart !== void 0) for (const { start: spanStart, end: spanEnd, patch } of emphasized) {
5078
+ const { story: wordsStory, blockId: wordsBlockId } = wordsStart;
5079
+ intents.push({
5080
+ type: "formatRun",
5081
+ from: spanStart === 0 ? wordsStart : {
5082
+ story: wordsStory,
5083
+ blockId: wordsBlockId,
5084
+ offset: wordsStart.offset + spanStart
5085
+ },
5086
+ to: {
5087
+ story: wordsStory,
5088
+ blockId: wordsBlockId,
5089
+ offset: wordsStart.offset + spanEnd
5090
+ },
5091
+ patch
5092
+ });
5093
+ }
5094
+ if (rebuilds) {
5095
+ const patch = droppedParagraphFormatting(paragraph.source.formatting);
5096
+ if (Object.keys(patch).length > 0) intents.push({
5097
+ type: "formatParagraph",
5098
+ at: {
5099
+ story,
5100
+ blockId: paragraph.blockId,
5101
+ offset: 0
5102
+ },
5103
+ patch
5104
+ });
5105
+ }
4954
5106
  intents.push(...restyle);
4955
5107
  } else if (operation.type === "mergeBlockWithNext" && intent.type === "joinParagraphs") {
4956
5108
  const separator = operation.separator ?? "";
4957
5109
  if (separator !== "") {
4958
5110
  const at = projection.value.addressAt(paragraph.start + paragraph.node.content.size);
4959
- if (at.isErr()) return refusal("unsupportedBlock");
5111
+ if (at.isErr()) return refusal("unsupportedBlock", void 0, at.error.ground);
4960
5112
  intents.push({
4961
5113
  type: "replaceText",
4962
5114
  from: at.value,