@stll/folio-core 0.73.0 → 0.75.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 (221) 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 +5 -2
  4. package/dist/ai-edits/headless.js +20 -14
  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 +134 -88
  9. package/dist/ai-edits/pendingJoin.d.ts +5 -1
  10. package/dist/ai-edits/pendingJoin.js +12 -3
  11. package/dist/ai-edits/result-validation.js +1 -1
  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/snapshot.js +1 -1
  15. package/dist/ai-edits/table-cell-mutations.js +1 -1
  16. package/dist/ai-edits/tracked-batch-fidelity.d.ts +6 -10
  17. package/dist/ai-edits/tracked-batch-fidelity.js +3 -182
  18. package/dist/canonical/canonicalBatchReview.d.ts +4 -1
  19. package/dist/canonical/canonicalBatchReview.js +32 -14
  20. package/dist/canonical/canonicalComments.d.ts +6 -2
  21. package/dist/canonical/canonicalComments.js +8 -4
  22. package/dist/canonical/canonicalInlineGaps.d.ts +56 -0
  23. package/dist/canonical/canonicalInlineGaps.js +118 -0
  24. package/dist/canonical/canonicalInlineProjection.d.ts +4 -13
  25. package/dist/canonical/canonicalInlineProjection.js +6 -28
  26. package/dist/canonical/canonicalProjectionBlocks.d.ts +4 -4
  27. package/dist/canonical/canonicalPublicOperations.js +99 -36
  28. package/dist/canonical/canonicalRefusalGrounds.d.ts +4 -0
  29. package/dist/canonical/canonicalRefusalGrounds.js +56 -0
  30. package/dist/canonical/canonicalSelection.js +1 -1
  31. package/dist/canonical/canonicalSession.d.ts +12 -6
  32. package/dist/canonical/canonicalSession.js +129 -141
  33. package/dist/canonical/canonicalTrackedBatchFidelity.js +3 -3
  34. package/dist/compare/inline-atoms.d.ts +35 -41
  35. package/dist/compare/inline-atoms.js +2 -465
  36. package/dist/compare/section-boundary-properties.d.ts +3 -30
  37. package/dist/compare/section-boundary-properties.js +4 -72
  38. package/dist/controller/autocompleteSuggestion.js +1 -1
  39. package/dist/controller/canonicalClipboard.js +45 -44
  40. package/dist/controller/canonicalComposition.d.ts +1 -1
  41. package/dist/controller/canonicalComposition.js +6 -6
  42. package/dist/controller/canonicalInput.d.ts +4 -2
  43. package/dist/controller/canonicalInput.js +34 -17
  44. package/dist/controller/canonicalPresence.js +1 -1
  45. package/dist/controller/canonicalRoomAuthority.js +1 -1
  46. package/dist/controller/canonicalRoomWire.js +1 -1
  47. package/dist/controller/canonicalStoryEditor.d.ts +2 -3
  48. package/dist/controller/canonicalStoryEditor.js +43 -25
  49. package/dist/controller/canonicalStructure.d.ts +19 -2
  50. package/dist/controller/canonicalStructure.js +140 -43
  51. package/dist/controller/canonicalTabRoom.js +1 -1
  52. package/dist/controller/canonicalYjsRoom.js +1 -1
  53. package/dist/controller/deferredDisplayListPainter.d.ts +8 -0
  54. package/dist/controller/deferredDisplayListPainter.js +34 -0
  55. package/dist/controller/folioEditor.js +4 -2
  56. package/dist/controller/headerFooterEditorManager.js +3 -17
  57. package/dist/controller/hiddenEditorApi.d.ts +24 -3
  58. package/dist/controller/hiddenEditorApi.js +4 -17
  59. package/dist/controller/hiddenEditorManager.js +136 -197
  60. package/dist/controller/layoutPipeline.d.ts +4 -86
  61. package/dist/controller/layoutPipeline.js +8 -727
  62. package/dist/controller/layoutPipelineExecution.d.ts +94 -0
  63. package/dist/controller/layoutPipelineExecution.js +730 -0
  64. package/dist/controller/noteEditorManager.js +3 -16
  65. package/dist/document-operations.js +1 -1
  66. package/dist/docx/blockContentParser.d.ts +1 -3
  67. package/dist/docx/blockContentParser.js +3 -10
  68. package/dist/docx/canonicalSave.d.ts +4 -3
  69. package/dist/docx/canonicalSave.js +4 -3
  70. package/dist/docx/canonicalSessionInput.js +1 -1
  71. package/dist/docx/containerChildren.js +1 -1
  72. package/dist/docx/createDocx.d.ts +4 -0
  73. package/dist/docx/createDocx.js +6 -0
  74. package/dist/docx/listMarkerComputation.d.ts +24 -17
  75. package/dist/docx/listMarkerComputation.js +31 -60
  76. package/dist/docx/listModelNormalization.js +8 -15
  77. package/dist/docx/modelValidation.js +1 -1
  78. package/dist/docx/parser.js +1 -1
  79. package/dist/docx/reviewResolutionProvenance.js +1 -1
  80. package/dist/docx/rezip.d.ts +16 -3
  81. package/dist/docx/rezip.js +36 -10
  82. package/dist/docx/selectiveSave.js +13 -5
  83. package/dist/docx/serializer/borderSerializer.js +1 -1
  84. package/dist/docx/serializer/commentSerializer.js +1 -1
  85. package/dist/docx/serializer/documentSerializer.js +1 -1
  86. package/dist/docx/serializer/paragraphSerializer.js +3 -3
  87. package/dist/docx/serializer/runSerializer.js +1 -1
  88. package/dist/docx/serializer/sectionPropertiesSerializer.js +1 -1
  89. package/dist/docx/serializer/tableSerializer.js +1 -1
  90. package/dist/docx/serializer/textFormattingSerializer.js +1 -1
  91. package/dist/docx/serializer/trackedChangeAttributes.js +1 -1
  92. package/dist/docx/server/templatePlan/apply.js +107 -14
  93. package/dist/docx/server/templatePlan/blocks.d.ts +16 -1
  94. package/dist/docx/server/templatePlan/blocks.js +93 -7
  95. package/dist/docx/server/templatePlan/builders.d.ts +37 -2
  96. package/dist/docx/server/templatePlan/builders.js +196 -5
  97. package/dist/docx/server/templatePlan/emit.d.ts +2 -0
  98. package/dist/docx/server/templatePlan/emit.js +2 -0
  99. package/dist/docx/server/templatePlan/inspect.js +81 -61
  100. package/dist/docx/server/templatePlan/labels.d.ts +16 -2
  101. package/dist/docx/server/templatePlan/labels.js +131 -20
  102. package/dist/docx/server/templatePlan/plan.d.ts +15 -1
  103. package/dist/docx/server/templatePlan/plan.js +62 -13
  104. package/dist/docx/server/templatePlan/planShape.js +52 -4
  105. package/dist/docx/server/templatePlan/story.d.ts +8 -0
  106. package/dist/docx/server/templatePlan/story.js +11 -1
  107. package/dist/docx/server/templatePlan/types.d.ts +176 -18
  108. package/dist/docx/server/templatePlan/types.js +1 -0
  109. package/dist/docx/server/templatePlan/verify.js +60 -11
  110. package/dist/docx/server/templatePlan/xml.d.ts +5 -0
  111. package/dist/docx/server/templatePlan/xml.js +7 -1
  112. package/dist/docx/storyBlockReplay.js +1 -1
  113. package/dist/docx/xmlParser.js +1 -1
  114. package/dist/i18n/loadMessages.d.ts +5 -0
  115. package/dist/i18n/loadMessages.js +46 -0
  116. package/dist/i18n/locales.d.ts +3 -0
  117. package/dist/i18n/locales.js +17 -0
  118. package/dist/i18n/messages/ar.gen.js +1 -0
  119. package/dist/i18n/messages/catalogs.gen.d.ts +17 -0
  120. package/dist/i18n/messages/catalogs.gen.js +17 -0
  121. package/dist/i18n/messages/cs.gen.js +1 -0
  122. package/dist/i18n/messages/de.gen.js +1 -0
  123. package/dist/i18n/messages/en.gen.js +1 -0
  124. package/dist/i18n/messages/es.gen.js +1 -0
  125. package/dist/i18n/messages/et.gen.js +1 -0
  126. package/dist/i18n/messages/fr.gen.js +1 -0
  127. package/dist/i18n/messages/he.gen.js +1 -0
  128. package/dist/i18n/messages/hi.gen.js +1 -0
  129. package/dist/i18n/messages/hu.gen.js +1 -0
  130. package/dist/i18n/messages/lt.gen.js +1 -0
  131. package/dist/i18n/messages/lv.gen.js +1 -0
  132. package/dist/i18n/messages/messages.gen.d.ts +1 -0
  133. package/dist/i18n/messages/pl.gen.js +1 -0
  134. package/dist/i18n/messages/pt-BR.gen.js +1 -0
  135. package/dist/i18n/messages/sk.gen.js +1 -0
  136. package/dist/i18n/messages/tr.gen.js +1 -0
  137. package/dist/i18n/messages/zh-CN.gen.js +1 -0
  138. package/dist/i18n/messages.d.ts +3 -2
  139. package/dist/i18n/messages.js +4 -16
  140. package/dist/internal/clipboardTransformPlugin.d.ts +3 -0
  141. package/dist/internal/clipboardTransformPlugin.js +13 -0
  142. package/dist/internal/extensionRuntime.d.ts +7 -0
  143. package/dist/internal/extensionRuntime.js +28 -0
  144. package/dist/internal/paragraphFormattingSerialization.js +1 -1
  145. package/dist/internal/starterKitExtensions.d.ts +20 -0
  146. package/dist/internal/starterKitExtensions.js +123 -0
  147. package/dist/internal/wholeStoryRevisionResolution.js +2 -2
  148. package/dist/layout-bridge/convert/toFlowBlocks.js +0 -12
  149. package/dist/layout-bridge/convert/topLevelConversion.js +1 -10
  150. package/dist/prosemirror/attrs/index.js +1 -1
  151. package/dist/prosemirror/canonicalSelectionRange.js +1 -1
  152. package/dist/prosemirror/canonicalTableCommands.js +1 -1
  153. package/dist/prosemirror/commands/comments.js +3 -3
  154. package/dist/prosemirror/commands/contentControls.js +1 -1
  155. package/dist/prosemirror/commands/pastePlainText.js +2 -3
  156. package/dist/prosemirror/commands/replaceRangeText.js +1 -1
  157. package/dist/prosemirror/commentRecords.js +2 -2
  158. package/dist/prosemirror/conversion/fromProseDoc.d.ts +0 -5
  159. package/dist/prosemirror/conversion/fromProseDoc.js +2 -9
  160. package/dist/prosemirror/conversion/index.d.ts +2 -2
  161. package/dist/prosemirror/conversion/index.js +2 -2
  162. package/dist/prosemirror/extensions/ExtensionManager.js +4 -22
  163. package/dist/prosemirror/extensions/StarterKit.d.ts +4 -27
  164. package/dist/prosemirror/extensions/StarterKit.js +29 -115
  165. package/dist/prosemirror/extensions/core/ParagraphExtension.js +2 -2
  166. package/dist/prosemirror/extensions/features/BaseKeymapExtension.js +1 -1
  167. package/dist/prosemirror/extensions/features/ImagePasteExtension.js +1 -1
  168. package/dist/prosemirror/extensions/features/ListExtension.js +7 -2
  169. package/dist/prosemirror/extensions/features/pastedHeadingStyles.js +1 -1
  170. package/dist/prosemirror/extensions/index.d.ts +2 -1
  171. package/dist/prosemirror/extensions/marks/FootnoteRefExtension.js +8 -3
  172. package/dist/prosemirror/extensions/nodes/TableExtension.js +7 -40
  173. package/dist/prosemirror/hyperlinkRemoval.js +7 -2
  174. package/dist/prosemirror/index.d.ts +2 -2
  175. package/dist/prosemirror/index.js +2 -2
  176. package/dist/prosemirror/keptRangeBoundaries.js +1 -1
  177. package/dist/prosemirror/listMarker.d.ts +1 -6
  178. package/dist/prosemirror/listMarker.js +4 -56
  179. package/dist/prosemirror/listNumbering.js +1 -1
  180. package/dist/prosemirror/noteReferenceOccurrences.js +1 -1
  181. package/dist/prosemirror/noteReferenceReview.d.ts +2 -56
  182. package/dist/prosemirror/noteReferenceReview.js +2 -243
  183. package/dist/prosemirror/pastedCommentCopies.js +1 -1
  184. package/dist/prosemirror/plugins/documentNumbering.js +1 -1
  185. package/dist/prosemirror/plugins/documentStyles.js +1 -1
  186. package/dist/prosemirror/replacedAnnotations.js +1 -1
  187. package/dist/prosemirror/suggestionCommands.d.ts +47 -0
  188. package/dist/prosemirror/suggestionCommands.js +31 -0
  189. package/dist/prosemirror/tableCellPaste.js +1 -1
  190. package/dist/prosemirror/tableRunIn.js +1 -1
  191. package/dist/prosemirror/textInput.js +1 -1
  192. package/dist/server.d.ts +2 -2
  193. package/dist/types/canonicalCapabilities.d.ts +42 -93
  194. package/dist/types/canonicalCapabilities.js +53 -91
  195. package/dist/types/canonicalComments.d.ts +2 -2
  196. package/dist/types/canonicalSections.d.ts +2 -2
  197. package/dist/utils/clipboard.d.ts +2 -28
  198. package/dist/utils/clipboard.js +1 -96
  199. package/dist/utils/clipboardFiles.d.ts +27 -0
  200. package/dist/utils/clipboardFiles.js +98 -0
  201. package/dist/utils/rulerControl.d.ts +1 -0
  202. package/dist/utils/rulerControl.js +2 -1
  203. package/package.json +2 -2
  204. package/dist/ai-edits/apply.d.ts +0 -94
  205. package/dist/ai-edits/apply.js +0 -6637
  206. package/dist/ai-edits/note-story-inventory.d.ts +0 -5
  207. package/dist/ai-edits/note-story-inventory.js +0 -10
  208. package/dist/ai-edits/revisionStretches.d.ts +0 -32
  209. package/dist/ai-edits/revisionStretches.js +0 -147
  210. package/dist/document-operations-apply.d.ts +0 -15
  211. package/dist/document-operations-apply.js +0 -280
  212. package/dist/prosemirror/extensions/core/HistoryExtension.d.ts +0 -12
  213. package/dist/prosemirror/extensions/core/HistoryExtension.js +0 -114
  214. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.d.ts +0 -23
  215. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.js +0 -270
  216. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +0 -51
  217. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.js +0 -411
  218. package/dist/prosemirror/plugins/suggestionMode.d.ts +0 -92
  219. package/dist/prosemirror/plugins/suggestionMode.js +0 -1515
  220. package/dist/prosemirror/tablePositionedBookmarks.d.ts +0 -8
  221. package/dist/prosemirror/tablePositionedBookmarks.js +0 -80
@@ -17,7 +17,7 @@ import { ProjectionBlockCache, collectPairedBookmarkIds, footnoteToProseDoc, hea
17
17
  import { heldUnreferencedNotes } from "../prosemirror/noteReferenceReview.js";
18
18
  import { preservesReplacementCommentAlignment, splitAtKeptCommentBoundaries } from "../prosemirror/replacedAnnotations.js";
19
19
  import { runFormattingPatchFromMarks } from "../prosemirror/runFormattingFromMarks.js";
20
- import { CANONICAL_GAP, CANONICAL_RULE } from "../types/canonicalCapabilities.js";
20
+ import { CANONICAL_CONDITION, CANONICAL_GAP, CANONICAL_RULE } from "../types/canonicalCapabilities.js";
21
21
  import { canonicalJson } from "../utils/canonicalJson.js";
22
22
  import { itemBefore } from "../utils/listItems.js";
23
23
  import { CanonicalIdLease } from "./canonicalIdLease.js";
@@ -25,6 +25,7 @@ import { InlineProjectionCache, canonicalNativeCells, projectCanonicalInline } f
25
25
  import { normalizeCanonicalListRendering } from "./canonicalListRendering.js";
26
26
  import { lockViolationBetween } from "./canonicalLockGuard.js";
27
27
  import { ParagraphIdIndex, sameIdOrder, storyFactContributions } from "./canonicalProjectionBlocks.js";
28
+ import { groundForDocumentOpRefusal } from "./canonicalRefusalGrounds.js";
28
29
  import { rebaseHistorySteps, remoteSelection } from "./canonicalRemoteHistory.js";
29
30
  import { canonicalRevisionLocks } from "./canonicalRevisionLocks.js";
30
31
  import { changedWindow, unsupportedEditReason, unsupportedSeedReason } from "./canonicalSeedContent.js";
@@ -34,66 +35,53 @@ import { mapTocSelection } from "./canonicalTocSelection.js";
34
35
  import { controlEdgesAt } from "./controlEdges.js";
35
36
  import { ownedSourceCopies, preservePropertySources, preservePropertySourcesWholeStories } from "./propertySourcePreservation.js";
36
37
  import { Result, TaggedError, panic } from "better-result";
37
- import { Fragment } from "prosemirror-model";
38
- import { CellSelection } from "prosemirror-tables";
38
+ import { hasIllegalXmlCharacters } from "@stll/docx-core";
39
39
  import { lockedControlMessage } from "@stll/docx-core/model";
40
40
  import { DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_TYPES, ID_LEASE_KINDS, OP_STORIES, applyDocumentOp, applyDocumentOps, combineEdits, combineRecordedRevisions, compileEditorIntent, createEditorIntentIdAllocator, documentStories, editorParagraphGroups, findStoryBody, formatParaId, freshLeasedIds, inverseMeetingDocument, isBlockBoundary, normalizeForOps, packageParagraphIds, paragraphIdsIn, paragraphsThroughTextBoxes, planWholeParagraphReplacement, sameStory, suggestedCommentIds, suggestionRevisionInfos, survivingComments, validateOpsDocument, withParagraphCopies } from "@stll/docx-core/ops";
41
- import { hasIllegalXmlCharacters } from "@stll/docx-core";
42
41
  import { AllSelection, NodeSelection, Selection, TextSelection } from "prosemirror-state";
42
+ import { CellSelection } from "prosemirror-tables";
43
+ import { Fragment } from "prosemirror-model";
43
44
  // src/canonical/canonicalSession.ts
44
45
  const CanonicalSessionErrorBase = TaggedError("CanonicalSessionError");
45
46
  var CanonicalSessionError = class extends CanonicalSessionErrorBase {};
46
- const refuse = (message) => Result.err(new CanonicalSessionError({
47
- ground: { gap: CANONICAL_GAP.dispatch },
48
- message,
49
- reason: "refused"
50
- }));
51
- /** A refusal under the gap or rule it belongs to. */
52
- const refuseUnder = (ground, message) => Result.err(new CanonicalSessionError({
47
+ const INVALID_REQUEST = { condition: CANONICAL_CONDITION.invalidRequest };
48
+ const STALE = { condition: CANONICAL_CONDITION.stale };
49
+ const INTERNAL = { condition: CANONICAL_CONDITION.internal };
50
+ const COMPOSING = { condition: CANONICAL_CONDITION.composing };
51
+ const ID_SPACE = { condition: CANONICAL_CONDITION.idSpace };
52
+ const HOST_TRANSACTION = { condition: CANONICAL_CONDITION.hostTransaction };
53
+ /** A refusal under the gap, rule or condition it belongs to. */
54
+ const refuse = (message, ground) => Result.err(new CanonicalSessionError({
53
55
  ground,
54
56
  message,
55
57
  reason: "refused"
56
58
  }));
59
+ /** A refusal the document operations stated, under its reason's ground. */
60
+ const refuseOp = ({ reason, message }) => refuse(message, groundForDocumentOpRefusal(reason));
57
61
  /** A change a content control's lock forbids: the document's rule, not a gap. */
58
62
  const lockRefusal = (violation) => Result.err(new CanonicalSessionError({
59
63
  ground: { rule: CANONICAL_RULE.contentControlLock },
60
64
  message: `Refused: ${lockedControlMessage(violation)}`,
61
65
  reason: "refused"
62
66
  }));
67
+ /** A request that changes nothing: not a refusal, and never shown. */
63
68
  const noChange = (message) => Result.err(new CanonicalSessionError({
64
- ground: { gap: CANONICAL_GAP.dispatch },
69
+ ground: INVALID_REQUEST,
65
70
  message,
66
71
  reason: "noChange"
67
72
  }));
68
73
  /**
69
74
  * What the session says for an intent the compiler or the engine refused. A
70
- * change the engine cannot record belongs to the capability that would record
71
- * it: the tracked table records for a
72
- * suggested row, column or table change. Every other refusal is unclassified.
75
+ * suggested row, column or table change the engine cannot record belongs to
76
+ * the tracked table records; every other refusal reports its reason's ground.
73
77
  */
74
78
  const intentRefusal = (intent, mode, { reason, message }) => {
75
79
  if (reason === DOCUMENT_OP_REFUSAL_REASONS.NO_CHANGE) return noChange(message);
76
- if (reason === DOCUMENT_OP_REFUSAL_REASONS.UNRECORDABLE_LINK_SUGGESTION) return Result.err(new CanonicalSessionError({
77
- ground: { rule: CANONICAL_RULE.linkSuggestionShape },
78
- message,
79
- reason: "refused"
80
- }));
81
- if (reason !== DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE) return refuse(message);
82
- let gap;
83
- switch (intent.type) {
84
- case "table":
85
- case "tableRow":
86
- case "tableBlock":
87
- if (mode.type !== "suggesting") return refuse(message);
88
- gap = CANONICAL_GAP.trackedTableStructure;
89
- break;
90
- default: return refuse(message);
91
- }
92
- return Result.err(new CanonicalSessionError({
93
- ground: { gap },
94
- message,
95
- reason: "refused"
96
- }));
80
+ if (reason === DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE && mode.type === "suggesting" && (intent.type === "table" || intent.type === "tableRow" || intent.type === "tableBlock")) return refuse(message, { gap: CANONICAL_GAP.trackedTableStructure });
81
+ return refuseOp({
82
+ reason,
83
+ message
84
+ });
97
85
  };
98
86
  const COMMENT_OPERATION_TYPES = /* @__PURE__ */ new Set([
99
87
  DOCUMENT_OP_TYPES.CREATE_COMMENT,
@@ -279,21 +267,18 @@ var CanonicalProjection = class CanonicalProjection {
279
267
  container: entry.container ?? this.content,
280
268
  start: (this.starts[block] ?? panic("Missing block start")) + entry.offset,
281
269
  text: entry.inline.text,
282
- boundaries: entry.inline.boundaries,
283
- seams: entry.inline.seams,
270
+ gaps: entry.inline.gaps,
284
271
  node: entry.node,
285
272
  source: entry.source
286
273
  };
287
274
  this.addresses.set(entry.blockId, address);
288
275
  return address;
289
276
  }
290
- /** The paragraph whose content holds `position`, its ends included. */
291
- /** Whether `position` lies in a text box's content. */
292
- insideTextBox(position) {
293
- const resolved = this.doc.resolve(Math.max(0, Math.min(position, this.doc.content.size)));
294
- for (let depth = resolved.depth; depth > 0; depth -= 1) if (resolved.node(depth).type.name === "textBox") return true;
295
- return false;
296
- }
277
+ /**
278
+ * The paragraph whose content holds `position`, its ends included: a
279
+ * story paragraph, or one in a text box the story draws, which the
280
+ * projection lists after its host as the story's own.
281
+ */
297
282
  paragraphAround(position) {
298
283
  let low = 0;
299
284
  let high = this.starts.length - 1;
@@ -323,26 +308,25 @@ var CanonicalProjection = class CanonicalProjection {
323
308
  return this.addressOf(block, found);
324
309
  }
325
310
  addressAt(position, edge = "caret") {
326
- if (!Number.isInteger(position)) return refuse("The input position is not an integer.");
311
+ const unaddressed = (message) => refuse(message, { condition: CANONICAL_CONDITION.invalidRequest });
312
+ if (!Number.isInteger(position)) return unaddressed("The input position is not an integer.");
327
313
  position = canonicalContentPosition(this.doc, position);
328
314
  const paragraph = this.paragraphAround(position);
329
- if (paragraph === void 0) return this.insideTextBox(position) ? refuseUnder({ gap: CANONICAL_GAP.publicUnsupportedInline }, "The canonical session holds no address in this paragraph, such as one in a text box.") : refuse("The input is outside a plain paragraph.");
315
+ if (paragraph === void 0) return unaddressed("The input is outside a plain paragraph.");
330
316
  const relative = position - paragraph.start;
331
- const offset = paragraph.boundaries.findIndex((gaps) => gaps.some((gap) => gap.position === relative));
332
- if (offset < 0) return refuse("The input splits an indivisible inline element.");
333
- if (splitsSurrogatePair(paragraph.text, offset)) return refuse("The input would split a surrogate pair.");
334
- const gaps = paragraph.boundaries.at(offset) ?? panic("Missing canonical boundary");
335
- const index = gaps.findIndex((entry) => entry.position === relative);
336
- const gap = gaps[index] ?? panic("Missing canonical native gap");
337
- const seam = paragraph.seams.at(offset)?.[index] ?? panic("Missing canonical seam");
317
+ const offset = paragraph.gaps.offsetOf(relative);
318
+ if (offset < 0) return unaddressed("The input splits an indivisible inline element.");
319
+ if (splitsSurrogatePair(paragraph.text, offset)) return unaddressed("The input would split a surrogate pair.");
320
+ const gaps = paragraph.gaps.at(offset) ?? panic("Missing canonical boundary");
321
+ const gap = gaps.find((entry) => entry.position === relative) ?? panic("Missing canonical native gap");
338
322
  let ordinal = gap.zeroWidthBefore;
339
- if (edge === "afterMarkers") ordinal = seam.last;
340
- if (edge === "beforeMarkers") ordinal = seam.first;
323
+ if (edge === "afterMarkers") ordinal = gap.last;
324
+ if (edge === "beforeMarkers") ordinal = gap.first;
341
325
  return Result.ok({
342
326
  story: this.story,
343
327
  blockId: paragraph.blockId,
344
328
  offset,
345
- ...gaps.length > 1 || ordinal > 0 || seam.first !== seam.last ? { zeroWidthBefore: ordinal } : {}
329
+ ...gaps.length > 1 || ordinal > 0 || gap.first !== gap.last ? { zeroWidthBefore: ordinal } : {}
346
330
  });
347
331
  }
348
332
  /**
@@ -380,17 +364,13 @@ var CanonicalProjection = class CanonicalProjection {
380
364
  }
381
365
  positionAt(address) {
382
366
  const paragraph = this.paragraph(address.blockId);
383
- if (!sameStory(address.story, this.story) || paragraph === void 0 || !Number.isInteger(address.offset) || address.offset < 0 || address.offset > paragraph.text.length || splitsSurrogatePair(paragraph.text, address.offset)) return refuse("The canonical selection is outside a plain paragraph.");
384
- const gaps = paragraph.boundaries.at(address.offset) ?? panic("Missing canonical boundary");
385
- const seams = paragraph.seams.at(address.offset) ?? panic("Missing canonical seams");
386
- const lastOrdinal = (seams.at(-1) ?? panic("Missing canonical seam")).last;
367
+ if (!sameStory(address.story, this.story) || paragraph === void 0 || !Number.isInteger(address.offset) || address.offset < 0 || address.offset > paragraph.text.length || splitsSurrogatePair(paragraph.text, address.offset)) return refuse("The canonical selection is outside a plain paragraph.", INVALID_REQUEST);
368
+ const gaps = paragraph.gaps.at(address.offset) ?? panic("Missing canonical boundary");
369
+ const lastOrdinal = (gaps.at(-1) ?? panic("Missing canonical seam")).last;
387
370
  const ordinal = address.zeroWidthBefore ?? lastOrdinal;
388
- const gap = gaps.find(({ zeroWidthBefore }) => zeroWidthBefore === ordinal) ?? gaps.find((_, index) => {
389
- const seam = seams[index];
390
- return seam !== void 0 && seam.first <= ordinal && ordinal <= seam.last;
391
- });
392
- if (!Number.isInteger(ordinal) || ordinal < 0 || ordinal > lastOrdinal) return refuse("The canonical selection is outside a paragraph gap.");
393
- if (gap === void 0) return refuse("This source gap is inside a collapsed or erased inline boundary and has no editor position.");
371
+ const gap = gaps.find(({ zeroWidthBefore }) => zeroWidthBefore === ordinal) ?? gaps.find(({ first, last }) => first <= ordinal && ordinal <= last);
372
+ if (!Number.isInteger(ordinal) || ordinal < 0 || ordinal > lastOrdinal) return refuse("The canonical selection is outside a paragraph gap.", INVALID_REQUEST);
373
+ if (gap === void 0) return refuse("This source gap is inside a collapsed or erased inline boundary and has no editor position.", INVALID_REQUEST);
394
374
  return Result.ok(paragraph.start + gap.position);
395
375
  }
396
376
  selectionAt(state) {
@@ -409,7 +389,7 @@ var CanonicalProjection = class CanonicalProjection {
409
389
  const range = canonicalSelectionRange(state);
410
390
  anchorPosition = range.from;
411
391
  headPosition = range.to;
412
- } else return refuse("Canonical input requires text, an inline atom, or the whole document selection.");
392
+ } else return refuse("Canonical input requires text, an inline atom, or the whole document selection.", INVALID_REQUEST);
413
393
  const anchor = this.addressAt(anchorPosition);
414
394
  if (anchor.isErr()) return anchor;
415
395
  const head = this.addressAt(headPosition);
@@ -734,7 +714,7 @@ const projectBlock = (top, index, walk) => {
734
714
  const inline = walk.inline === void 0 ? projectCanonicalInline(inlineArgs) : walk.inline.project(inlineArgs);
735
715
  if (inline.isErr()) {
736
716
  failure = new CanonicalSessionError({
737
- ground: { gap: CANONICAL_GAP.dispatch },
717
+ ground: { gap: CANONICAL_GAP.storyContentProjection },
738
718
  reason: "refused",
739
719
  message: inline.error.message
740
720
  });
@@ -853,7 +833,7 @@ const projectEveryBlock = ({ doc, content, story, markersOf, inline }) => {
853
833
  openAfter: open.current
854
834
  });
855
835
  }
856
- if (projectedSources.size + continuationSources.size + textBoxHosts.size !== allSources.size || [...projectedSources].some((source) => continuationSources.has(source) || textBoxHosts.has(source)) || [...textBoxHosts].some((source) => continuationSources.has(source))) return refuse("The projection changed paragraph structure.");
836
+ if (projectedSources.size + continuationSources.size + textBoxHosts.size !== allSources.size || [...projectedSources].some((source) => continuationSources.has(source) || textBoxHosts.has(source)) || [...textBoxHosts].some((source) => continuationSources.has(source))) return refuse("The projection changed paragraph structure.", INTERNAL);
857
837
  return Result.ok(new CanonicalProjection({
858
838
  doc,
859
839
  story,
@@ -957,7 +937,7 @@ const projectChangedBlocks = (previous, { doc, content, story, markersOf, inline
957
937
  };
958
938
  const project = ({ document, styles, story = OP_STORIES.MAIN, caches, previous }) => {
959
939
  const body = findStoryBody(document, story);
960
- if (!body) return refuse("The canonical story no longer exists.");
940
+ if (!body) return refuse("The canonical story no longer exists.", STALE);
961
941
  const currentStyles = Object.hasOwn(document.package, "styles") ? document.package.styles : styles;
962
942
  const options = storyConversionOptions({
963
943
  styles: currentStyles,
@@ -974,7 +954,7 @@ const project = ({ document, styles, story = OP_STORIES.MAIN, caches, previous }
974
954
  return footnoteToProseDoc(body.content, options);
975
955
  },
976
956
  catch: (cause) => new CanonicalSessionError({
977
- ground: { gap: CANONICAL_GAP.dispatch },
957
+ ground: INTERNAL,
978
958
  reason: "refused",
979
959
  message: `Canonical projection failed: ${cause instanceof Error ? cause.message : String(cause)}`
980
960
  })
@@ -1063,19 +1043,19 @@ const projectionChangeOf = (projected, published) => {
1063
1043
  };
1064
1044
  /** The model publishes only after PM and every plugin accept its exact projection. */
1065
1045
  const publishCanonicalProjection = ({ state, commit, session }) => {
1066
- if (!isCanonicalProjectionTransaction(commit.transaction, session)) return refuse("The staged canonical projection is unauthorized.");
1046
+ if (!isCanonicalProjectionTransaction(commit.transaction, session)) return refuse("The staged canonical projection is unauthorized.", INTERNAL);
1067
1047
  const applied = Result.try({
1068
1048
  try: () => state.applyTransaction(commit.transaction),
1069
1049
  catch: (cause) => new CanonicalSessionError({
1070
- ground: { gap: CANONICAL_GAP.dispatch },
1050
+ ground: INTERNAL,
1071
1051
  reason: "refused",
1072
1052
  message: `Canonical plugin staging failed: ${cause instanceof Error ? cause.message : String(cause)}`
1073
1053
  })
1074
1054
  });
1075
1055
  if (applied.isErr()) return applied;
1076
1056
  const staged = applied.value;
1077
- if (!staged.transactions.includes(commit.transaction)) return refuse("A plugin refused or changed the canonical projection: a plugin filtered the projection transaction.");
1078
- if (!staged.state.doc.eq(commit.projection.doc) || staged.transactions.some((transaction) => transaction.docChanged && !isCanonicalProjectionTransaction(transaction, session))) return refuse(`A plugin refused or changed the canonical projection: ${projectionChangeOf(commit.projection.doc, staged.state.doc)}.`);
1057
+ if (!staged.transactions.includes(commit.transaction)) return refuse("A plugin refused or changed the canonical projection: a plugin filtered the projection transaction.", HOST_TRANSACTION);
1058
+ if (!staged.state.doc.eq(commit.projection.doc) || staged.transactions.some((transaction) => transaction.docChanged && !isCanonicalProjectionTransaction(transaction, session))) return refuse(`A plugin refused or changed the canonical projection: ${projectionChangeOf(commit.projection.doc, staged.state.doc)}.`, HOST_TRANSACTION);
1079
1059
  const published = commit.publish();
1080
1060
  if (published.isErr()) return published;
1081
1061
  return Result.ok(staged);
@@ -1248,7 +1228,7 @@ var CanonicalSession = class {
1248
1228
  * cleared.
1249
1229
  */
1250
1230
  compileReplacementPieces({ projection, pieces, start, end, intent }) {
1251
- const refused = (message) => refuseUnder({ gap: CANONICAL_GAP.commentReplacementAlignment }, message);
1231
+ const refused = (message) => refuse(message, { gap: CANONICAL_GAP.commentReplacementAlignment });
1252
1232
  const addressed = [];
1253
1233
  for (const [index, piece] of pieces.entries()) {
1254
1234
  const from = index === 0 ? Result.ok(start) : projection.inputAddressAt(piece.from, "afterMarkers");
@@ -1317,9 +1297,9 @@ var CanonicalSession = class {
1317
1297
  const fresh = this.freshBlockIds([1]);
1318
1298
  if (fresh.isErr()) return fresh;
1319
1299
  const id = fresh.value[0]?.[0];
1320
- return id === void 0 ? refuse("The paragraph identity lease is exhausted.") : Result.ok(id);
1300
+ return id === void 0 ? refuse("The paragraph identity lease is exhausted.", ID_SPACE) : Result.ok(id);
1321
1301
  }
1322
- if (this.nextBlockId > 2147483647) return refuse("The paragraph identity space is exhausted.");
1302
+ if (this.nextBlockId > 2147483647) return refuse("The paragraph identity space is exhausted.", ID_SPACE);
1323
1303
  return Result.ok(this.nextBlockId.toString(16).padStart(8, "0").toUpperCase());
1324
1304
  }
1325
1305
  /**
@@ -1337,11 +1317,11 @@ var CanonicalSession = class {
1337
1317
  count: total,
1338
1318
  taken: (id) => this.allocatedBlockIds.has(formatParaId(id))
1339
1319
  });
1340
- if (leased.length < total) return refuse("The paragraph identity lease is exhausted.");
1320
+ if (leased.length < total) return refuse("The paragraph identity lease is exhausted.", ID_SPACE);
1341
1321
  ids.push(...leased.map(formatParaId));
1342
1322
  }
1343
1323
  for (let candidate = this.nextBlockId; ids.length < total; candidate += 1) {
1344
- if (candidate > 2147483647) return refuse("The paragraph identity space is exhausted.");
1324
+ if (candidate > 2147483647) return refuse("The paragraph identity space is exhausted.", ID_SPACE);
1345
1325
  const id = candidate.toString(16).padStart(8, "0").toUpperCase();
1346
1326
  if (!this.allocatedBlockIds.has(id)) ids.push(id);
1347
1327
  }
@@ -1428,7 +1408,7 @@ var CanonicalSession = class {
1428
1408
  }
1429
1409
  get document() {
1430
1410
  if (this.isComposing) throw new CanonicalSessionError({
1431
- ground: { gap: CANONICAL_GAP.dispatch },
1411
+ ground: COMPOSING,
1432
1412
  reason: "refused",
1433
1413
  message: "Composition must finish before taking a snapshot."
1434
1414
  });
@@ -1449,7 +1429,7 @@ var CanonicalSession = class {
1449
1429
  }
1450
1430
  captureSaveSnapshot() {
1451
1431
  if (this.isComposing) throw new CanonicalSessionError({
1452
- ground: { gap: CANONICAL_GAP.save },
1432
+ ground: { condition: CANONICAL_CONDITION.composing },
1453
1433
  reason: "refused",
1454
1434
  message: "Composition must finish before saving the canonical document."
1455
1435
  });
@@ -1597,7 +1577,7 @@ var CanonicalSession = class {
1597
1577
  const projected = this.projectStory(story);
1598
1578
  if (projected.isErr()) return projected;
1599
1579
  const projection = projected.value;
1600
- if (state.doc !== projection.doc && !state.doc.eq(projection.doc)) return refuse("The story editor shows a stale canonical projection.");
1580
+ if (state.doc !== projection.doc && !state.doc.eq(projection.doc)) return refuse("The story editor shows a stale canonical projection.", STALE);
1601
1581
  const selection = projection.selectionAt(state);
1602
1582
  if (selection.isErr()) {
1603
1583
  this.storySelections.delete(storyProjectionKey(story));
@@ -1627,14 +1607,14 @@ var CanonicalSession = class {
1627
1607
  * without a lease takes one.
1628
1608
  */
1629
1609
  adoptIdLease(lease) {
1630
- if (this.leased !== void 0) return refuse("The session already holds an id lease.");
1631
- if (this.currentVersion !== 0) return refuse("The session was edited before it took an id lease.");
1610
+ if (this.leased !== void 0) return refuse("The session already holds an id lease.", INVALID_REQUEST);
1611
+ if (this.currentVersion !== 0) return refuse("The session was edited before it took an id lease.", INVALID_REQUEST);
1632
1612
  this.leased = new CanonicalIdLease(lease, this.currentDocument);
1633
1613
  return Result.ok(void 0);
1634
1614
  }
1635
1615
  /** Add blocks the authority granted; ids this session already minted stay spent. */
1636
1616
  extendIdLease(lease) {
1637
- if (this.leased === void 0) return refuse("The session was created without an id lease.");
1617
+ if (this.leased === void 0) return refuse("The session was created without an id lease.", INVALID_REQUEST);
1638
1618
  this.leased.extend(lease);
1639
1619
  return Result.ok(void 0);
1640
1620
  }
@@ -1654,7 +1634,7 @@ var CanonicalSession = class {
1654
1634
  this.groupingBoundary += 1;
1655
1635
  }
1656
1636
  beginComposition() {
1657
- if (this.isComposing) return refuse("A canonical composition is already pending.");
1637
+ if (this.isComposing) return refuse("A canonical composition is already pending.", COMPOSING);
1658
1638
  this.lifecycle = { type: "composing" };
1659
1639
  this.breakUndoGroup();
1660
1640
  return Result.ok(void 0);
@@ -1664,8 +1644,8 @@ var CanonicalSession = class {
1664
1644
  this.breakUndoGroup();
1665
1645
  }
1666
1646
  checkState(state, projection = this.projection) {
1667
- if (this.isComposing) return refuse("Composition must finish before committing another edit.");
1668
- if (state.doc !== projection.doc && !state.doc.eq(projection.doc)) return refuse("The input uses a stale canonical projection.");
1647
+ if (this.isComposing) return refuse("Composition must finish before committing another edit.", COMPOSING);
1648
+ if (state.doc !== projection.doc && !state.doc.eq(projection.doc)) return refuse("The input uses a stale canonical projection.", STALE);
1669
1649
  return Result.ok(void 0);
1670
1650
  }
1671
1651
  prepareReplace(state, { from, to, text, story = OP_STORIES.MAIN, semantic = "replacement", compositionPhase, time = Date.now() }) {
@@ -1674,16 +1654,16 @@ var CanonicalSession = class {
1674
1654
  const projection = projected.value;
1675
1655
  const checked = this.checkState(state, projection);
1676
1656
  if (checked.isErr()) return checked;
1677
- if (!Number.isFinite(time)) return refuse("The input time is invalid.");
1678
- if (!Number.isSafeInteger(from) || !Number.isSafeInteger(to) || from < 0 || to > projection.doc.content.size || from > to || hasIllegalXmlCharacters(text) || /[\t\r\n]/u.test(text)) return refuse("Canonical input accepts a well-formed text replacement.");
1657
+ if (!Number.isFinite(time)) return refuse("The input time is invalid.", INVALID_REQUEST);
1658
+ if (!Number.isSafeInteger(from) || !Number.isSafeInteger(to) || from < 0 || to > projection.doc.content.size || from > to || hasIllegalXmlCharacters(text) || /[\t\r\n]/u.test(text)) return refuse("Canonical input accepts a well-formed text replacement.", INVALID_REQUEST);
1679
1659
  if (from === to && text.length === 0) return noChange("The input makes no text change.");
1680
1660
  const replacesStructuralSelection = state.selection instanceof AllSelection && from === state.selection.from && to === state.selection.to;
1681
1661
  if (state.selection instanceof CellSelection) {
1682
- if (from !== state.selection.from || to !== state.selection.to) return refuse("A replacement range cannot partially address a cell selection.");
1662
+ if (from !== state.selection.from || to !== state.selection.to) return refuse("A replacement range cannot partially address a cell selection.", INVALID_REQUEST);
1683
1663
  const ranges = canonicalCellSelectionRanges(state.selection);
1684
1664
  const firstRange = ranges.at(0);
1685
1665
  const lastRange = ranges.at(-1);
1686
- if (firstRange === void 0 || lastRange === void 0) return refuse("The selected cells contain no editable text.");
1666
+ if (firstRange === void 0 || lastRange === void 0) return refuse("The selected cells contain no editable text.", INVALID_REQUEST);
1687
1667
  const intents = [];
1688
1668
  const commentChanges = [];
1689
1669
  let first = true;
@@ -1715,7 +1695,7 @@ var CanonicalSession = class {
1715
1695
  },
1716
1696
  changes: commentChanges,
1717
1697
  removal: this.replacementRemoval()
1718
- })) return refuseUnder({ gap: CANONICAL_GAP.commentReplacementAlignment }, "Canonical replacement cannot preserve the aligned comment ranges.");
1698
+ })) return refuse("Canonical replacement cannot preserve the aligned comment ranges.", { gap: CANONICAL_GAP.commentReplacementAlignment });
1719
1699
  return this.prepareIntents(state, {
1720
1700
  intents,
1721
1701
  semantic
@@ -1741,7 +1721,7 @@ var CanonicalSession = class {
1741
1721
  to: end.value,
1742
1722
  suggesting: this.mode.type === "suggesting" ? { author: this.mode.author } : void 0
1743
1723
  });
1744
- if (retirement.isErr()) return refuse(retirement.error.message);
1724
+ if (retirement.isErr()) return refuseOp(retirement.error);
1745
1725
  const removal = this.replacementRemoval();
1746
1726
  const whole = [{
1747
1727
  from: inputFrom,
@@ -1766,7 +1746,7 @@ var CanonicalSession = class {
1766
1746
  comments: removal.comments
1767
1747
  }) : void 0;
1768
1748
  const retired = /* @__PURE__ */ new Set([...retirement.value?.commentIds ?? [], ...split?.retiredCommentIds ?? []]);
1769
- if (split === void 0 || split.changes.length < 2 || !aligned(split.changes, retired)) return refuseUnder({ gap: CANONICAL_GAP.commentReplacementAlignment }, "Canonical replacement cannot preserve the aligned comment ranges.");
1749
+ if (split === void 0 || split.changes.length < 2 || !aligned(split.changes, retired)) return refuse("Canonical replacement cannot preserve the aligned comment ranges.", { gap: CANONICAL_GAP.commentReplacementAlignment });
1770
1750
  pieces = split.changes;
1771
1751
  }
1772
1752
  }
@@ -1793,7 +1773,7 @@ var CanonicalSession = class {
1793
1773
  });
1794
1774
  if (compiled.isErr()) {
1795
1775
  if (compiled.error instanceof CanonicalSessionError) return Result.err(compiled.error);
1796
- return compiled.error.reason === DOCUMENT_OP_REFUSAL_REASONS.NO_CHANGE ? noChange(compiled.error.message) : refuse(compiled.error.message);
1776
+ return compiled.error.reason === DOCUMENT_OP_REFUSAL_REASONS.NO_CHANGE ? noChange(compiled.error.message) : refuseOp(compiled.error);
1797
1777
  }
1798
1778
  const { ops, selection: caret } = compiled.value;
1799
1779
  const postSelection = {
@@ -1858,9 +1838,9 @@ var CanonicalSession = class {
1858
1838
  * the edit happens at the start of the first, as the editor's own command
1859
1839
  * does over a cell selection. One commit, so one undo step.
1860
1840
  */
1861
- prepareCellSelectionStructure(state, structure, { resourceOps = [], semantic = "structure" } = {}) {
1862
- if (!(state.selection instanceof CellSelection)) return refuse("The structural edit needs a cell selection.");
1863
- const projected = this.projectStory(OP_STORIES.MAIN);
1841
+ prepareCellSelectionStructure(state, structure, { resourceOps = [], semantic = "structure", story = OP_STORIES.MAIN } = {}) {
1842
+ if (!(state.selection instanceof CellSelection)) return refuse("The structural edit needs a cell selection.", INVALID_REQUEST);
1843
+ const projected = this.projectStory(story);
1864
1844
  if (projected.isErr()) return projected;
1865
1845
  const projection = projected.value;
1866
1846
  const intents = [];
@@ -1879,7 +1859,7 @@ var CanonicalSession = class {
1879
1859
  text: ""
1880
1860
  });
1881
1861
  }
1882
- if (first === void 0) return refuse("The cell selection is empty.");
1862
+ if (first === void 0) return refuse("The cell selection is empty.", INVALID_REQUEST);
1883
1863
  intents.push(structure({
1884
1864
  ...first,
1885
1865
  offset: 0,
@@ -1898,7 +1878,7 @@ var CanonicalSession = class {
1898
1878
  const first = intents.at(0);
1899
1879
  if (first === void 0) return noChange("The intent batch is empty.");
1900
1880
  const story = intentStory(first);
1901
- if (intents.some((intent) => !sameStory(story, intentStory(intent)))) return refuse("A compound input must address one story.");
1881
+ if (intents.some((intent) => !sameStory(story, intentStory(intent)))) return refuse("A compound input must address one story.", INVALID_REQUEST);
1902
1882
  const projected = this.projectStory(story);
1903
1883
  if (projected.isErr()) return projected;
1904
1884
  const checked = this.checkState(state, projected.value);
@@ -1911,7 +1891,7 @@ var CanonicalSession = class {
1911
1891
  const edits = [];
1912
1892
  if (resourceOps.length > 0) {
1913
1893
  const imported = applyDocumentOps(document, resourceOps);
1914
- if (imported.isErr()) return refuse(imported.error.message);
1894
+ if (imported.isErr()) return refuseOp(imported.error);
1915
1895
  document = imported.value.document;
1916
1896
  edits.push(imported.value);
1917
1897
  }
@@ -2019,7 +1999,7 @@ var CanonicalSession = class {
2019
1999
  return true;
2020
2000
  },
2021
2001
  prepare: (state, postSelection) => {
2022
- if (version !== this.currentVersion || base !== this.currentDocument) return refuse("The compiled operations use a stale canonical document.");
2002
+ if (version !== this.currentVersion || base !== this.currentDocument) return refuse("The compiled operations use a stale canonical document.", STALE);
2023
2003
  const combined = combineEdits(document, effects.map(({ inverse, touched }) => ({
2024
2004
  document,
2025
2005
  inverse,
@@ -2130,12 +2110,16 @@ var CanonicalSession = class {
2130
2110
  }
2131
2111
  });
2132
2112
  }
2133
- prepareSplit(state) {
2134
- const from = this.projection.inputAddressAt(state.selection.from);
2113
+ /** Split the paragraph at the selection of the editor showing `story`. */
2114
+ prepareSplit(state, story = OP_STORIES.MAIN) {
2115
+ const projected = this.projectStory(story);
2116
+ if (projected.isErr()) return projected;
2117
+ const projection = projected.value;
2118
+ const from = projection.inputAddressAt(state.selection.from);
2135
2119
  if (from.isErr()) return from;
2136
- const to = this.projection.inputAddressAt(state.selection.to);
2120
+ const to = projection.inputAddressAt(state.selection.to);
2137
2121
  if (to.isErr()) return to;
2138
- const source = this.projection.paragraph(from.value.blockId);
2122
+ const source = projection.paragraph(from.value.blockId);
2139
2123
  const nextStyle = (Object.hasOwn(this.currentDocument.package, "styles") ? this.currentDocument.package.styles : this.styles)?.styles.find(({ styleId }) => styleId === source?.source.formatting?.styleId)?.next;
2140
2124
  const fresh = this.freshBlockId();
2141
2125
  if (fresh.isErr()) return fresh;
@@ -2155,11 +2139,15 @@ var CanonicalSession = class {
2155
2139
  });
2156
2140
  return this.prepareIntents(state, { intents });
2157
2141
  }
2158
- prepareJoin(state, direction) {
2159
- const checked = this.checkState(state);
2142
+ /** Join the paragraph at the caret of the editor showing `story` with its neighbour. */
2143
+ prepareJoin(state, direction, story = OP_STORIES.MAIN) {
2144
+ const projected = this.projectStory(story);
2145
+ if (projected.isErr()) return projected;
2146
+ const projection = projected.value;
2147
+ const checked = this.checkState(state, projection);
2160
2148
  if (checked.isErr()) return checked;
2161
- if (!state.selection.empty) return refuse("Join requires a collapsed text selection.");
2162
- const at = this.projection.inputAddressAt(state.selection.from);
2149
+ if (!state.selection.empty) return refuse("Join requires a collapsed text selection.", INVALID_REQUEST);
2150
+ const at = projection.inputAddressAt(state.selection.from);
2163
2151
  if (at.isErr()) return at;
2164
2152
  const groups = editorParagraphGroups(this.currentDocument, at.value.story);
2165
2153
  const index = groups.findIndex(({ paragraphs }) => paragraphs.some((paragraph) => paragraph.paraId === at.value.blockId));
@@ -2169,8 +2157,8 @@ var CanonicalSession = class {
2169
2157
  const first = firstGroup?.paragraphs.at(-1);
2170
2158
  const second = secondGroup?.paragraphs.at(0);
2171
2159
  if (!first?.paraId || !second?.paraId) return noChange("There is no adjacent paragraph to join.");
2172
- if (this.projection.paragraph(first.paraId)?.container !== this.projection.paragraph(second.paraId)?.container) return noChange("There is no adjacent paragraph to join.");
2173
- if (!isCanonicalJoinBoundary(state, direction)) return refuse("Join requires a caret at a paragraph boundary.");
2160
+ if (projection.paragraph(first.paraId)?.container !== projection.paragraph(second.paraId)?.container) return noChange("There is no adjacent paragraph to join.");
2161
+ if (!isCanonicalJoinBoundary(state, direction)) return refuse("Join requires a caret at a paragraph boundary.", INVALID_REQUEST);
2174
2162
  return this.prepareIntent(state, {
2175
2163
  type: "joinParagraphs",
2176
2164
  story: at.value.story,
@@ -2202,7 +2190,7 @@ var CanonicalSession = class {
2202
2190
  const resolved = locks.unlocked.flat();
2203
2191
  const ops = [...before, ...resolved.length === 0 ? [] : resolve(resolved)];
2204
2192
  const applied = applyDocumentOps(this.currentDocument, ops);
2205
- if (applied.isErr()) return refuse(applied.error.message);
2193
+ if (applied.isErr()) return refuseOp(applied.error);
2206
2194
  const projected = project({
2207
2195
  document: applied.value.document,
2208
2196
  styles: this.styles,
@@ -2212,7 +2200,7 @@ var CanonicalSession = class {
2212
2200
  if (projected.isErr()) return projected;
2213
2201
  const surviving = projected.value.paragraph(preSelection.value.head.blockId);
2214
2202
  const first = projected.value.firstParagraph;
2215
- if (first === void 0) return refuse("Resolution left no paragraph.");
2203
+ if (first === void 0) return refuse("Resolution left no paragraph.", INTERNAL);
2216
2204
  let offset = surviving ? Math.min(preSelection.value.head.offset, surviving.text.length) : 0;
2217
2205
  if (surviving && splitsSurrogatePair(surviving.text, offset)) offset -= 1;
2218
2206
  const caret = {
@@ -2296,7 +2284,7 @@ var CanonicalSession = class {
2296
2284
  const body = findStoryBody(this.currentDocument, story);
2297
2285
  if (body === void 0) {
2298
2286
  this.storyProjections.delete(key);
2299
- return refuse("The canonical story no longer exists.");
2287
+ return refuse("The canonical story no longer exists.", STALE);
2300
2288
  }
2301
2289
  const cached = this.storyProjections.get(key);
2302
2290
  const { styles, theme } = this.currentDocument.package;
@@ -2317,7 +2305,7 @@ var CanonicalSession = class {
2317
2305
  return projected;
2318
2306
  }
2319
2307
  prepareOperations(state, ops) {
2320
- if (ops.length === 0) return refuse("The operation batch is empty.");
2308
+ if (ops.length === 0) return refuse("The operation batch is empty.", INVALID_REQUEST);
2321
2309
  const selected = this.projection.selectionAt(state);
2322
2310
  if (selected.isErr()) return selected;
2323
2311
  let preparedOps = ops;
@@ -2360,7 +2348,7 @@ var CanonicalSession = class {
2360
2348
  };
2361
2349
  if (ops.length > 1) {
2362
2350
  const applied = applyDocumentOp(cloneDocumentWithParagraphPropertySources(document), structuredClone(next));
2363
- if (applied.isErr()) return refuse(applied.error.message);
2351
+ if (applied.isErr()) return refuseOp(applied.error);
2364
2352
  document = applied.value.document;
2365
2353
  }
2366
2354
  tracked.push(next);
@@ -2429,7 +2417,7 @@ var CanonicalSession = class {
2429
2417
  if (stack === "undo") this.applied.length = 0;
2430
2418
  else this.undone.length = 0;
2431
2419
  this.reportHistoryDrop(dropped);
2432
- return refuse(`The ${stack} step no longer applies after a remote edit: ${applied.error.message}`);
2420
+ return refuse(`The ${stack} step no longer applies after a remote edit: ${applied.error.message}`, STALE);
2433
2421
  }
2434
2422
  /** Called with every history drop a remote edit causes; returns the unsubscribe. */
2435
2423
  onHistoryDrop(listener) {
@@ -2470,7 +2458,7 @@ var CanonicalSession = class {
2470
2458
  const checked = this.checkState(state, projected.value);
2471
2459
  if (checked.isErr()) return checked;
2472
2460
  const applied = applyDocumentOps(this.currentDocument, change.batch.ops);
2473
- if (applied.isErr()) return refuse(applied.error.message);
2461
+ if (applied.isErr()) return refuseOp(applied.error);
2474
2462
  const shown = projected.value.selectionAt(state);
2475
2463
  const before = shown.isOk() ? shown.value : this.currentSelection;
2476
2464
  const selection = remoteSelection({
@@ -2577,7 +2565,7 @@ var CanonicalSession = class {
2577
2565
  }
2578
2566
  prepareUndo(state, story = OP_STORIES.MAIN) {
2579
2567
  const group = this.applied.at(-1);
2580
- if (group === void 0) return refuse("There is no canonical edit to undo.");
2568
+ if (group === void 0) return refuse("There is no canonical edit to undo.", INVALID_REQUEST);
2581
2569
  const ops = undoOpsOf(group);
2582
2570
  const rebased = this.rebasedStepApplies(group, ops, "undo");
2583
2571
  if (rebased.isErr()) return rebased;
@@ -2604,7 +2592,7 @@ var CanonicalSession = class {
2604
2592
  }
2605
2593
  prepareRedo(state, story = OP_STORIES.MAIN) {
2606
2594
  const undone = this.undone.at(-1);
2607
- if (undone === void 0) return refuse("There is no canonical edit to redo.");
2595
+ if (undone === void 0) return refuse("There is no canonical edit to redo.", INVALID_REQUEST);
2608
2596
  const rebased = this.rebasedStepApplies(undone.group, undone.redoOps, "redo");
2609
2597
  if (rebased.isErr()) return rebased;
2610
2598
  const propertySourceDocument = undone.group.rebased === true ? void 0 : undone.group.entries.at(-1)?.postDocument;
@@ -2639,7 +2627,7 @@ var CanonicalSession = class {
2639
2627
  const checked = this.checkState(state, previous.value);
2640
2628
  if (checked.isErr()) return checked;
2641
2629
  const applied = stagedApplied === void 0 ? applyDocumentOps(this.currentDocument, ops) : Result.ok(stagedApplied);
2642
- if (applied.isErr()) return refuse(applied.error.message);
2630
+ if (applied.isErr()) return refuseOp(applied.error);
2643
2631
  if (applied.value.inverse.length === 0) return noChange("The intent makes no document change.");
2644
2632
  const locked = admission === CANONICAL_ADMISSION.restage ? null : lockViolationBetween(this.currentDocument, applied.value.document);
2645
2633
  if (locked !== null) return lockRefusal(locked);
@@ -2652,7 +2640,7 @@ var CanonicalSession = class {
2652
2640
  applied.value.document = normalized.document;
2653
2641
  applied.value.inverse = inverseMeetingDocument(normalized.document, normalized.inverse.concat(applied.value.inverse));
2654
2642
  const leaseJudgement = origin === "remote" ? this.leased?.admit(applied.value.document) : this.leased?.judge(applied.value.document);
2655
- if (leaseJudgement?.type === "outside") return refuse(`The ${leaseJudgement.id.kind} id ${leaseJudgement.id.id} is outside this author's id lease.`);
2643
+ if (leaseJudgement?.type === "outside") return refuse(`The ${leaseJudgement.id.kind} id ${leaseJudgement.id.id} is outside this author's id lease.`, INVALID_REQUEST);
2656
2644
  const changed = changedStories({
2657
2645
  document: applied.value.document,
2658
2646
  previous: this.currentDocument
@@ -2754,7 +2742,7 @@ var CanonicalSession = class {
2754
2742
  type: "near",
2755
2743
  anchor: state.selection.anchor
2756
2744
  }
2757
- })) return refuse("Canonical history cannot restore the selected inline atom.");
2745
+ })) return refuse("Canonical history cannot restore the selected inline atom.", INTERNAL);
2758
2746
  }
2759
2747
  const shown = (sameStory(selection.anchor.story, projectedStory) && sameStory(selection.head.story, projectedStory) ? placeShownSelection(transaction, projected.value) : void 0) ?? selection;
2760
2748
  const held = projected.value.heldAs(transaction.doc);
@@ -2784,9 +2772,9 @@ var CanonicalSession = class {
2784
2772
  origin,
2785
2773
  history,
2786
2774
  publish: () => {
2787
- if (this.isComposing || this.groupingBoundary !== baseBoundary) return refuse("The staged canonical commit crossed a composition or selection boundary.");
2788
- if (this.version !== baseVersion) return refuse("The staged canonical commit is stale.");
2789
- if (!isCanonicalProjectionTransaction(transaction, this)) return refuse("The staged canonical projection was changed after preparation.");
2775
+ if (this.isComposing || this.groupingBoundary !== baseBoundary) return refuse("The staged canonical commit crossed a composition or selection boundary.", STALE);
2776
+ if (this.version !== baseVersion) return refuse("The staged canonical commit is stale.", STALE);
2777
+ if (!isCanonicalProjectionTransaction(transaction, this)) return refuse("The staged canonical projection was changed after preparation.", HOST_TRANSACTION);
2790
2778
  for (const blockId of applied.value.touched.inserted) this.allocatedBlockIds.add(blockId.toUpperCase());
2791
2779
  for (const op of ops) {
2792
2780
  if (op.type === DOCUMENT_OP_TYPES.SPLIT_BLOCK) this.allocatedBlockIds.add(op.newBlockId.toUpperCase());
@@ -2846,13 +2834,13 @@ const createCanonicalSession = (document, styles, { idLease, newOpId } = {}) =>
2846
2834
  const owned = cloneDocumentWithParagraphPropertySources(document);
2847
2835
  const source = normalizeCanonicalSource(owned);
2848
2836
  const unsupported = unsupportedSeedReason(source.document);
2849
- if (unsupported !== null) return refuse(unsupported);
2837
+ if (unsupported !== null) return refuse(unsupported, { gap: CANONICAL_GAP.storyContentProjection });
2850
2838
  const identified = preservePropertySourcesWholeStories({
2851
2839
  target: normalizeForOps(source.document),
2852
2840
  source: owned
2853
2841
  });
2854
2842
  const validated = validateOpsDocument(identified);
2855
- if (validated.isErr()) return refuse(validated.error.message);
2843
+ if (validated.isErr()) return refuseOp(validated.error);
2856
2844
  const caches = newStoryProjectionCaches();
2857
2845
  const normalized = preservePropertySourcesWholeStories({
2858
2846
  target: normalizeCanonicalListRendering(identified, caches.lists).document,
@@ -2883,7 +2871,7 @@ const visibleDeletionContext = (state) => {
2883
2871
  const { selection } = state;
2884
2872
  const paragraphDepth = selection.$from.depth;
2885
2873
  const containerDepth = paragraphDepth - 1;
2886
- if (containerDepth < 0 || selection.$from.node(paragraphDepth).type.name !== "paragraph") return refuse("Canonical deletion requires a caret inside a paragraph.");
2874
+ if (containerDepth < 0 || selection.$from.node(paragraphDepth).type.name !== "paragraph") return refuse("Canonical deletion requires a caret inside a paragraph.", INVALID_REQUEST);
2887
2875
  const container = selection.$from.node(containerDepth);
2888
2876
  const containerStart = selection.$from.start(containerDepth);
2889
2877
  const index = selection.$from.index(containerDepth);
@@ -2901,7 +2889,7 @@ const visibleDeletionContext = (state) => {
2901
2889
  const native = canonicalNativeCells(paragraph);
2902
2890
  if (native.isErr()) {
2903
2891
  issue = new CanonicalSessionError({
2904
- ground: { gap: CANONICAL_GAP.dispatch },
2892
+ ground: { gap: CANONICAL_GAP.storyContentProjection },
2905
2893
  reason: "refused",
2906
2894
  message: native.error.message
2907
2895
  });
@@ -2914,7 +2902,7 @@ const visibleDeletionContext = (state) => {
2914
2902
  const to = containerStart + paragraphOffset + 1 + cell.to;
2915
2903
  if (cell.type !== "text" && selection.from > from && selection.from < to) {
2916
2904
  issue = new CanonicalSessionError({
2917
- ground: { gap: CANONICAL_GAP.dispatch },
2905
+ ground: INVALID_REQUEST,
2918
2906
  reason: "refused",
2919
2907
  message: "Character deletion cannot start inside an inline atom."
2920
2908
  });
@@ -2955,20 +2943,20 @@ const deletionRange = (state, direction) => {
2955
2943
  to: selection.to
2956
2944
  });
2957
2945
  if (selection instanceof AllSelection) return Result.ok(canonicalSelectionRange(state));
2958
- if (!(selection instanceof TextSelection)) return refuse("Canonical deletion requires text, an inline atom, or the whole document selection.");
2946
+ if (!(selection instanceof TextSelection)) return refuse("Canonical deletion requires text, an inline atom, or the whole document selection.", INVALID_REQUEST);
2959
2947
  if (!selection.empty) return Result.ok({
2960
2948
  from: selection.from,
2961
2949
  to: selection.to
2962
2950
  });
2963
2951
  const parent = selection.$from.parent;
2964
2952
  const offset = selection.$from.parentOffset;
2965
- if ((direction === "backward" ? parent.childBefore(offset).node : parent.childAfter(offset).node)?.type.name === "noteMarker") return refuse("Automatic note marks cannot be deleted as characters.");
2953
+ if ((direction === "backward" ? parent.childBefore(offset).node : parent.childAfter(offset).node)?.type.name === "noteMarker") return refuse("Automatic note marks cannot be deleted as characters.", INVALID_REQUEST);
2966
2954
  const context = visibleDeletionContext(state);
2967
2955
  if (context.isErr()) return context;
2968
2956
  const { text, physicalStarts, physicalEnds, visibleOffset } = context.value;
2969
- if (splitsSurrogatePair(text, visibleOffset)) return refuse("The deletion would split a surrogate pair.");
2970
- if (splitsGraphemeCluster(text, visibleOffset)) return refuse("Character deletion requires a caret at a grapheme boundary.");
2971
- if (direction === "backward" && visibleOffset === 0 || direction === "forward" && visibleOffset === text.length) return refuse("There is no visible character to delete in this paragraph.");
2957
+ if (splitsSurrogatePair(text, visibleOffset)) return refuse("The deletion would split a surrogate pair.", INVALID_REQUEST);
2958
+ if (splitsGraphemeCluster(text, visibleOffset)) return refuse("Character deletion requires a caret at a grapheme boundary.", INVALID_REQUEST);
2959
+ if (direction === "backward" && visibleOffset === 0 || direction === "forward" && visibleOffset === text.length) return refuse("There is no visible character to delete in this paragraph.", INVALID_REQUEST);
2972
2960
  let boundary = visibleOffset + (direction === "backward" ? -1 : 1);
2973
2961
  while (splitsGraphemeCluster(text, boundary)) boundary += direction === "backward" ? -1 : 1;
2974
2962
  const from = physicalStarts.at(direction === "backward" ? boundary : visibleOffset);
@@ -3005,7 +2993,7 @@ const measuredDeletionRange = (state, measured) => {
3005
2993
  state.doc.nodesBetween(from, to, (node) => {
3006
2994
  if (node.type.name === "noteMarker") noteMarkers += 1;
3007
2995
  });
3008
- if (noteMarkers > 0) return refuse("Automatic note marks cannot be deleted as characters.");
2996
+ if (noteMarkers > 0) return refuse("Automatic note marks cannot be deleted as characters.", INVALID_REQUEST);
3009
2997
  return Result.ok({
3010
2998
  from,
3011
2999
  to