@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
@@ -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";
@@ -43,57 +44,44 @@ 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,
@@ -286,13 +274,11 @@ var CanonicalProjection = class CanonicalProjection {
286
274
  this.addresses.set(entry.blockId, address);
287
275
  return address;
288
276
  }
289
- /** The paragraph whose content holds `position`, its ends included. */
290
- /** Whether `position` lies in a text box's content. */
291
- insideTextBox(position) {
292
- const resolved = this.doc.resolve(Math.max(0, Math.min(position, this.doc.content.size)));
293
- for (let depth = resolved.depth; depth > 0; depth -= 1) if (resolved.node(depth).type.name === "textBox") return true;
294
- return false;
295
- }
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
+ */
296
282
  paragraphAround(position) {
297
283
  let low = 0;
298
284
  let high = this.starts.length - 1;
@@ -322,14 +308,15 @@ var CanonicalProjection = class CanonicalProjection {
322
308
  return this.addressOf(block, found);
323
309
  }
324
310
  addressAt(position, edge = "caret") {
325
- 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.");
326
313
  position = canonicalContentPosition(this.doc, position);
327
314
  const paragraph = this.paragraphAround(position);
328
- 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.");
329
316
  const relative = position - paragraph.start;
330
317
  const offset = paragraph.gaps.offsetOf(relative);
331
- if (offset < 0) return refuse("The input splits an indivisible inline element.");
332
- if (splitsSurrogatePair(paragraph.text, offset)) return refuse("The input would split a surrogate pair.");
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.");
333
320
  const gaps = paragraph.gaps.at(offset) ?? panic("Missing canonical boundary");
334
321
  const gap = gaps.find((entry) => entry.position === relative) ?? panic("Missing canonical native gap");
335
322
  let ordinal = gap.zeroWidthBefore;
@@ -377,13 +364,13 @@ var CanonicalProjection = class CanonicalProjection {
377
364
  }
378
365
  positionAt(address) {
379
366
  const paragraph = this.paragraph(address.blockId);
380
- 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.");
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);
381
368
  const gaps = paragraph.gaps.at(address.offset) ?? panic("Missing canonical boundary");
382
369
  const lastOrdinal = (gaps.at(-1) ?? panic("Missing canonical seam")).last;
383
370
  const ordinal = address.zeroWidthBefore ?? lastOrdinal;
384
371
  const gap = gaps.find(({ zeroWidthBefore }) => zeroWidthBefore === ordinal) ?? gaps.find(({ first, last }) => first <= ordinal && ordinal <= last);
385
- if (!Number.isInteger(ordinal) || ordinal < 0 || ordinal > lastOrdinal) return refuse("The canonical selection is outside a paragraph gap.");
386
- if (gap === void 0) return refuse("This source gap is inside a collapsed or erased inline boundary and has no editor position.");
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);
387
374
  return Result.ok(paragraph.start + gap.position);
388
375
  }
389
376
  selectionAt(state) {
@@ -402,7 +389,7 @@ var CanonicalProjection = class CanonicalProjection {
402
389
  const range = canonicalSelectionRange(state);
403
390
  anchorPosition = range.from;
404
391
  headPosition = range.to;
405
- } 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);
406
393
  const anchor = this.addressAt(anchorPosition);
407
394
  if (anchor.isErr()) return anchor;
408
395
  const head = this.addressAt(headPosition);
@@ -727,7 +714,7 @@ const projectBlock = (top, index, walk) => {
727
714
  const inline = walk.inline === void 0 ? projectCanonicalInline(inlineArgs) : walk.inline.project(inlineArgs);
728
715
  if (inline.isErr()) {
729
716
  failure = new CanonicalSessionError({
730
- ground: { gap: CANONICAL_GAP.dispatch },
717
+ ground: { gap: CANONICAL_GAP.storyContentProjection },
731
718
  reason: "refused",
732
719
  message: inline.error.message
733
720
  });
@@ -846,7 +833,7 @@ const projectEveryBlock = ({ doc, content, story, markersOf, inline }) => {
846
833
  openAfter: open.current
847
834
  });
848
835
  }
849
- 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);
850
837
  return Result.ok(new CanonicalProjection({
851
838
  doc,
852
839
  story,
@@ -950,7 +937,7 @@ const projectChangedBlocks = (previous, { doc, content, story, markersOf, inline
950
937
  };
951
938
  const project = ({ document, styles, story = OP_STORIES.MAIN, caches, previous }) => {
952
939
  const body = findStoryBody(document, story);
953
- if (!body) return refuse("The canonical story no longer exists.");
940
+ if (!body) return refuse("The canonical story no longer exists.", STALE);
954
941
  const currentStyles = Object.hasOwn(document.package, "styles") ? document.package.styles : styles;
955
942
  const options = storyConversionOptions({
956
943
  styles: currentStyles,
@@ -967,7 +954,7 @@ const project = ({ document, styles, story = OP_STORIES.MAIN, caches, previous }
967
954
  return footnoteToProseDoc(body.content, options);
968
955
  },
969
956
  catch: (cause) => new CanonicalSessionError({
970
- ground: { gap: CANONICAL_GAP.dispatch },
957
+ ground: INTERNAL,
971
958
  reason: "refused",
972
959
  message: `Canonical projection failed: ${cause instanceof Error ? cause.message : String(cause)}`
973
960
  })
@@ -991,6 +978,7 @@ const intentStory = (intent) => {
991
978
  case "replaceFragment":
992
979
  case "pasteBlocks":
993
980
  case "moveFragment":
981
+ case "moveBlocks":
994
982
  case "replaceText":
995
983
  case "formatRun":
996
984
  case "insertAtom": return intent.from.story;
@@ -1056,19 +1044,19 @@ const projectionChangeOf = (projected, published) => {
1056
1044
  };
1057
1045
  /** The model publishes only after PM and every plugin accept its exact projection. */
1058
1046
  const publishCanonicalProjection = ({ state, commit, session }) => {
1059
- if (!isCanonicalProjectionTransaction(commit.transaction, session)) return refuse("The staged canonical projection is unauthorized.");
1047
+ if (!isCanonicalProjectionTransaction(commit.transaction, session)) return refuse("The staged canonical projection is unauthorized.", INTERNAL);
1060
1048
  const applied = Result.try({
1061
1049
  try: () => state.applyTransaction(commit.transaction),
1062
1050
  catch: (cause) => new CanonicalSessionError({
1063
- ground: { gap: CANONICAL_GAP.dispatch },
1051
+ ground: INTERNAL,
1064
1052
  reason: "refused",
1065
1053
  message: `Canonical plugin staging failed: ${cause instanceof Error ? cause.message : String(cause)}`
1066
1054
  })
1067
1055
  });
1068
1056
  if (applied.isErr()) return applied;
1069
1057
  const staged = applied.value;
1070
- if (!staged.transactions.includes(commit.transaction)) return refuse("A plugin refused or changed the canonical projection: a plugin filtered the projection transaction.");
1071
- 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)}.`);
1058
+ if (!staged.transactions.includes(commit.transaction)) return refuse("A plugin refused or changed the canonical projection: a plugin filtered the projection transaction.", HOST_TRANSACTION);
1059
+ 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);
1072
1060
  const published = commit.publish();
1073
1061
  if (published.isErr()) return published;
1074
1062
  return Result.ok(staged);
@@ -1241,7 +1229,7 @@ var CanonicalSession = class {
1241
1229
  * cleared.
1242
1230
  */
1243
1231
  compileReplacementPieces({ projection, pieces, start, end, intent }) {
1244
- const refused = (message) => refuseUnder({ gap: CANONICAL_GAP.commentReplacementAlignment }, message);
1232
+ const refused = (message) => refuse(message, { gap: CANONICAL_GAP.commentReplacementAlignment });
1245
1233
  const addressed = [];
1246
1234
  for (const [index, piece] of pieces.entries()) {
1247
1235
  const from = index === 0 ? Result.ok(start) : projection.inputAddressAt(piece.from, "afterMarkers");
@@ -1310,9 +1298,9 @@ var CanonicalSession = class {
1310
1298
  const fresh = this.freshBlockIds([1]);
1311
1299
  if (fresh.isErr()) return fresh;
1312
1300
  const id = fresh.value[0]?.[0];
1313
- return id === void 0 ? refuse("The paragraph identity lease is exhausted.") : Result.ok(id);
1301
+ return id === void 0 ? refuse("The paragraph identity lease is exhausted.", ID_SPACE) : Result.ok(id);
1314
1302
  }
1315
- if (this.nextBlockId > 2147483647) return refuse("The paragraph identity space is exhausted.");
1303
+ if (this.nextBlockId > 2147483647) return refuse("The paragraph identity space is exhausted.", ID_SPACE);
1316
1304
  return Result.ok(this.nextBlockId.toString(16).padStart(8, "0").toUpperCase());
1317
1305
  }
1318
1306
  /**
@@ -1330,11 +1318,11 @@ var CanonicalSession = class {
1330
1318
  count: total,
1331
1319
  taken: (id) => this.allocatedBlockIds.has(formatParaId(id))
1332
1320
  });
1333
- if (leased.length < total) return refuse("The paragraph identity lease is exhausted.");
1321
+ if (leased.length < total) return refuse("The paragraph identity lease is exhausted.", ID_SPACE);
1334
1322
  ids.push(...leased.map(formatParaId));
1335
1323
  }
1336
1324
  for (let candidate = this.nextBlockId; ids.length < total; candidate += 1) {
1337
- if (candidate > 2147483647) return refuse("The paragraph identity space is exhausted.");
1325
+ if (candidate > 2147483647) return refuse("The paragraph identity space is exhausted.", ID_SPACE);
1338
1326
  const id = candidate.toString(16).padStart(8, "0").toUpperCase();
1339
1327
  if (!this.allocatedBlockIds.has(id)) ids.push(id);
1340
1328
  }
@@ -1387,7 +1375,8 @@ var CanonicalSession = class {
1387
1375
  case "insertHyperlink":
1388
1376
  case "replaceFragment":
1389
1377
  case "pasteBlocks":
1390
- case "moveFragment": return true;
1378
+ case "moveFragment":
1379
+ case "moveBlocks": return true;
1391
1380
  case "replaceText":
1392
1381
  case "insertAtom":
1393
1382
  case "formatRun":
@@ -1421,7 +1410,7 @@ var CanonicalSession = class {
1421
1410
  }
1422
1411
  get document() {
1423
1412
  if (this.isComposing) throw new CanonicalSessionError({
1424
- ground: { gap: CANONICAL_GAP.dispatch },
1413
+ ground: COMPOSING,
1425
1414
  reason: "refused",
1426
1415
  message: "Composition must finish before taking a snapshot."
1427
1416
  });
@@ -1442,7 +1431,7 @@ var CanonicalSession = class {
1442
1431
  }
1443
1432
  captureSaveSnapshot() {
1444
1433
  if (this.isComposing) throw new CanonicalSessionError({
1445
- ground: { gap: CANONICAL_GAP.saveSerialization },
1434
+ ground: { condition: CANONICAL_CONDITION.composing },
1446
1435
  reason: "refused",
1447
1436
  message: "Composition must finish before saving the canonical document."
1448
1437
  });
@@ -1590,7 +1579,7 @@ var CanonicalSession = class {
1590
1579
  const projected = this.projectStory(story);
1591
1580
  if (projected.isErr()) return projected;
1592
1581
  const projection = projected.value;
1593
- if (state.doc !== projection.doc && !state.doc.eq(projection.doc)) return refuse("The story editor shows a stale canonical projection.");
1582
+ if (state.doc !== projection.doc && !state.doc.eq(projection.doc)) return refuse("The story editor shows a stale canonical projection.", STALE);
1594
1583
  const selection = projection.selectionAt(state);
1595
1584
  if (selection.isErr()) {
1596
1585
  this.storySelections.delete(storyProjectionKey(story));
@@ -1620,14 +1609,14 @@ var CanonicalSession = class {
1620
1609
  * without a lease takes one.
1621
1610
  */
1622
1611
  adoptIdLease(lease) {
1623
- if (this.leased !== void 0) return refuse("The session already holds an id lease.");
1624
- if (this.currentVersion !== 0) return refuse("The session was edited before it took an id lease.");
1612
+ if (this.leased !== void 0) return refuse("The session already holds an id lease.", INVALID_REQUEST);
1613
+ if (this.currentVersion !== 0) return refuse("The session was edited before it took an id lease.", INVALID_REQUEST);
1625
1614
  this.leased = new CanonicalIdLease(lease, this.currentDocument);
1626
1615
  return Result.ok(void 0);
1627
1616
  }
1628
1617
  /** Add blocks the authority granted; ids this session already minted stay spent. */
1629
1618
  extendIdLease(lease) {
1630
- if (this.leased === void 0) return refuse("The session was created without an id lease.");
1619
+ if (this.leased === void 0) return refuse("The session was created without an id lease.", INVALID_REQUEST);
1631
1620
  this.leased.extend(lease);
1632
1621
  return Result.ok(void 0);
1633
1622
  }
@@ -1647,7 +1636,7 @@ var CanonicalSession = class {
1647
1636
  this.groupingBoundary += 1;
1648
1637
  }
1649
1638
  beginComposition() {
1650
- if (this.isComposing) return refuse("A canonical composition is already pending.");
1639
+ if (this.isComposing) return refuse("A canonical composition is already pending.", COMPOSING);
1651
1640
  this.lifecycle = { type: "composing" };
1652
1641
  this.breakUndoGroup();
1653
1642
  return Result.ok(void 0);
@@ -1657,8 +1646,8 @@ var CanonicalSession = class {
1657
1646
  this.breakUndoGroup();
1658
1647
  }
1659
1648
  checkState(state, projection = this.projection) {
1660
- if (this.isComposing) return refuse("Composition must finish before committing another edit.");
1661
- if (state.doc !== projection.doc && !state.doc.eq(projection.doc)) return refuse("The input uses a stale canonical projection.");
1649
+ if (this.isComposing) return refuse("Composition must finish before committing another edit.", COMPOSING);
1650
+ if (state.doc !== projection.doc && !state.doc.eq(projection.doc)) return refuse("The input uses a stale canonical projection.", STALE);
1662
1651
  return Result.ok(void 0);
1663
1652
  }
1664
1653
  prepareReplace(state, { from, to, text, story = OP_STORIES.MAIN, semantic = "replacement", compositionPhase, time = Date.now() }) {
@@ -1667,16 +1656,16 @@ var CanonicalSession = class {
1667
1656
  const projection = projected.value;
1668
1657
  const checked = this.checkState(state, projection);
1669
1658
  if (checked.isErr()) return checked;
1670
- if (!Number.isFinite(time)) return refuse("The input time is invalid.");
1671
- 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.");
1659
+ if (!Number.isFinite(time)) return refuse("The input time is invalid.", INVALID_REQUEST);
1660
+ 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);
1672
1661
  if (from === to && text.length === 0) return noChange("The input makes no text change.");
1673
1662
  const replacesStructuralSelection = state.selection instanceof AllSelection && from === state.selection.from && to === state.selection.to;
1674
1663
  if (state.selection instanceof CellSelection) {
1675
- if (from !== state.selection.from || to !== state.selection.to) return refuse("A replacement range cannot partially address a cell selection.");
1664
+ if (from !== state.selection.from || to !== state.selection.to) return refuse("A replacement range cannot partially address a cell selection.", INVALID_REQUEST);
1676
1665
  const ranges = canonicalCellSelectionRanges(state.selection);
1677
1666
  const firstRange = ranges.at(0);
1678
1667
  const lastRange = ranges.at(-1);
1679
- if (firstRange === void 0 || lastRange === void 0) return refuse("The selected cells contain no editable text.");
1668
+ if (firstRange === void 0 || lastRange === void 0) return refuse("The selected cells contain no editable text.", INVALID_REQUEST);
1680
1669
  const intents = [];
1681
1670
  const commentChanges = [];
1682
1671
  let first = true;
@@ -1708,7 +1697,7 @@ var CanonicalSession = class {
1708
1697
  },
1709
1698
  changes: commentChanges,
1710
1699
  removal: this.replacementRemoval()
1711
- })) return refuseUnder({ gap: CANONICAL_GAP.commentReplacementAlignment }, "Canonical replacement cannot preserve the aligned comment ranges.");
1700
+ })) return refuse("Canonical replacement cannot preserve the aligned comment ranges.", { gap: CANONICAL_GAP.commentReplacementAlignment });
1712
1701
  return this.prepareIntents(state, {
1713
1702
  intents,
1714
1703
  semantic
@@ -1734,7 +1723,7 @@ var CanonicalSession = class {
1734
1723
  to: end.value,
1735
1724
  suggesting: this.mode.type === "suggesting" ? { author: this.mode.author } : void 0
1736
1725
  });
1737
- if (retirement.isErr()) return refuse(retirement.error.message);
1726
+ if (retirement.isErr()) return refuseOp(retirement.error);
1738
1727
  const removal = this.replacementRemoval();
1739
1728
  const whole = [{
1740
1729
  from: inputFrom,
@@ -1759,7 +1748,7 @@ var CanonicalSession = class {
1759
1748
  comments: removal.comments
1760
1749
  }) : void 0;
1761
1750
  const retired = /* @__PURE__ */ new Set([...retirement.value?.commentIds ?? [], ...split?.retiredCommentIds ?? []]);
1762
- 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.");
1751
+ 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 });
1763
1752
  pieces = split.changes;
1764
1753
  }
1765
1754
  }
@@ -1786,7 +1775,7 @@ var CanonicalSession = class {
1786
1775
  });
1787
1776
  if (compiled.isErr()) {
1788
1777
  if (compiled.error instanceof CanonicalSessionError) return Result.err(compiled.error);
1789
- return compiled.error.reason === DOCUMENT_OP_REFUSAL_REASONS.NO_CHANGE ? noChange(compiled.error.message) : refuse(compiled.error.message);
1778
+ return compiled.error.reason === DOCUMENT_OP_REFUSAL_REASONS.NO_CHANGE ? noChange(compiled.error.message) : refuseOp(compiled.error);
1790
1779
  }
1791
1780
  const { ops, selection: caret } = compiled.value;
1792
1781
  const postSelection = {
@@ -1851,9 +1840,9 @@ var CanonicalSession = class {
1851
1840
  * the edit happens at the start of the first, as the editor's own command
1852
1841
  * does over a cell selection. One commit, so one undo step.
1853
1842
  */
1854
- prepareCellSelectionStructure(state, structure, { resourceOps = [], semantic = "structure" } = {}) {
1855
- if (!(state.selection instanceof CellSelection)) return refuse("The structural edit needs a cell selection.");
1856
- const projected = this.projectStory(OP_STORIES.MAIN);
1843
+ prepareCellSelectionStructure(state, structure, { resourceOps = [], semantic = "structure", story = OP_STORIES.MAIN } = {}) {
1844
+ if (!(state.selection instanceof CellSelection)) return refuse("The structural edit needs a cell selection.", INVALID_REQUEST);
1845
+ const projected = this.projectStory(story);
1857
1846
  if (projected.isErr()) return projected;
1858
1847
  const projection = projected.value;
1859
1848
  const intents = [];
@@ -1872,7 +1861,7 @@ var CanonicalSession = class {
1872
1861
  text: ""
1873
1862
  });
1874
1863
  }
1875
- if (first === void 0) return refuse("The cell selection is empty.");
1864
+ if (first === void 0) return refuse("The cell selection is empty.", INVALID_REQUEST);
1876
1865
  intents.push(structure({
1877
1866
  ...first,
1878
1867
  offset: 0,
@@ -1891,7 +1880,7 @@ var CanonicalSession = class {
1891
1880
  const first = intents.at(0);
1892
1881
  if (first === void 0) return noChange("The intent batch is empty.");
1893
1882
  const story = intentStory(first);
1894
- if (intents.some((intent) => !sameStory(story, intentStory(intent)))) return refuse("A compound input must address one story.");
1883
+ if (intents.some((intent) => !sameStory(story, intentStory(intent)))) return refuse("A compound input must address one story.", INVALID_REQUEST);
1895
1884
  const projected = this.projectStory(story);
1896
1885
  if (projected.isErr()) return projected;
1897
1886
  const checked = this.checkState(state, projected.value);
@@ -1904,7 +1893,7 @@ var CanonicalSession = class {
1904
1893
  const edits = [];
1905
1894
  if (resourceOps.length > 0) {
1906
1895
  const imported = applyDocumentOps(document, resourceOps);
1907
- if (imported.isErr()) return refuse(imported.error.message);
1896
+ if (imported.isErr()) return refuseOp(imported.error);
1908
1897
  document = imported.value.document;
1909
1898
  edits.push(imported.value);
1910
1899
  }
@@ -2012,7 +2001,7 @@ var CanonicalSession = class {
2012
2001
  return true;
2013
2002
  },
2014
2003
  prepare: (state, postSelection) => {
2015
- if (version !== this.currentVersion || base !== this.currentDocument) return refuse("The compiled operations use a stale canonical document.");
2004
+ if (version !== this.currentVersion || base !== this.currentDocument) return refuse("The compiled operations use a stale canonical document.", STALE);
2016
2005
  const combined = combineEdits(document, effects.map(({ inverse, touched }) => ({
2017
2006
  document,
2018
2007
  inverse,
@@ -2123,12 +2112,16 @@ var CanonicalSession = class {
2123
2112
  }
2124
2113
  });
2125
2114
  }
2126
- prepareSplit(state) {
2127
- const from = this.projection.inputAddressAt(state.selection.from);
2115
+ /** Split the paragraph at the selection of the editor showing `story`. */
2116
+ prepareSplit(state, story = OP_STORIES.MAIN) {
2117
+ const projected = this.projectStory(story);
2118
+ if (projected.isErr()) return projected;
2119
+ const projection = projected.value;
2120
+ const from = projection.inputAddressAt(state.selection.from);
2128
2121
  if (from.isErr()) return from;
2129
- const to = this.projection.inputAddressAt(state.selection.to);
2122
+ const to = projection.inputAddressAt(state.selection.to);
2130
2123
  if (to.isErr()) return to;
2131
- const source = this.projection.paragraph(from.value.blockId);
2124
+ const source = projection.paragraph(from.value.blockId);
2132
2125
  const nextStyle = (Object.hasOwn(this.currentDocument.package, "styles") ? this.currentDocument.package.styles : this.styles)?.styles.find(({ styleId }) => styleId === source?.source.formatting?.styleId)?.next;
2133
2126
  const fresh = this.freshBlockId();
2134
2127
  if (fresh.isErr()) return fresh;
@@ -2148,11 +2141,15 @@ var CanonicalSession = class {
2148
2141
  });
2149
2142
  return this.prepareIntents(state, { intents });
2150
2143
  }
2151
- prepareJoin(state, direction) {
2152
- const checked = this.checkState(state);
2144
+ /** Join the paragraph at the caret of the editor showing `story` with its neighbour. */
2145
+ prepareJoin(state, direction, story = OP_STORIES.MAIN) {
2146
+ const projected = this.projectStory(story);
2147
+ if (projected.isErr()) return projected;
2148
+ const projection = projected.value;
2149
+ const checked = this.checkState(state, projection);
2153
2150
  if (checked.isErr()) return checked;
2154
- if (!state.selection.empty) return refuse("Join requires a collapsed text selection.");
2155
- const at = this.projection.inputAddressAt(state.selection.from);
2151
+ if (!state.selection.empty) return refuse("Join requires a collapsed text selection.", INVALID_REQUEST);
2152
+ const at = projection.inputAddressAt(state.selection.from);
2156
2153
  if (at.isErr()) return at;
2157
2154
  const groups = editorParagraphGroups(this.currentDocument, at.value.story);
2158
2155
  const index = groups.findIndex(({ paragraphs }) => paragraphs.some((paragraph) => paragraph.paraId === at.value.blockId));
@@ -2162,8 +2159,8 @@ var CanonicalSession = class {
2162
2159
  const first = firstGroup?.paragraphs.at(-1);
2163
2160
  const second = secondGroup?.paragraphs.at(0);
2164
2161
  if (!first?.paraId || !second?.paraId) return noChange("There is no adjacent paragraph to join.");
2165
- if (this.projection.paragraph(first.paraId)?.container !== this.projection.paragraph(second.paraId)?.container) return noChange("There is no adjacent paragraph to join.");
2166
- if (!isCanonicalJoinBoundary(state, direction)) return refuse("Join requires a caret at a paragraph boundary.");
2162
+ if (projection.paragraph(first.paraId)?.container !== projection.paragraph(second.paraId)?.container) return noChange("There is no adjacent paragraph to join.");
2163
+ if (!isCanonicalJoinBoundary(state, direction)) return refuse("Join requires a caret at a paragraph boundary.", INVALID_REQUEST);
2167
2164
  return this.prepareIntent(state, {
2168
2165
  type: "joinParagraphs",
2169
2166
  story: at.value.story,
@@ -2195,7 +2192,7 @@ var CanonicalSession = class {
2195
2192
  const resolved = locks.unlocked.flat();
2196
2193
  const ops = [...before, ...resolved.length === 0 ? [] : resolve(resolved)];
2197
2194
  const applied = applyDocumentOps(this.currentDocument, ops);
2198
- if (applied.isErr()) return refuse(applied.error.message);
2195
+ if (applied.isErr()) return refuseOp(applied.error);
2199
2196
  const projected = project({
2200
2197
  document: applied.value.document,
2201
2198
  styles: this.styles,
@@ -2205,7 +2202,7 @@ var CanonicalSession = class {
2205
2202
  if (projected.isErr()) return projected;
2206
2203
  const surviving = projected.value.paragraph(preSelection.value.head.blockId);
2207
2204
  const first = projected.value.firstParagraph;
2208
- if (first === void 0) return refuse("Resolution left no paragraph.");
2205
+ if (first === void 0) return refuse("Resolution left no paragraph.", INTERNAL);
2209
2206
  let offset = surviving ? Math.min(preSelection.value.head.offset, surviving.text.length) : 0;
2210
2207
  if (surviving && splitsSurrogatePair(surviving.text, offset)) offset -= 1;
2211
2208
  const caret = {
@@ -2289,7 +2286,7 @@ var CanonicalSession = class {
2289
2286
  const body = findStoryBody(this.currentDocument, story);
2290
2287
  if (body === void 0) {
2291
2288
  this.storyProjections.delete(key);
2292
- return refuse("The canonical story no longer exists.");
2289
+ return refuse("The canonical story no longer exists.", STALE);
2293
2290
  }
2294
2291
  const cached = this.storyProjections.get(key);
2295
2292
  const { styles, theme } = this.currentDocument.package;
@@ -2310,7 +2307,7 @@ var CanonicalSession = class {
2310
2307
  return projected;
2311
2308
  }
2312
2309
  prepareOperations(state, ops) {
2313
- if (ops.length === 0) return refuse("The operation batch is empty.");
2310
+ if (ops.length === 0) return refuse("The operation batch is empty.", INVALID_REQUEST);
2314
2311
  const selected = this.projection.selectionAt(state);
2315
2312
  if (selected.isErr()) return selected;
2316
2313
  let preparedOps = ops;
@@ -2353,7 +2350,7 @@ var CanonicalSession = class {
2353
2350
  };
2354
2351
  if (ops.length > 1) {
2355
2352
  const applied = applyDocumentOp(cloneDocumentWithParagraphPropertySources(document), structuredClone(next));
2356
- if (applied.isErr()) return refuse(applied.error.message);
2353
+ if (applied.isErr()) return refuseOp(applied.error);
2357
2354
  document = applied.value.document;
2358
2355
  }
2359
2356
  tracked.push(next);
@@ -2422,7 +2419,7 @@ var CanonicalSession = class {
2422
2419
  if (stack === "undo") this.applied.length = 0;
2423
2420
  else this.undone.length = 0;
2424
2421
  this.reportHistoryDrop(dropped);
2425
- return refuse(`The ${stack} step no longer applies after a remote edit: ${applied.error.message}`);
2422
+ return refuse(`The ${stack} step no longer applies after a remote edit: ${applied.error.message}`, STALE);
2426
2423
  }
2427
2424
  /** Called with every history drop a remote edit causes; returns the unsubscribe. */
2428
2425
  onHistoryDrop(listener) {
@@ -2463,7 +2460,7 @@ var CanonicalSession = class {
2463
2460
  const checked = this.checkState(state, projected.value);
2464
2461
  if (checked.isErr()) return checked;
2465
2462
  const applied = applyDocumentOps(this.currentDocument, change.batch.ops);
2466
- if (applied.isErr()) return refuse(applied.error.message);
2463
+ if (applied.isErr()) return refuseOp(applied.error);
2467
2464
  const shown = projected.value.selectionAt(state);
2468
2465
  const before = shown.isOk() ? shown.value : this.currentSelection;
2469
2466
  const selection = remoteSelection({
@@ -2570,7 +2567,7 @@ var CanonicalSession = class {
2570
2567
  }
2571
2568
  prepareUndo(state, story = OP_STORIES.MAIN) {
2572
2569
  const group = this.applied.at(-1);
2573
- if (group === void 0) return refuse("There is no canonical edit to undo.");
2570
+ if (group === void 0) return refuse("There is no canonical edit to undo.", INVALID_REQUEST);
2574
2571
  const ops = undoOpsOf(group);
2575
2572
  const rebased = this.rebasedStepApplies(group, ops, "undo");
2576
2573
  if (rebased.isErr()) return rebased;
@@ -2597,7 +2594,7 @@ var CanonicalSession = class {
2597
2594
  }
2598
2595
  prepareRedo(state, story = OP_STORIES.MAIN) {
2599
2596
  const undone = this.undone.at(-1);
2600
- if (undone === void 0) return refuse("There is no canonical edit to redo.");
2597
+ if (undone === void 0) return refuse("There is no canonical edit to redo.", INVALID_REQUEST);
2601
2598
  const rebased = this.rebasedStepApplies(undone.group, undone.redoOps, "redo");
2602
2599
  if (rebased.isErr()) return rebased;
2603
2600
  const propertySourceDocument = undone.group.rebased === true ? void 0 : undone.group.entries.at(-1)?.postDocument;
@@ -2632,7 +2629,7 @@ var CanonicalSession = class {
2632
2629
  const checked = this.checkState(state, previous.value);
2633
2630
  if (checked.isErr()) return checked;
2634
2631
  const applied = stagedApplied === void 0 ? applyDocumentOps(this.currentDocument, ops) : Result.ok(stagedApplied);
2635
- if (applied.isErr()) return refuse(applied.error.message);
2632
+ if (applied.isErr()) return refuseOp(applied.error);
2636
2633
  if (applied.value.inverse.length === 0) return noChange("The intent makes no document change.");
2637
2634
  const locked = admission === CANONICAL_ADMISSION.restage ? null : lockViolationBetween(this.currentDocument, applied.value.document);
2638
2635
  if (locked !== null) return lockRefusal(locked);
@@ -2645,7 +2642,7 @@ var CanonicalSession = class {
2645
2642
  applied.value.document = normalized.document;
2646
2643
  applied.value.inverse = inverseMeetingDocument(normalized.document, normalized.inverse.concat(applied.value.inverse));
2647
2644
  const leaseJudgement = origin === "remote" ? this.leased?.admit(applied.value.document) : this.leased?.judge(applied.value.document);
2648
- if (leaseJudgement?.type === "outside") return refuse(`The ${leaseJudgement.id.kind} id ${leaseJudgement.id.id} is outside this author's id lease.`);
2645
+ if (leaseJudgement?.type === "outside") return refuse(`The ${leaseJudgement.id.kind} id ${leaseJudgement.id.id} is outside this author's id lease.`, INVALID_REQUEST);
2649
2646
  const changed = changedStories({
2650
2647
  document: applied.value.document,
2651
2648
  previous: this.currentDocument
@@ -2747,7 +2744,7 @@ var CanonicalSession = class {
2747
2744
  type: "near",
2748
2745
  anchor: state.selection.anchor
2749
2746
  }
2750
- })) return refuse("Canonical history cannot restore the selected inline atom.");
2747
+ })) return refuse("Canonical history cannot restore the selected inline atom.", INTERNAL);
2751
2748
  }
2752
2749
  const shown = (sameStory(selection.anchor.story, projectedStory) && sameStory(selection.head.story, projectedStory) ? placeShownSelection(transaction, projected.value) : void 0) ?? selection;
2753
2750
  const held = projected.value.heldAs(transaction.doc);
@@ -2777,9 +2774,9 @@ var CanonicalSession = class {
2777
2774
  origin,
2778
2775
  history,
2779
2776
  publish: () => {
2780
- if (this.isComposing || this.groupingBoundary !== baseBoundary) return refuse("The staged canonical commit crossed a composition or selection boundary.");
2781
- if (this.version !== baseVersion) return refuse("The staged canonical commit is stale.");
2782
- if (!isCanonicalProjectionTransaction(transaction, this)) return refuse("The staged canonical projection was changed after preparation.");
2777
+ if (this.isComposing || this.groupingBoundary !== baseBoundary) return refuse("The staged canonical commit crossed a composition or selection boundary.", STALE);
2778
+ if (this.version !== baseVersion) return refuse("The staged canonical commit is stale.", STALE);
2779
+ if (!isCanonicalProjectionTransaction(transaction, this)) return refuse("The staged canonical projection was changed after preparation.", HOST_TRANSACTION);
2783
2780
  for (const blockId of applied.value.touched.inserted) this.allocatedBlockIds.add(blockId.toUpperCase());
2784
2781
  for (const op of ops) {
2785
2782
  if (op.type === DOCUMENT_OP_TYPES.SPLIT_BLOCK) this.allocatedBlockIds.add(op.newBlockId.toUpperCase());
@@ -2839,13 +2836,13 @@ const createCanonicalSession = (document, styles, { idLease, newOpId } = {}) =>
2839
2836
  const owned = cloneDocumentWithParagraphPropertySources(document);
2840
2837
  const source = normalizeCanonicalSource(owned);
2841
2838
  const unsupported = unsupportedSeedReason(source.document);
2842
- if (unsupported !== null) return refuse(unsupported);
2839
+ if (unsupported !== null) return refuse(unsupported, { gap: CANONICAL_GAP.storyContentProjection });
2843
2840
  const identified = preservePropertySourcesWholeStories({
2844
2841
  target: normalizeForOps(source.document),
2845
2842
  source: owned
2846
2843
  });
2847
2844
  const validated = validateOpsDocument(identified);
2848
- if (validated.isErr()) return refuse(validated.error.message);
2845
+ if (validated.isErr()) return refuseOp(validated.error);
2849
2846
  const caches = newStoryProjectionCaches();
2850
2847
  const normalized = preservePropertySourcesWholeStories({
2851
2848
  target: normalizeCanonicalListRendering(identified, caches.lists).document,
@@ -2876,7 +2873,7 @@ const visibleDeletionContext = (state) => {
2876
2873
  const { selection } = state;
2877
2874
  const paragraphDepth = selection.$from.depth;
2878
2875
  const containerDepth = paragraphDepth - 1;
2879
- if (containerDepth < 0 || selection.$from.node(paragraphDepth).type.name !== "paragraph") return refuse("Canonical deletion requires a caret inside a paragraph.");
2876
+ if (containerDepth < 0 || selection.$from.node(paragraphDepth).type.name !== "paragraph") return refuse("Canonical deletion requires a caret inside a paragraph.", INVALID_REQUEST);
2880
2877
  const container = selection.$from.node(containerDepth);
2881
2878
  const containerStart = selection.$from.start(containerDepth);
2882
2879
  const index = selection.$from.index(containerDepth);
@@ -2894,7 +2891,7 @@ const visibleDeletionContext = (state) => {
2894
2891
  const native = canonicalNativeCells(paragraph);
2895
2892
  if (native.isErr()) {
2896
2893
  issue = new CanonicalSessionError({
2897
- ground: { gap: CANONICAL_GAP.dispatch },
2894
+ ground: { gap: CANONICAL_GAP.storyContentProjection },
2898
2895
  reason: "refused",
2899
2896
  message: native.error.message
2900
2897
  });
@@ -2907,7 +2904,7 @@ const visibleDeletionContext = (state) => {
2907
2904
  const to = containerStart + paragraphOffset + 1 + cell.to;
2908
2905
  if (cell.type !== "text" && selection.from > from && selection.from < to) {
2909
2906
  issue = new CanonicalSessionError({
2910
- ground: { gap: CANONICAL_GAP.dispatch },
2907
+ ground: INVALID_REQUEST,
2911
2908
  reason: "refused",
2912
2909
  message: "Character deletion cannot start inside an inline atom."
2913
2910
  });
@@ -2948,20 +2945,20 @@ const deletionRange = (state, direction) => {
2948
2945
  to: selection.to
2949
2946
  });
2950
2947
  if (selection instanceof AllSelection) return Result.ok(canonicalSelectionRange(state));
2951
- if (!(selection instanceof TextSelection)) return refuse("Canonical deletion requires text, an inline atom, or the whole document selection.");
2948
+ if (!(selection instanceof TextSelection)) return refuse("Canonical deletion requires text, an inline atom, or the whole document selection.", INVALID_REQUEST);
2952
2949
  if (!selection.empty) return Result.ok({
2953
2950
  from: selection.from,
2954
2951
  to: selection.to
2955
2952
  });
2956
2953
  const parent = selection.$from.parent;
2957
2954
  const offset = selection.$from.parentOffset;
2958
- if ((direction === "backward" ? parent.childBefore(offset).node : parent.childAfter(offset).node)?.type.name === "noteMarker") return refuse("Automatic note marks cannot be deleted as characters.");
2955
+ 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);
2959
2956
  const context = visibleDeletionContext(state);
2960
2957
  if (context.isErr()) return context;
2961
2958
  const { text, physicalStarts, physicalEnds, visibleOffset } = context.value;
2962
- if (splitsSurrogatePair(text, visibleOffset)) return refuse("The deletion would split a surrogate pair.");
2963
- if (splitsGraphemeCluster(text, visibleOffset)) return refuse("Character deletion requires a caret at a grapheme boundary.");
2964
- if (direction === "backward" && visibleOffset === 0 || direction === "forward" && visibleOffset === text.length) return refuse("There is no visible character to delete in this paragraph.");
2959
+ if (splitsSurrogatePair(text, visibleOffset)) return refuse("The deletion would split a surrogate pair.", INVALID_REQUEST);
2960
+ if (splitsGraphemeCluster(text, visibleOffset)) return refuse("Character deletion requires a caret at a grapheme boundary.", INVALID_REQUEST);
2961
+ if (direction === "backward" && visibleOffset === 0 || direction === "forward" && visibleOffset === text.length) return refuse("There is no visible character to delete in this paragraph.", INVALID_REQUEST);
2965
2962
  let boundary = visibleOffset + (direction === "backward" ? -1 : 1);
2966
2963
  while (splitsGraphemeCluster(text, boundary)) boundary += direction === "backward" ? -1 : 1;
2967
2964
  const from = physicalStarts.at(direction === "backward" ? boundary : visibleOffset);
@@ -2998,7 +2995,7 @@ const measuredDeletionRange = (state, measured) => {
2998
2995
  state.doc.nodesBetween(from, to, (node) => {
2999
2996
  if (node.type.name === "noteMarker") noteMarkers += 1;
3000
2997
  });
3001
- if (noteMarkers > 0) return refuse("Automatic note marks cannot be deleted as characters.");
2998
+ if (noteMarkers > 0) return refuse("Automatic note marks cannot be deleted as characters.", INVALID_REQUEST);
3002
2999
  return Result.ok({
3003
3000
  from,
3004
3001
  to