@stll/folio-core 0.74.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 (113) 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 +18 -9
  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 +6 -2
  11. package/dist/ai-edits/retired-comment-receipts.d.ts +2 -2
  12. package/dist/ai-edits/retired-comment-receipts.js +3 -18
  13. package/dist/ai-edits/tracked-batch-fidelity.d.ts +6 -10
  14. package/dist/ai-edits/tracked-batch-fidelity.js +3 -182
  15. package/dist/canonical/canonicalBatchReview.d.ts +4 -1
  16. package/dist/canonical/canonicalBatchReview.js +32 -14
  17. package/dist/canonical/canonicalComments.d.ts +6 -2
  18. package/dist/canonical/canonicalComments.js +8 -4
  19. package/dist/canonical/canonicalPublicOperations.js +29 -9
  20. package/dist/canonical/canonicalRefusalGrounds.d.ts +4 -0
  21. package/dist/canonical/canonicalRefusalGrounds.js +56 -0
  22. package/dist/canonical/canonicalSession.d.ts +12 -6
  23. package/dist/canonical/canonicalSession.js +116 -121
  24. package/dist/canonical/canonicalTrackedBatchFidelity.js +3 -3
  25. package/dist/compare/inline-atoms.d.ts +35 -41
  26. package/dist/compare/inline-atoms.js +2 -465
  27. package/dist/compare/section-boundary-properties.d.ts +3 -30
  28. package/dist/compare/section-boundary-properties.js +4 -72
  29. package/dist/controller/canonicalClipboard.js +43 -42
  30. package/dist/controller/canonicalComposition.d.ts +1 -1
  31. package/dist/controller/canonicalComposition.js +5 -5
  32. package/dist/controller/canonicalInput.d.ts +4 -2
  33. package/dist/controller/canonicalInput.js +33 -16
  34. package/dist/controller/canonicalStoryEditor.d.ts +2 -3
  35. package/dist/controller/canonicalStoryEditor.js +43 -25
  36. package/dist/controller/canonicalStructure.d.ts +19 -2
  37. package/dist/controller/canonicalStructure.js +139 -42
  38. package/dist/controller/deferredDisplayListPainter.d.ts +8 -0
  39. package/dist/controller/deferredDisplayListPainter.js +34 -0
  40. package/dist/controller/folioEditor.js +4 -2
  41. package/dist/controller/headerFooterEditorManager.js +3 -17
  42. package/dist/controller/hiddenEditorApi.d.ts +24 -3
  43. package/dist/controller/hiddenEditorApi.js +2 -0
  44. package/dist/controller/hiddenEditorManager.js +132 -189
  45. package/dist/controller/layoutPipeline.d.ts +4 -86
  46. package/dist/controller/layoutPipeline.js +8 -727
  47. package/dist/controller/layoutPipelineExecution.d.ts +94 -0
  48. package/dist/controller/layoutPipelineExecution.js +730 -0
  49. package/dist/controller/noteEditorManager.js +3 -16
  50. package/dist/docx/blockContentParser.d.ts +1 -3
  51. package/dist/docx/blockContentParser.js +3 -10
  52. package/dist/docx/canonicalSave.d.ts +4 -3
  53. package/dist/docx/canonicalSave.js +4 -3
  54. package/dist/docx/listMarkerComputation.d.ts +24 -17
  55. package/dist/docx/listMarkerComputation.js +31 -60
  56. package/dist/docx/listModelNormalization.js +8 -15
  57. package/dist/docx/rezip.d.ts +16 -3
  58. package/dist/docx/rezip.js +35 -9
  59. package/dist/docx/selectiveSave.js +13 -5
  60. package/dist/docx/server/templatePlan/apply.js +38 -3
  61. package/dist/docx/server/templatePlan/blocks.d.ts +16 -1
  62. package/dist/docx/server/templatePlan/blocks.js +93 -7
  63. package/dist/docx/server/templatePlan/builders.d.ts +37 -2
  64. package/dist/docx/server/templatePlan/builders.js +196 -5
  65. package/dist/docx/server/templatePlan/emit.d.ts +2 -0
  66. package/dist/docx/server/templatePlan/emit.js +2 -0
  67. package/dist/docx/server/templatePlan/inspect.js +19 -52
  68. package/dist/docx/server/templatePlan/labels.d.ts +7 -2
  69. package/dist/docx/server/templatePlan/labels.js +104 -22
  70. package/dist/docx/server/templatePlan/plan.d.ts +13 -1
  71. package/dist/docx/server/templatePlan/plan.js +22 -7
  72. package/dist/docx/server/templatePlan/planShape.js +31 -2
  73. package/dist/docx/server/templatePlan/story.d.ts +8 -0
  74. package/dist/docx/server/templatePlan/story.js +11 -1
  75. package/dist/docx/server/templatePlan/types.d.ts +138 -16
  76. package/dist/docx/server/templatePlan/verify.js +50 -9
  77. package/dist/i18n/messages/ar.gen.js +1 -0
  78. package/dist/i18n/messages/catalogs.gen.d.ts +17 -0
  79. package/dist/i18n/messages/catalogs.gen.js +17 -0
  80. package/dist/i18n/messages/cs.gen.js +1 -0
  81. package/dist/i18n/messages/de.gen.js +1 -0
  82. package/dist/i18n/messages/en.gen.js +1 -0
  83. package/dist/i18n/messages/es.gen.js +1 -0
  84. package/dist/i18n/messages/et.gen.js +1 -0
  85. package/dist/i18n/messages/fr.gen.js +1 -0
  86. package/dist/i18n/messages/he.gen.js +1 -0
  87. package/dist/i18n/messages/hi.gen.js +1 -0
  88. package/dist/i18n/messages/hu.gen.js +1 -0
  89. package/dist/i18n/messages/lt.gen.js +1 -0
  90. package/dist/i18n/messages/lv.gen.js +1 -0
  91. package/dist/i18n/messages/messages.gen.d.ts +1 -0
  92. package/dist/i18n/messages/pl.gen.js +1 -0
  93. package/dist/i18n/messages/pt-BR.gen.js +1 -0
  94. package/dist/i18n/messages/sk.gen.js +1 -0
  95. package/dist/i18n/messages/tr.gen.js +1 -0
  96. package/dist/i18n/messages/zh-CN.gen.js +1 -0
  97. package/dist/layout-bridge/convert/toFlowBlocks.js +0 -12
  98. package/dist/layout-bridge/convert/topLevelConversion.js +1 -10
  99. package/dist/prosemirror/extensions/features/ImagePasteExtension.js +1 -1
  100. package/dist/prosemirror/listMarker.d.ts +1 -6
  101. package/dist/prosemirror/listMarker.js +4 -56
  102. package/dist/server.d.ts +2 -2
  103. package/dist/types/canonicalCapabilities.d.ts +40 -45
  104. package/dist/types/canonicalCapabilities.js +51 -43
  105. package/dist/types/canonicalComments.d.ts +2 -2
  106. package/dist/types/canonicalSections.d.ts +2 -2
  107. package/dist/utils/clipboard.d.ts +2 -28
  108. package/dist/utils/clipboard.js +1 -96
  109. package/dist/utils/clipboardFiles.d.ts +27 -0
  110. package/dist/utils/clipboardFiles.js +98 -0
  111. package/dist/utils/rulerControl.d.ts +1 -0
  112. package/dist/utils/rulerControl.js +2 -1
  113. package/package.json +2 -2
@@ -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
  })
@@ -1056,19 +1043,19 @@ const projectionChangeOf = (projected, published) => {
1056
1043
  };
1057
1044
  /** The model publishes only after PM and every plugin accept its exact projection. */
1058
1045
  const publishCanonicalProjection = ({ state, commit, session }) => {
1059
- 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);
1060
1047
  const applied = Result.try({
1061
1048
  try: () => state.applyTransaction(commit.transaction),
1062
1049
  catch: (cause) => new CanonicalSessionError({
1063
- ground: { gap: CANONICAL_GAP.dispatch },
1050
+ ground: INTERNAL,
1064
1051
  reason: "refused",
1065
1052
  message: `Canonical plugin staging failed: ${cause instanceof Error ? cause.message : String(cause)}`
1066
1053
  })
1067
1054
  });
1068
1055
  if (applied.isErr()) return applied;
1069
1056
  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)}.`);
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);
1072
1059
  const published = commit.publish();
1073
1060
  if (published.isErr()) return published;
1074
1061
  return Result.ok(staged);
@@ -1241,7 +1228,7 @@ var CanonicalSession = class {
1241
1228
  * cleared.
1242
1229
  */
1243
1230
  compileReplacementPieces({ projection, pieces, start, end, intent }) {
1244
- const refused = (message) => refuseUnder({ gap: CANONICAL_GAP.commentReplacementAlignment }, message);
1231
+ const refused = (message) => refuse(message, { gap: CANONICAL_GAP.commentReplacementAlignment });
1245
1232
  const addressed = [];
1246
1233
  for (const [index, piece] of pieces.entries()) {
1247
1234
  const from = index === 0 ? Result.ok(start) : projection.inputAddressAt(piece.from, "afterMarkers");
@@ -1310,9 +1297,9 @@ var CanonicalSession = class {
1310
1297
  const fresh = this.freshBlockIds([1]);
1311
1298
  if (fresh.isErr()) return fresh;
1312
1299
  const id = fresh.value[0]?.[0];
1313
- 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);
1314
1301
  }
1315
- 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);
1316
1303
  return Result.ok(this.nextBlockId.toString(16).padStart(8, "0").toUpperCase());
1317
1304
  }
1318
1305
  /**
@@ -1330,11 +1317,11 @@ var CanonicalSession = class {
1330
1317
  count: total,
1331
1318
  taken: (id) => this.allocatedBlockIds.has(formatParaId(id))
1332
1319
  });
1333
- 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);
1334
1321
  ids.push(...leased.map(formatParaId));
1335
1322
  }
1336
1323
  for (let candidate = this.nextBlockId; ids.length < total; candidate += 1) {
1337
- 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);
1338
1325
  const id = candidate.toString(16).padStart(8, "0").toUpperCase();
1339
1326
  if (!this.allocatedBlockIds.has(id)) ids.push(id);
1340
1327
  }
@@ -1421,7 +1408,7 @@ var CanonicalSession = class {
1421
1408
  }
1422
1409
  get document() {
1423
1410
  if (this.isComposing) throw new CanonicalSessionError({
1424
- ground: { gap: CANONICAL_GAP.dispatch },
1411
+ ground: COMPOSING,
1425
1412
  reason: "refused",
1426
1413
  message: "Composition must finish before taking a snapshot."
1427
1414
  });
@@ -1442,7 +1429,7 @@ var CanonicalSession = class {
1442
1429
  }
1443
1430
  captureSaveSnapshot() {
1444
1431
  if (this.isComposing) throw new CanonicalSessionError({
1445
- ground: { gap: CANONICAL_GAP.saveSerialization },
1432
+ ground: { condition: CANONICAL_CONDITION.composing },
1446
1433
  reason: "refused",
1447
1434
  message: "Composition must finish before saving the canonical document."
1448
1435
  });
@@ -1590,7 +1577,7 @@ var CanonicalSession = class {
1590
1577
  const projected = this.projectStory(story);
1591
1578
  if (projected.isErr()) return projected;
1592
1579
  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.");
1580
+ if (state.doc !== projection.doc && !state.doc.eq(projection.doc)) return refuse("The story editor shows a stale canonical projection.", STALE);
1594
1581
  const selection = projection.selectionAt(state);
1595
1582
  if (selection.isErr()) {
1596
1583
  this.storySelections.delete(storyProjectionKey(story));
@@ -1620,14 +1607,14 @@ var CanonicalSession = class {
1620
1607
  * without a lease takes one.
1621
1608
  */
1622
1609
  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.");
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);
1625
1612
  this.leased = new CanonicalIdLease(lease, this.currentDocument);
1626
1613
  return Result.ok(void 0);
1627
1614
  }
1628
1615
  /** Add blocks the authority granted; ids this session already minted stay spent. */
1629
1616
  extendIdLease(lease) {
1630
- 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);
1631
1618
  this.leased.extend(lease);
1632
1619
  return Result.ok(void 0);
1633
1620
  }
@@ -1647,7 +1634,7 @@ var CanonicalSession = class {
1647
1634
  this.groupingBoundary += 1;
1648
1635
  }
1649
1636
  beginComposition() {
1650
- if (this.isComposing) return refuse("A canonical composition is already pending.");
1637
+ if (this.isComposing) return refuse("A canonical composition is already pending.", COMPOSING);
1651
1638
  this.lifecycle = { type: "composing" };
1652
1639
  this.breakUndoGroup();
1653
1640
  return Result.ok(void 0);
@@ -1657,8 +1644,8 @@ var CanonicalSession = class {
1657
1644
  this.breakUndoGroup();
1658
1645
  }
1659
1646
  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.");
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);
1662
1649
  return Result.ok(void 0);
1663
1650
  }
1664
1651
  prepareReplace(state, { from, to, text, story = OP_STORIES.MAIN, semantic = "replacement", compositionPhase, time = Date.now() }) {
@@ -1667,16 +1654,16 @@ var CanonicalSession = class {
1667
1654
  const projection = projected.value;
1668
1655
  const checked = this.checkState(state, projection);
1669
1656
  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.");
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);
1672
1659
  if (from === to && text.length === 0) return noChange("The input makes no text change.");
1673
1660
  const replacesStructuralSelection = state.selection instanceof AllSelection && from === state.selection.from && to === state.selection.to;
1674
1661
  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.");
1662
+ if (from !== state.selection.from || to !== state.selection.to) return refuse("A replacement range cannot partially address a cell selection.", INVALID_REQUEST);
1676
1663
  const ranges = canonicalCellSelectionRanges(state.selection);
1677
1664
  const firstRange = ranges.at(0);
1678
1665
  const lastRange = ranges.at(-1);
1679
- 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);
1680
1667
  const intents = [];
1681
1668
  const commentChanges = [];
1682
1669
  let first = true;
@@ -1708,7 +1695,7 @@ var CanonicalSession = class {
1708
1695
  },
1709
1696
  changes: commentChanges,
1710
1697
  removal: this.replacementRemoval()
1711
- })) 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 });
1712
1699
  return this.prepareIntents(state, {
1713
1700
  intents,
1714
1701
  semantic
@@ -1734,7 +1721,7 @@ var CanonicalSession = class {
1734
1721
  to: end.value,
1735
1722
  suggesting: this.mode.type === "suggesting" ? { author: this.mode.author } : void 0
1736
1723
  });
1737
- if (retirement.isErr()) return refuse(retirement.error.message);
1724
+ if (retirement.isErr()) return refuseOp(retirement.error);
1738
1725
  const removal = this.replacementRemoval();
1739
1726
  const whole = [{
1740
1727
  from: inputFrom,
@@ -1759,7 +1746,7 @@ var CanonicalSession = class {
1759
1746
  comments: removal.comments
1760
1747
  }) : void 0;
1761
1748
  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.");
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 });
1763
1750
  pieces = split.changes;
1764
1751
  }
1765
1752
  }
@@ -1786,7 +1773,7 @@ var CanonicalSession = class {
1786
1773
  });
1787
1774
  if (compiled.isErr()) {
1788
1775
  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);
1776
+ return compiled.error.reason === DOCUMENT_OP_REFUSAL_REASONS.NO_CHANGE ? noChange(compiled.error.message) : refuseOp(compiled.error);
1790
1777
  }
1791
1778
  const { ops, selection: caret } = compiled.value;
1792
1779
  const postSelection = {
@@ -1851,9 +1838,9 @@ var CanonicalSession = class {
1851
1838
  * the edit happens at the start of the first, as the editor's own command
1852
1839
  * does over a cell selection. One commit, so one undo step.
1853
1840
  */
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);
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);
1857
1844
  if (projected.isErr()) return projected;
1858
1845
  const projection = projected.value;
1859
1846
  const intents = [];
@@ -1872,7 +1859,7 @@ var CanonicalSession = class {
1872
1859
  text: ""
1873
1860
  });
1874
1861
  }
1875
- 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);
1876
1863
  intents.push(structure({
1877
1864
  ...first,
1878
1865
  offset: 0,
@@ -1891,7 +1878,7 @@ var CanonicalSession = class {
1891
1878
  const first = intents.at(0);
1892
1879
  if (first === void 0) return noChange("The intent batch is empty.");
1893
1880
  const story = intentStory(first);
1894
- 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);
1895
1882
  const projected = this.projectStory(story);
1896
1883
  if (projected.isErr()) return projected;
1897
1884
  const checked = this.checkState(state, projected.value);
@@ -1904,7 +1891,7 @@ var CanonicalSession = class {
1904
1891
  const edits = [];
1905
1892
  if (resourceOps.length > 0) {
1906
1893
  const imported = applyDocumentOps(document, resourceOps);
1907
- if (imported.isErr()) return refuse(imported.error.message);
1894
+ if (imported.isErr()) return refuseOp(imported.error);
1908
1895
  document = imported.value.document;
1909
1896
  edits.push(imported.value);
1910
1897
  }
@@ -2012,7 +1999,7 @@ var CanonicalSession = class {
2012
1999
  return true;
2013
2000
  },
2014
2001
  prepare: (state, postSelection) => {
2015
- 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);
2016
2003
  const combined = combineEdits(document, effects.map(({ inverse, touched }) => ({
2017
2004
  document,
2018
2005
  inverse,
@@ -2123,12 +2110,16 @@ var CanonicalSession = class {
2123
2110
  }
2124
2111
  });
2125
2112
  }
2126
- prepareSplit(state) {
2127
- 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);
2128
2119
  if (from.isErr()) return from;
2129
- const to = this.projection.inputAddressAt(state.selection.to);
2120
+ const to = projection.inputAddressAt(state.selection.to);
2130
2121
  if (to.isErr()) return to;
2131
- const source = this.projection.paragraph(from.value.blockId);
2122
+ const source = projection.paragraph(from.value.blockId);
2132
2123
  const nextStyle = (Object.hasOwn(this.currentDocument.package, "styles") ? this.currentDocument.package.styles : this.styles)?.styles.find(({ styleId }) => styleId === source?.source.formatting?.styleId)?.next;
2133
2124
  const fresh = this.freshBlockId();
2134
2125
  if (fresh.isErr()) return fresh;
@@ -2148,11 +2139,15 @@ var CanonicalSession = class {
2148
2139
  });
2149
2140
  return this.prepareIntents(state, { intents });
2150
2141
  }
2151
- prepareJoin(state, direction) {
2152
- 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);
2153
2148
  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);
2149
+ if (!state.selection.empty) return refuse("Join requires a collapsed text selection.", INVALID_REQUEST);
2150
+ const at = projection.inputAddressAt(state.selection.from);
2156
2151
  if (at.isErr()) return at;
2157
2152
  const groups = editorParagraphGroups(this.currentDocument, at.value.story);
2158
2153
  const index = groups.findIndex(({ paragraphs }) => paragraphs.some((paragraph) => paragraph.paraId === at.value.blockId));
@@ -2162,8 +2157,8 @@ var CanonicalSession = class {
2162
2157
  const first = firstGroup?.paragraphs.at(-1);
2163
2158
  const second = secondGroup?.paragraphs.at(0);
2164
2159
  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.");
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);
2167
2162
  return this.prepareIntent(state, {
2168
2163
  type: "joinParagraphs",
2169
2164
  story: at.value.story,
@@ -2195,7 +2190,7 @@ var CanonicalSession = class {
2195
2190
  const resolved = locks.unlocked.flat();
2196
2191
  const ops = [...before, ...resolved.length === 0 ? [] : resolve(resolved)];
2197
2192
  const applied = applyDocumentOps(this.currentDocument, ops);
2198
- if (applied.isErr()) return refuse(applied.error.message);
2193
+ if (applied.isErr()) return refuseOp(applied.error);
2199
2194
  const projected = project({
2200
2195
  document: applied.value.document,
2201
2196
  styles: this.styles,
@@ -2205,7 +2200,7 @@ var CanonicalSession = class {
2205
2200
  if (projected.isErr()) return projected;
2206
2201
  const surviving = projected.value.paragraph(preSelection.value.head.blockId);
2207
2202
  const first = projected.value.firstParagraph;
2208
- if (first === void 0) return refuse("Resolution left no paragraph.");
2203
+ if (first === void 0) return refuse("Resolution left no paragraph.", INTERNAL);
2209
2204
  let offset = surviving ? Math.min(preSelection.value.head.offset, surviving.text.length) : 0;
2210
2205
  if (surviving && splitsSurrogatePair(surviving.text, offset)) offset -= 1;
2211
2206
  const caret = {
@@ -2289,7 +2284,7 @@ var CanonicalSession = class {
2289
2284
  const body = findStoryBody(this.currentDocument, story);
2290
2285
  if (body === void 0) {
2291
2286
  this.storyProjections.delete(key);
2292
- return refuse("The canonical story no longer exists.");
2287
+ return refuse("The canonical story no longer exists.", STALE);
2293
2288
  }
2294
2289
  const cached = this.storyProjections.get(key);
2295
2290
  const { styles, theme } = this.currentDocument.package;
@@ -2310,7 +2305,7 @@ var CanonicalSession = class {
2310
2305
  return projected;
2311
2306
  }
2312
2307
  prepareOperations(state, ops) {
2313
- 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);
2314
2309
  const selected = this.projection.selectionAt(state);
2315
2310
  if (selected.isErr()) return selected;
2316
2311
  let preparedOps = ops;
@@ -2353,7 +2348,7 @@ var CanonicalSession = class {
2353
2348
  };
2354
2349
  if (ops.length > 1) {
2355
2350
  const applied = applyDocumentOp(cloneDocumentWithParagraphPropertySources(document), structuredClone(next));
2356
- if (applied.isErr()) return refuse(applied.error.message);
2351
+ if (applied.isErr()) return refuseOp(applied.error);
2357
2352
  document = applied.value.document;
2358
2353
  }
2359
2354
  tracked.push(next);
@@ -2422,7 +2417,7 @@ var CanonicalSession = class {
2422
2417
  if (stack === "undo") this.applied.length = 0;
2423
2418
  else this.undone.length = 0;
2424
2419
  this.reportHistoryDrop(dropped);
2425
- 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);
2426
2421
  }
2427
2422
  /** Called with every history drop a remote edit causes; returns the unsubscribe. */
2428
2423
  onHistoryDrop(listener) {
@@ -2463,7 +2458,7 @@ var CanonicalSession = class {
2463
2458
  const checked = this.checkState(state, projected.value);
2464
2459
  if (checked.isErr()) return checked;
2465
2460
  const applied = applyDocumentOps(this.currentDocument, change.batch.ops);
2466
- if (applied.isErr()) return refuse(applied.error.message);
2461
+ if (applied.isErr()) return refuseOp(applied.error);
2467
2462
  const shown = projected.value.selectionAt(state);
2468
2463
  const before = shown.isOk() ? shown.value : this.currentSelection;
2469
2464
  const selection = remoteSelection({
@@ -2570,7 +2565,7 @@ var CanonicalSession = class {
2570
2565
  }
2571
2566
  prepareUndo(state, story = OP_STORIES.MAIN) {
2572
2567
  const group = this.applied.at(-1);
2573
- 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);
2574
2569
  const ops = undoOpsOf(group);
2575
2570
  const rebased = this.rebasedStepApplies(group, ops, "undo");
2576
2571
  if (rebased.isErr()) return rebased;
@@ -2597,7 +2592,7 @@ var CanonicalSession = class {
2597
2592
  }
2598
2593
  prepareRedo(state, story = OP_STORIES.MAIN) {
2599
2594
  const undone = this.undone.at(-1);
2600
- 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);
2601
2596
  const rebased = this.rebasedStepApplies(undone.group, undone.redoOps, "redo");
2602
2597
  if (rebased.isErr()) return rebased;
2603
2598
  const propertySourceDocument = undone.group.rebased === true ? void 0 : undone.group.entries.at(-1)?.postDocument;
@@ -2632,7 +2627,7 @@ var CanonicalSession = class {
2632
2627
  const checked = this.checkState(state, previous.value);
2633
2628
  if (checked.isErr()) return checked;
2634
2629
  const applied = stagedApplied === void 0 ? applyDocumentOps(this.currentDocument, ops) : Result.ok(stagedApplied);
2635
- if (applied.isErr()) return refuse(applied.error.message);
2630
+ if (applied.isErr()) return refuseOp(applied.error);
2636
2631
  if (applied.value.inverse.length === 0) return noChange("The intent makes no document change.");
2637
2632
  const locked = admission === CANONICAL_ADMISSION.restage ? null : lockViolationBetween(this.currentDocument, applied.value.document);
2638
2633
  if (locked !== null) return lockRefusal(locked);
@@ -2645,7 +2640,7 @@ var CanonicalSession = class {
2645
2640
  applied.value.document = normalized.document;
2646
2641
  applied.value.inverse = inverseMeetingDocument(normalized.document, normalized.inverse.concat(applied.value.inverse));
2647
2642
  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.`);
2643
+ if (leaseJudgement?.type === "outside") return refuse(`The ${leaseJudgement.id.kind} id ${leaseJudgement.id.id} is outside this author's id lease.`, INVALID_REQUEST);
2649
2644
  const changed = changedStories({
2650
2645
  document: applied.value.document,
2651
2646
  previous: this.currentDocument
@@ -2747,7 +2742,7 @@ var CanonicalSession = class {
2747
2742
  type: "near",
2748
2743
  anchor: state.selection.anchor
2749
2744
  }
2750
- })) return refuse("Canonical history cannot restore the selected inline atom.");
2745
+ })) return refuse("Canonical history cannot restore the selected inline atom.", INTERNAL);
2751
2746
  }
2752
2747
  const shown = (sameStory(selection.anchor.story, projectedStory) && sameStory(selection.head.story, projectedStory) ? placeShownSelection(transaction, projected.value) : void 0) ?? selection;
2753
2748
  const held = projected.value.heldAs(transaction.doc);
@@ -2777,9 +2772,9 @@ var CanonicalSession = class {
2777
2772
  origin,
2778
2773
  history,
2779
2774
  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.");
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);
2783
2778
  for (const blockId of applied.value.touched.inserted) this.allocatedBlockIds.add(blockId.toUpperCase());
2784
2779
  for (const op of ops) {
2785
2780
  if (op.type === DOCUMENT_OP_TYPES.SPLIT_BLOCK) this.allocatedBlockIds.add(op.newBlockId.toUpperCase());
@@ -2839,13 +2834,13 @@ const createCanonicalSession = (document, styles, { idLease, newOpId } = {}) =>
2839
2834
  const owned = cloneDocumentWithParagraphPropertySources(document);
2840
2835
  const source = normalizeCanonicalSource(owned);
2841
2836
  const unsupported = unsupportedSeedReason(source.document);
2842
- if (unsupported !== null) return refuse(unsupported);
2837
+ if (unsupported !== null) return refuse(unsupported, { gap: CANONICAL_GAP.storyContentProjection });
2843
2838
  const identified = preservePropertySourcesWholeStories({
2844
2839
  target: normalizeForOps(source.document),
2845
2840
  source: owned
2846
2841
  });
2847
2842
  const validated = validateOpsDocument(identified);
2848
- if (validated.isErr()) return refuse(validated.error.message);
2843
+ if (validated.isErr()) return refuseOp(validated.error);
2849
2844
  const caches = newStoryProjectionCaches();
2850
2845
  const normalized = preservePropertySourcesWholeStories({
2851
2846
  target: normalizeCanonicalListRendering(identified, caches.lists).document,
@@ -2876,7 +2871,7 @@ const visibleDeletionContext = (state) => {
2876
2871
  const { selection } = state;
2877
2872
  const paragraphDepth = selection.$from.depth;
2878
2873
  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.");
2874
+ if (containerDepth < 0 || selection.$from.node(paragraphDepth).type.name !== "paragraph") return refuse("Canonical deletion requires a caret inside a paragraph.", INVALID_REQUEST);
2880
2875
  const container = selection.$from.node(containerDepth);
2881
2876
  const containerStart = selection.$from.start(containerDepth);
2882
2877
  const index = selection.$from.index(containerDepth);
@@ -2894,7 +2889,7 @@ const visibleDeletionContext = (state) => {
2894
2889
  const native = canonicalNativeCells(paragraph);
2895
2890
  if (native.isErr()) {
2896
2891
  issue = new CanonicalSessionError({
2897
- ground: { gap: CANONICAL_GAP.dispatch },
2892
+ ground: { gap: CANONICAL_GAP.storyContentProjection },
2898
2893
  reason: "refused",
2899
2894
  message: native.error.message
2900
2895
  });
@@ -2907,7 +2902,7 @@ const visibleDeletionContext = (state) => {
2907
2902
  const to = containerStart + paragraphOffset + 1 + cell.to;
2908
2903
  if (cell.type !== "text" && selection.from > from && selection.from < to) {
2909
2904
  issue = new CanonicalSessionError({
2910
- ground: { gap: CANONICAL_GAP.dispatch },
2905
+ ground: INVALID_REQUEST,
2911
2906
  reason: "refused",
2912
2907
  message: "Character deletion cannot start inside an inline atom."
2913
2908
  });
@@ -2948,20 +2943,20 @@ const deletionRange = (state, direction) => {
2948
2943
  to: selection.to
2949
2944
  });
2950
2945
  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.");
2946
+ if (!(selection instanceof TextSelection)) return refuse("Canonical deletion requires text, an inline atom, or the whole document selection.", INVALID_REQUEST);
2952
2947
  if (!selection.empty) return Result.ok({
2953
2948
  from: selection.from,
2954
2949
  to: selection.to
2955
2950
  });
2956
2951
  const parent = selection.$from.parent;
2957
2952
  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.");
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);
2959
2954
  const context = visibleDeletionContext(state);
2960
2955
  if (context.isErr()) return context;
2961
2956
  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.");
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);
2965
2960
  let boundary = visibleOffset + (direction === "backward" ? -1 : 1);
2966
2961
  while (splitsGraphemeCluster(text, boundary)) boundary += direction === "backward" ? -1 : 1;
2967
2962
  const from = physicalStarts.at(direction === "backward" ? boundary : visibleOffset);
@@ -2998,7 +2993,7 @@ const measuredDeletionRange = (state, measured) => {
2998
2993
  state.doc.nodesBetween(from, to, (node) => {
2999
2994
  if (node.type.name === "noteMarker") noteMarkers += 1;
3000
2995
  });
3001
- 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);
3002
2997
  return Result.ok({
3003
2998
  from,
3004
2999
  to