@stll/folio-core 0.68.0 → 0.70.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 (1134) hide show
  1. package/dist/_virtual/_rolldown/runtime.js +4 -4
  2. package/dist/ai-edits/apply.d.ts +39 -16
  3. package/dist/ai-edits/apply.js +1014 -723
  4. package/dist/ai-edits/block-identity.d.ts +6 -0
  5. package/dist/ai-edits/block-identity.js +11 -1
  6. package/dist/ai-edits/blockRange.d.ts +9 -0
  7. package/dist/ai-edits/clean-text.d.ts +2 -0
  8. package/dist/ai-edits/clean-text.js +2 -1
  9. package/dist/ai-edits/comment-lifecycle.d.ts +24 -0
  10. package/dist/ai-edits/comment-lifecycle.js +17 -8
  11. package/dist/ai-edits/directJoin.d.ts +30 -0
  12. package/dist/ai-edits/directJoin.js +30 -0
  13. package/dist/ai-edits/existingRevisions.d.ts +9 -0
  14. package/dist/ai-edits/existingRevisions.js +30 -0
  15. package/dist/ai-edits/finalSectionReview.d.ts +11 -0
  16. package/dist/ai-edits/finalSectionReview.js +26 -0
  17. package/dist/ai-edits/headless.d.ts +275 -14
  18. package/dist/ai-edits/headless.js +1597 -195
  19. package/dist/ai-edits/index.d.ts +11 -10
  20. package/dist/ai-edits/index.js +2 -2
  21. package/dist/ai-edits/markdownInsertion.d.ts +25 -0
  22. package/dist/ai-edits/markdownInsertion.js +67 -0
  23. package/dist/ai-edits/minimal-replacement.d.ts +120 -1
  24. package/dist/ai-edits/minimal-replacement.js +81 -1
  25. package/dist/ai-edits/newListNumbering.d.ts +31 -7
  26. package/dist/ai-edits/newListNumbering.js +46 -8
  27. package/dist/ai-edits/note-references.d.ts +19 -1
  28. package/dist/ai-edits/note-references.js +3 -1
  29. package/dist/ai-edits/pending-suggestions.d.ts +44 -2
  30. package/dist/ai-edits/pending-suggestions.js +483 -22
  31. package/dist/ai-edits/pendingJoin.d.ts +170 -0
  32. package/dist/ai-edits/pendingJoin.js +272 -0
  33. package/dist/ai-edits/read.d.ts +57 -4
  34. package/dist/ai-edits/read.js +317 -40
  35. package/dist/ai-edits/removed-blocks.d.ts +1 -1
  36. package/dist/ai-edits/result-validation.d.ts +36 -1
  37. package/dist/ai-edits/result-validation.js +1 -1
  38. package/dist/ai-edits/retired-comment-receipts.d.ts +20 -0
  39. package/dist/ai-edits/retired-comment-receipts.js +165 -0
  40. package/dist/ai-edits/revisionStretches.d.ts +17 -0
  41. package/dist/ai-edits/snapshot.d.ts +12 -3
  42. package/dist/ai-edits/snapshot.js +9 -7
  43. package/dist/ai-edits/snapshotBatchFacts.d.ts +52 -0
  44. package/dist/ai-edits/snapshotBatchFacts.js +184 -0
  45. package/dist/ai-edits/table-geometry.d.ts +45 -11
  46. package/dist/ai-edits/table-geometry.js +141 -26
  47. package/dist/ai-edits/table-mutation-plan.d.ts +12 -0
  48. package/dist/ai-edits/table-mutation-plan.js +1 -1
  49. package/dist/ai-edits/table-row-column-mutations.d.ts +26 -3
  50. package/dist/ai-edits/table-row-column-mutations.js +90 -11
  51. package/dist/ai-edits/table-template.d.ts +21 -0
  52. package/dist/ai-edits/tableInsertionModes.d.ts +10 -0
  53. package/dist/ai-edits/tableInsertionModes.js +8 -0
  54. package/dist/ai-edits/tracked-batch-fidelity.d.ts +23 -0
  55. package/dist/ai-edits/tracked-batch-fidelity.js +357 -0
  56. package/dist/ai-edits/types.d.ts +81 -15
  57. package/dist/ai-edits/undefinedReferences.d.ts +49 -0
  58. package/dist/ai-edits/undefinedReferences.js +234 -0
  59. package/dist/ai-suggestions/apply.d.ts +12 -0
  60. package/dist/ai-suggestions/conflict.d.ts +9 -0
  61. package/dist/ai-suggestions/text-positions.d.ts +13 -0
  62. package/dist/canonical/batchCommentReferences.d.ts +20 -0
  63. package/dist/canonical/batchCommentReferences.js +93 -0
  64. package/dist/canonical/canonicalBatchReview.d.ts +25 -0
  65. package/dist/canonical/canonicalBatchReview.js +132 -0
  66. package/dist/{controller → canonical}/canonicalComments.d.ts +7 -4
  67. package/dist/{controller → canonical}/canonicalComments.js +36 -9
  68. package/dist/canonical/canonicalCompilerRefusal.d.ts +13 -0
  69. package/dist/canonical/canonicalCompilerRefusal.js +75 -0
  70. package/dist/canonical/canonicalIdLease.d.ts +40 -0
  71. package/dist/canonical/canonicalIdLease.js +96 -0
  72. package/dist/{controller → canonical}/canonicalInlineProjection.d.ts +1 -1
  73. package/dist/{controller → canonical}/canonicalInlineProjection.js +40 -20
  74. package/dist/canonical/canonicalInsertedCommentRange.d.ts +15 -0
  75. package/dist/canonical/canonicalInsertedCommentRange.js +43 -0
  76. package/dist/canonical/canonicalInsertionReplayIds.d.ts +40 -0
  77. package/dist/canonical/canonicalInsertionReplayIds.js +73 -0
  78. package/dist/canonical/canonicalJoinedReceipts.d.ts +11 -0
  79. package/dist/canonical/canonicalJoinedReceipts.js +22 -0
  80. package/dist/{controller → canonical}/canonicalListRendering.js +1 -1
  81. package/dist/canonical/canonicalLockGuard.d.ts +34 -0
  82. package/dist/canonical/canonicalLockGuard.js +208 -0
  83. package/dist/{controller → canonical}/canonicalOperations.js +1 -1
  84. package/dist/canonical/canonicalProjectionBlocks.d.ts +89 -0
  85. package/dist/canonical/canonicalProjectionBlocks.js +79 -0
  86. package/dist/{controller → canonical}/canonicalPublicOperations.d.ts +24 -9
  87. package/dist/canonical/canonicalPublicOperations.js +4791 -0
  88. package/dist/canonical/canonicalRemoteHistory.d.ts +48 -0
  89. package/dist/canonical/canonicalRemoteHistory.js +176 -0
  90. package/dist/canonical/canonicalRevisionLocks.d.ts +18 -0
  91. package/dist/canonical/canonicalRevisionLocks.js +30 -0
  92. package/dist/canonical/canonicalRevisionReceipts.d.ts +15 -0
  93. package/dist/canonical/canonicalRevisionReceipts.js +25 -0
  94. package/dist/canonical/canonicalRoomBase.d.ts +23 -0
  95. package/dist/canonical/canonicalRoomBase.js +38 -0
  96. package/dist/canonical/canonicalSeedContent.d.ts +36 -0
  97. package/dist/canonical/canonicalSeedContent.js +179 -0
  98. package/dist/{controller → canonical}/canonicalSelection.js +1 -1
  99. package/dist/canonical/canonicalSession.d.ts +515 -0
  100. package/dist/canonical/canonicalSession.js +2892 -0
  101. package/dist/canonical/canonicalSourceNormalization.d.ts +42 -0
  102. package/dist/canonical/canonicalSourceNormalization.js +166 -0
  103. package/dist/{controller → canonical}/canonicalTocSelection.js +1 -1
  104. package/dist/canonical/canonicalTrackedBatchFidelity.d.ts +9 -0
  105. package/dist/canonical/canonicalTrackedBatchFidelity.js +125 -0
  106. package/dist/canonical/canonicalWholeTextFidelity.d.ts +21 -0
  107. package/dist/canonical/canonicalWholeTextFidelity.js +88 -0
  108. package/dist/canonical/commentAnchorParagraph.d.ts +10 -0
  109. package/dist/canonical/commentAnchorParagraph.js +11 -0
  110. package/dist/canonical/controlEdges.d.ts +12 -0
  111. package/dist/canonical/controlEdges.js +17 -0
  112. package/dist/canonical/paragraphPatchAsRead.d.ts +19 -0
  113. package/dist/canonical/paragraphPatchAsRead.js +32 -0
  114. package/dist/canonical/propertySourcePreservation.d.ts +38 -0
  115. package/dist/canonical/propertySourcePreservation.js +129 -0
  116. package/dist/canonical/replacementRunSources.d.ts +29 -0
  117. package/dist/canonical/replacementRunSources.js +78 -0
  118. package/dist/compare/compare.d.ts +8 -6
  119. package/dist/compare/compare.js +37 -8
  120. package/dist/compare/content-alignment.d.ts +10 -1
  121. package/dist/compare/content-alignment.js +188 -27
  122. package/dist/compare/content.d.ts +9 -1
  123. package/dist/compare/content.js +2 -2
  124. package/dist/compare/formatting.d.ts +1 -0
  125. package/dist/compare/import-style-closure.d.ts +1 -1
  126. package/dist/compare/inline-atom-alignment.d.ts +83 -0
  127. package/dist/compare/inline-atom-alignment.js +173 -0
  128. package/dist/compare/inline-atoms-model.d.ts +65 -0
  129. package/dist/compare/inline-atoms-model.js +1131 -0
  130. package/dist/compare/inline-atoms.d.ts +4 -4
  131. package/dist/compare/inline-atoms.js +28 -139
  132. package/dist/compare/inline-provenance-model.d.ts +37 -0
  133. package/dist/compare/inline-provenance-model.js +138 -0
  134. package/dist/compare/inline-provenance.d.ts +52 -4
  135. package/dist/compare/inline-provenance.js +40 -7
  136. package/dist/compare/plan.d.ts +38 -4
  137. package/dist/compare/plan.js +22 -8
  138. package/dist/compare/scenario.d.ts +22 -1
  139. package/dist/compare/section-boundary-properties.d.ts +38 -5
  140. package/dist/compare/section-boundary-properties.js +164 -48
  141. package/dist/compare/style-resources.d.ts +3 -2
  142. package/dist/compare/style-resources.js +5 -4
  143. package/dist/compare/types.d.ts +5 -2
  144. package/dist/compare/verification.d.ts +24 -3
  145. package/dist/compare/verification.js +25 -18
  146. package/dist/compat/eigenpal.d.ts +32 -31
  147. package/dist/compat/eigenpal.js +3 -5
  148. package/dist/content-controls/findContentControls.d.ts +9 -0
  149. package/dist/content-controls/index.d.ts +8 -0
  150. package/dist/content-controls/mutateContentControls.d.ts +9 -0
  151. package/dist/controller/activeEditorStory.d.ts +1 -0
  152. package/dist/controller/anonymizationHighlights.d.ts +56 -0
  153. package/dist/controller/anonymizationHighlights.js +148 -0
  154. package/dist/controller/autocompleteSuggestion.d.ts +85 -0
  155. package/dist/controller/autocompleteSuggestion.js +213 -0
  156. package/dist/controller/canonicalClipboard.d.ts +2 -2
  157. package/dist/controller/canonicalClipboard.js +36 -16
  158. package/dist/controller/canonicalClipboardResources.js +9 -4
  159. package/dist/controller/canonicalCollaboration.d.ts +147 -0
  160. package/dist/controller/canonicalCollaboration.js +360 -0
  161. package/dist/controller/canonicalComposition.d.ts +7 -1
  162. package/dist/controller/canonicalComposition.js +48 -13
  163. package/dist/controller/canonicalContentControlValue.d.ts +17 -0
  164. package/dist/controller/canonicalContentControlValue.js +72 -0
  165. package/dist/controller/canonicalIndexedDbJournal.d.ts +6 -0
  166. package/dist/controller/canonicalIndexedDbJournal.js +80 -0
  167. package/dist/controller/canonicalInput.d.ts +13 -2
  168. package/dist/controller/canonicalInput.js +100 -17
  169. package/dist/controller/canonicalPresence.d.ts +63 -0
  170. package/dist/controller/canonicalPresence.js +125 -0
  171. package/dist/controller/canonicalReview.d.ts +1 -1
  172. package/dist/controller/canonicalReview.js +1 -1
  173. package/dist/controller/canonicalRoomAuthority.d.ts +66 -0
  174. package/dist/controller/canonicalRoomAuthority.js +119 -0
  175. package/dist/controller/canonicalRoomEditor.d.ts +87 -0
  176. package/dist/controller/canonicalRoomEditor.js +98 -0
  177. package/dist/controller/canonicalRoomTransport.d.ts +79 -0
  178. package/dist/controller/canonicalRoomTransport.js +104 -0
  179. package/dist/controller/canonicalRoomWire.d.ts +80 -0
  180. package/dist/controller/canonicalRoomWire.js +155 -0
  181. package/dist/controller/canonicalStoryEditor.d.ts +13 -1
  182. package/dist/controller/canonicalStoryEditor.js +55 -19
  183. package/dist/controller/canonicalStructure.d.ts +15 -5
  184. package/dist/controller/canonicalStructure.js +95 -34
  185. package/dist/controller/canonicalTabRoom.d.ts +91 -0
  186. package/dist/controller/canonicalTabRoom.js +553 -0
  187. package/dist/controller/canonicalYjsRoom.d.ts +102 -0
  188. package/dist/controller/canonicalYjsRoom.js +454 -0
  189. package/dist/controller/contentControlWidgetController.d.ts +16 -0
  190. package/dist/controller/contentControlWidgetController.js +7 -1
  191. package/dist/controller/documentChangeNotification.d.ts +5 -0
  192. package/dist/controller/documentChangeNotification.js +7 -0
  193. package/dist/controller/folioEditor.d.ts +12 -4
  194. package/dist/controller/folioEditor.js +21 -1
  195. package/dist/controller/folioEditorEvents.d.ts +1 -1
  196. package/dist/controller/fontReadiness.d.ts +14 -1
  197. package/dist/controller/fontReadiness.js +4 -4
  198. package/dist/controller/headerFooterEditorManager.d.ts +17 -6
  199. package/dist/controller/headerFooterEditorManager.js +29 -25
  200. package/dist/controller/hiddenEditorApi.d.ts +97 -14
  201. package/dist/controller/hiddenEditorApi.js +44 -3
  202. package/dist/controller/hiddenEditorManager.d.ts +68 -16
  203. package/dist/controller/hiddenEditorManager.js +440 -85
  204. package/dist/controller/hyphenationReadiness.d.ts +10 -0
  205. package/dist/controller/layoutPipeline.d.ts +14 -12
  206. package/dist/controller/layoutPipeline.js +66 -54
  207. package/dist/controller/layoutSession.d.ts +10 -6
  208. package/dist/controller/layoutSession.js +3 -1
  209. package/dist/controller/legacyTextAddress.d.ts +9 -0
  210. package/dist/controller/legacyTextAddress.js +52 -0
  211. package/dist/controller/noteEditorManager.d.ts +18 -6
  212. package/dist/controller/noteEditorManager.js +38 -32
  213. package/dist/controller/textPositionLookup.d.ts +24 -0
  214. package/dist/controller/textPositionLookup.js +78 -0
  215. package/dist/display-list/build/buildContext.d.ts +11 -0
  216. package/dist/display-list/build/buildDisplayList.d.ts +14 -1
  217. package/dist/display-list/build/colors.d.ts +8 -0
  218. package/dist/display-list/build/floatingImages.d.ts +10 -0
  219. package/dist/display-list/build/fontTable.d.ts +8 -0
  220. package/dist/display-list/build/furniture.d.ts +14 -2
  221. package/dist/display-list/build/glyphs.d.ts +7 -0
  222. package/dist/display-list/build/headerFooterPrimitives.d.ts +13 -0
  223. package/dist/display-list/build/imagePrimitives.d.ts +10 -0
  224. package/dist/display-list/build/pageBorderPrimitives.d.ts +16 -2
  225. package/dist/display-list/build/pageFurniture.d.ts +13 -0
  226. package/dist/display-list/build/paragraphPrimitives.d.ts +18 -0
  227. package/dist/display-list/build/paragraphPrimitives.js +17 -5
  228. package/dist/display-list/build/previewPrimitives.d.ts +14 -0
  229. package/dist/display-list/build/regions.d.ts +14 -0
  230. package/dist/display-list/build/storyPrimitives.d.ts +16 -0
  231. package/dist/display-list/build/strokes.d.ts +21 -3
  232. package/dist/display-list/build/strokes.js +2 -3
  233. package/dist/display-list/build/tablePrimitives.d.ts +15 -1
  234. package/dist/display-list/build/tablePrimitives.js +92 -55
  235. package/dist/display-list/build/textBoxPrimitives.d.ts +6 -0
  236. package/dist/display-list/build/unsupported.d.ts +10 -0
  237. package/dist/display-list/build/watermarkPrimitives.d.ts +15 -1
  238. package/dist/display-list/dom/renderDisplayListToDom.d.ts +33 -0
  239. package/dist/display-list/dom/renderDisplayListToDom.js +21 -11
  240. package/dist/display-list/editor/displayListPagePainter.d.ts +29 -1
  241. package/dist/display-list/editor/pageRenderer.d.ts +7 -0
  242. package/dist/display-list/html/renderDisplayListToHtml.d.ts +10 -0
  243. package/dist/display-list/primitives.d.ts +12 -1
  244. package/dist/display-list/selectDisplayPages.d.ts +8 -0
  245. package/dist/display-list/types.d.ts +11 -0
  246. package/dist/document-operations.d.ts +34 -4
  247. package/dist/document-operations.js +178 -40
  248. package/dist/docx/attributeRemainder.d.ts +35 -1
  249. package/dist/docx/automaticNoteMarkImport.d.ts +12 -0
  250. package/dist/docx/automaticNoteMarkImport.js +41 -0
  251. package/dist/docx/blockContentParser.d.ts +14 -5
  252. package/dist/docx/blockContentParser.js +19 -0
  253. package/dist/docx/blockPlainText.d.ts +14 -0
  254. package/dist/docx/blockPlainText.js +55 -4
  255. package/dist/docx/bookmarkParser.d.ts +17 -0
  256. package/dist/docx/bookmarkRangeJoin.d.ts +14 -0
  257. package/dist/docx/borderParser.d.ts +11 -0
  258. package/dist/docx/builtInStyles.d.ts +44 -1
  259. package/dist/docx/canonicalSave.d.ts +14 -4
  260. package/dist/docx/canonicalSave.js +133 -30
  261. package/dist/docx/canonicalSessionInput.d.ts +59 -4
  262. package/dist/docx/canonicalSessionInput.js +147 -6
  263. package/dist/docx/canonicalStoryRepack.d.ts +1 -0
  264. package/dist/docx/canonicalStoryRepack.js +2 -2
  265. package/dist/docx/chartPreview.js +10 -9
  266. package/dist/docx/commentAnchorIndex.d.ts +46 -1
  267. package/dist/docx/commentAnchorIndex.js +187 -7
  268. package/dist/docx/commentIdNormalization.d.ts +14 -0
  269. package/dist/docx/commentParagraphIds.d.ts +17 -0
  270. package/dist/docx/commentParagraphIds.js +79 -0
  271. package/dist/docx/commentParser.d.ts +20 -1
  272. package/dist/docx/commentParser.js +5 -0
  273. package/dist/docx/commentRangeIntegrity.js +27 -11
  274. package/dist/docx/commentRangeJoin.d.ts +21 -1
  275. package/dist/docx/commentRangeJoin.js +5 -1
  276. package/dist/docx/commentReferenceCompletion.d.ts +29 -2
  277. package/dist/docx/commentReferenceCompletion.js +4 -3
  278. package/dist/docx/commentReferenceNormalization.d.ts +17 -0
  279. package/dist/docx/commentReferenceNormalization.js +484 -49
  280. package/dist/docx/commentReplyMarkers.d.ts +22 -0
  281. package/dist/docx/compatibility.d.ts +10 -0
  282. package/dist/docx/containerChildren.d.ts +26 -1
  283. package/dist/docx/containerChildren.js +29 -3
  284. package/dist/docx/contentTypeRegistry.d.ts +16 -0
  285. package/dist/docx/contentTypeRegistry.js +49 -21
  286. package/dist/docx/danglingRelationshipReferences.d.ts +13 -0
  287. package/dist/docx/defaultParagraphStyle.d.ts +14 -1
  288. package/dist/docx/documentClone.d.ts +3 -2
  289. package/dist/docx/documentClone.js +1 -1
  290. package/dist/docx/documentParser.d.ts +28 -3
  291. package/dist/docx/documentParser.js +71 -4
  292. package/dist/docx/drawingAnchor.d.ts +17 -0
  293. package/dist/docx/drawingGroupChildren.d.ts +12 -0
  294. package/dist/docx/drawingIdNormalization.d.ts +8 -0
  295. package/dist/docx/drawingIdNormalization.js +46 -1
  296. package/dist/docx/drawingUtils.d.ts +6 -0
  297. package/dist/docx/drawingUtils.js +2 -2
  298. package/dist/docx/encryption/agileDecryption.d.ts +7 -0
  299. package/dist/docx/ensureParaIds.d.ts +73 -0
  300. package/dist/docx/ensureParaIds.js +299 -59
  301. package/dist/docx/ensureUniqueControlIds.js +10 -3
  302. package/dist/docx/ensureUniqueRevisionIds.d.ts +28 -0
  303. package/dist/docx/ensureUniqueRevisionIds.js +140 -0
  304. package/dist/docx/fieldParser.d.ts +27 -2
  305. package/dist/docx/fieldState.d.ts +15 -0
  306. package/dist/docx/fieldWrapperCaptures.d.ts +18 -0
  307. package/dist/docx/fieldWrapperCaptures.js +117 -0
  308. package/dist/docx/foldedListNumberFields.d.ts +14 -0
  309. package/dist/docx/fontTableParser.d.ts +11 -0
  310. package/dist/docx/footnoteParser.d.ts +24 -3
  311. package/dist/docx/footnoteParser.js +29 -6
  312. package/dist/docx/graphicFrameLocks.d.ts +9 -1
  313. package/dist/docx/groupDrawingParser.d.ts +2 -2
  314. package/dist/docx/headerFooterParser.d.ts +37 -5
  315. package/dist/docx/headerFooterParser.js +18 -4
  316. package/dist/docx/headerFooterRefParser.d.ts +7 -0
  317. package/dist/docx/hostCommentThreads.d.ts +21 -2
  318. package/dist/docx/hostCommentThreads.js +25 -2
  319. package/dist/docx/hyperlinkParser.d.ts +20 -3
  320. package/dist/docx/hyperlinkParser.js +19 -24
  321. package/dist/docx/imageParser.d.ts +27 -0
  322. package/dist/docx/index.d.ts +3 -3
  323. package/dist/docx/inlineContentRemovals.d.ts +8 -0
  324. package/dist/docx/inlineWrapperContent.d.ts +33 -1
  325. package/dist/docx/inlineWrapperContent.js +145 -1
  326. package/dist/docx/inlineWrapperParser.d.ts +14 -0
  327. package/dist/docx/listMarkerComputation.d.ts +37 -6
  328. package/dist/docx/listMarkerComputation.js +77 -28
  329. package/dist/docx/listModelNormalization.d.ts +24 -8
  330. package/dist/docx/listModelNormalization.js +426 -143
  331. package/dist/docx/listNumberingInstances.d.ts +39 -9
  332. package/dist/docx/listNumberingInstances.js +91 -44
  333. package/dist/docx/mainDocumentPart.d.ts +22 -1
  334. package/dist/docx/mainDocumentPart.js +51 -12
  335. package/dist/docx/markupRangeMarker.d.ts +16 -0
  336. package/dist/docx/markupRangeMarker.js +11 -2
  337. package/dist/docx/mathToMathml.d.ts +28 -0
  338. package/dist/docx/mergePropertyChangeLinks.d.ts +11 -0
  339. package/dist/docx/mergePropertyChangeLinks.js +30 -0
  340. package/dist/docx/nonVisualDrawingProps.d.ts +6 -0
  341. package/dist/docx/normalizeBaseDirection.d.ts +17 -0
  342. package/dist/docx/normalizedSourceParts.d.ts +21 -0
  343. package/dist/docx/normalizedSourceParts.js +81 -0
  344. package/dist/docx/notePropertiesParser.d.ts +7 -0
  345. package/dist/docx/noteReferenceMark.d.ts +9 -0
  346. package/dist/docx/noteReferenceStyles.d.ts +13 -0
  347. package/dist/docx/numberingIds.d.ts +6 -0
  348. package/dist/docx/numberingIds.js +6 -1
  349. package/dist/docx/numberingParser.d.ts +12 -0
  350. package/dist/docx/numberingReference.d.ts +10 -0
  351. package/dist/docx/numberingReferenceNormalization.d.ts +19 -0
  352. package/dist/docx/numberingReferenceNormalization.js +12 -2
  353. package/dist/docx/packageRelationshipsRoot.d.ts +24 -0
  354. package/dist/docx/packageRelationshipsRoot.js +28 -0
  355. package/dist/docx/packageUnnamedParagraphIds.d.ts +18 -0
  356. package/dist/docx/packageUnnamedParagraphIds.js +78 -0
  357. package/dist/docx/paraIdAttribute.d.ts +15 -0
  358. package/dist/docx/paragraphParser.d.ts +15 -3
  359. package/dist/docx/paragraphParser.js +126 -140
  360. package/dist/docx/paragraphProperties.d.ts +15 -1
  361. package/dist/docx/paragraphProperties.js +3 -5
  362. package/dist/docx/paragraphPropertySource.d.ts +60 -4
  363. package/dist/docx/paragraphPropertySource.js +239 -27
  364. package/dist/docx/paragraphTextBoxEnrichment.d.ts +3 -2
  365. package/dist/docx/paragraphTraversal.d.ts +39 -4
  366. package/dist/docx/paragraphTraversal.js +158 -42
  367. package/dist/docx/parseContext.d.ts +15 -0
  368. package/dist/docx/parseWarningMessage.d.ts +9 -0
  369. package/dist/docx/parseWarningMessage.js +7 -0
  370. package/dist/docx/parser.d.ts +1 -1
  371. package/dist/docx/parser.js +105 -29
  372. package/dist/docx/parserEnums.d.ts +21 -0
  373. package/dist/docx/partRelationships.d.ts +15 -0
  374. package/dist/docx/partRelationships.js +58 -0
  375. package/dist/docx/preservedRunContent.d.ts +2 -1
  376. package/dist/docx/preservedRunContent.js +40 -1
  377. package/dist/docx/previewBudget.d.ts +31 -0
  378. package/dist/docx/relsParser.d.ts +23 -0
  379. package/dist/docx/removeHeaderFooterParts.d.ts +1 -1
  380. package/dist/docx/removeHeaderFooterParts.js +1 -1
  381. package/dist/docx/replyToComment.d.ts +22 -1
  382. package/dist/docx/replyToComment.js +25 -21
  383. package/dist/docx/reviewResolutionProvenance.d.ts +32 -5
  384. package/dist/docx/reviewResolutionProvenance.js +284 -40
  385. package/dist/docx/rezip.d.ts +58 -11
  386. package/dist/docx/rezip.js +367 -101
  387. package/dist/docx/runConsolidator.d.ts +13 -0
  388. package/dist/docx/runParser.d.ts +4 -3
  389. package/dist/docx/runParser.js +27 -6
  390. package/dist/docx/runPayload.d.ts +29 -0
  391. package/dist/docx/saveDiagnostics.d.ts +3 -5
  392. package/dist/docx/sdtProperties.d.ts +17 -0
  393. package/dist/docx/sdtPropertiesPatch.d.ts +14 -0
  394. package/dist/docx/sectionParser.d.ts +21 -0
  395. package/dist/docx/sectionParser.js +1 -6
  396. package/dist/docx/selectiveSave.js +271 -80
  397. package/dist/docx/selectiveXmlPatch.d.ts +36 -1
  398. package/dist/docx/selectiveXmlPatch.js +342 -78
  399. package/dist/docx/serializer/blockSdtSerializer.d.ts +10 -0
  400. package/dist/docx/serializer/borderSerializer.d.ts +8 -0
  401. package/dist/docx/serializer/commentSerializer.d.ts +12 -1
  402. package/dist/docx/serializer/commentSerializer.js +1 -1
  403. package/dist/docx/serializer/documentSerializer.d.ts +21 -3
  404. package/dist/docx/serializer/documentSerializer.js +46 -7
  405. package/dist/docx/serializer/groupTextBoxWriteBack.d.ts +14 -0
  406. package/dist/docx/serializer/headerFooterSerializer.d.ts +11 -0
  407. package/dist/docx/serializer/markupRangeAttributes.d.ts +8 -0
  408. package/dist/docx/serializer/markupRangeAttributes.js +3 -1
  409. package/dist/docx/serializer/noteSerializer.d.ts +21 -0
  410. package/dist/docx/serializer/numberingSerializer.d.ts +14 -0
  411. package/dist/docx/serializer/paragraphSerializer.d.ts +11 -0
  412. package/dist/docx/serializer/paragraphSerializer.js +21 -9
  413. package/dist/docx/serializer/partNamespaces.d.ts +3 -1
  414. package/dist/docx/serializer/partNamespaces.js +4 -2
  415. package/dist/docx/serializer/runSerializer.js +12 -3
  416. package/dist/docx/serializer/sdtPropertiesSerializer.d.ts +15 -0
  417. package/dist/docx/serializer/stylesSerializer.d.ts +26 -1
  418. package/dist/docx/serializer/stylesSerializer.js +111 -23
  419. package/dist/docx/serializer/tableSerializer.js +9 -7
  420. package/dist/docx/serializer/themeSerializer.d.ts +2 -1
  421. package/dist/docx/server/applyDocxXmlPatchProposal.js +1 -1
  422. package/dist/docx/server/build.d.ts +1 -1
  423. package/dist/docx/server/changeListFormat.d.ts +20 -0
  424. package/dist/docx/server/changeListFormat.js +102 -0
  425. package/dist/docx/server/createBilingualDocument.d.ts +21 -0
  426. package/dist/docx/server/materializeYjsDocx.js +2 -2
  427. package/dist/docx/server/migrateYjsAttrSchema.js +5 -5
  428. package/dist/docx/sessionListPruning.d.ts +11 -0
  429. package/dist/docx/settingsParser.d.ts +10 -0
  430. package/dist/docx/shadingParser.d.ts +10 -0
  431. package/dist/docx/shapeAlternateContent.js +9 -2
  432. package/dist/docx/shapeParser.d.ts +27 -0
  433. package/dist/docx/splitRevisionPieces.d.ts +1 -1
  434. package/dist/docx/storyBlockReplay.d.ts +37 -3
  435. package/dist/docx/storyBlockReplay.js +291 -69
  436. package/dist/docx/strictNames.d.ts +12 -1
  437. package/dist/docx/strictValueEncodings.gen.d.ts +9 -0
  438. package/dist/docx/structuralXmlPatch.d.ts +19 -3
  439. package/dist/docx/structuralXmlPatch.js +139 -35
  440. package/dist/docx/styleParser.d.ts +20 -3
  441. package/dist/docx/styleParser.js +3 -2
  442. package/dist/docx/tableLook.d.ts +15 -1
  443. package/dist/docx/tableParser.d.ts +17 -6
  444. package/dist/docx/tableParser.js +10 -5
  445. package/dist/docx/textBoxContentParser.d.ts +3 -2
  446. package/dist/docx/textBoxParser.d.ts +30 -3
  447. package/dist/docx/themeColorAttribute.d.ts +11 -0
  448. package/dist/docx/themeParser.d.ts +17 -5
  449. package/dist/docx/trackedMoveRangeNormalization.d.ts +9 -0
  450. package/dist/docx/trackedMoveRangeNormalization.js +40 -16
  451. package/dist/docx/transitionalSpelling.d.ts +9 -0
  452. package/dist/docx/unnamedParagraphIds.d.ts +33 -0
  453. package/dist/docx/unnamedParagraphIds.js +43 -0
  454. package/dist/docx/unreferencedHeaderFooters.d.ts +27 -0
  455. package/dist/docx/unreferencedHeaderFooters.js +130 -0
  456. package/dist/docx/unzip.d.ts +25 -0
  457. package/dist/docx/verbatimCapture.d.ts +18 -0
  458. package/dist/docx/verbatimCapture.js +76 -9
  459. package/dist/docx/vmlImageParser.d.ts +32 -1
  460. package/dist/docx/watermarkParser.d.ts +21 -0
  461. package/dist/docx/wrapPolygon.d.ts +11 -0
  462. package/dist/docx/wrapTypes.d.ts +6 -0
  463. package/dist/docx/xmlParser.d.ts +23 -19
  464. package/dist/docx/xmlParser.js +2 -20
  465. package/dist/docx/xmlRootInsertion.d.ts +8 -0
  466. package/dist/docx/xmlRootInsertion.js +28 -0
  467. package/dist/docx/xmlSafety.d.ts +1 -0
  468. package/dist/docx/xmlSafety.js +7 -11
  469. package/dist/export-pdf.d.ts +24 -1
  470. package/dist/fields/resolveFieldValues.js +2 -1
  471. package/dist/fonts/fontsourceFaces.d.ts +2 -2
  472. package/dist/fonts/headlessMeasure.d.ts +16 -0
  473. package/dist/generated/text_shaper.js +71 -59
  474. package/dist/generated/text_shaper_bg.wasm +0 -0
  475. package/dist/headless-layout.d.ts +36 -5
  476. package/dist/headless-layout.js +19 -4
  477. package/dist/i18n/messages/ar.gen.js +2 -0
  478. package/dist/i18n/messages/catalogs.gen.d.ts +34 -0
  479. package/dist/i18n/messages/catalogs.gen.js +34 -0
  480. package/dist/i18n/messages/cs.gen.js +2 -0
  481. package/dist/i18n/messages/de.gen.js +2 -0
  482. package/dist/i18n/messages/en.gen.js +2 -0
  483. package/dist/i18n/messages/es.gen.js +2 -0
  484. package/dist/i18n/messages/et.gen.js +2 -0
  485. package/dist/i18n/messages/fr.gen.js +2 -0
  486. package/dist/i18n/messages/he.gen.js +2 -0
  487. package/dist/i18n/messages/hi.gen.js +2 -0
  488. package/dist/i18n/messages/hu.gen.js +2 -0
  489. package/dist/i18n/messages/lt.gen.js +2 -0
  490. package/dist/i18n/messages/lv.gen.js +2 -0
  491. package/dist/i18n/messages/messages.gen.d.ts +2 -0
  492. package/dist/i18n/messages/pl.gen.js +2 -0
  493. package/dist/i18n/messages/pt-BR.gen.js +2 -0
  494. package/dist/i18n/messages/sk.gen.js +2 -0
  495. package/dist/i18n/messages/tr.gen.js +2 -0
  496. package/dist/i18n/messages/zh-CN.gen.js +2 -0
  497. package/dist/index.d.ts +33 -31
  498. package/dist/index.js +3 -4
  499. package/dist/internal/canonicalOperationStaging.d.ts +2 -0
  500. package/dist/internal/canonicalOperationStaging.js +4 -0
  501. package/dist/internal/canonicalTyping.d.ts +9 -0
  502. package/dist/internal/canonicalTyping.js +7 -0
  503. package/dist/internal/compare/inline-presentation.d.ts +8 -0
  504. package/dist/internal/indexedPositionMap.js +2 -1
  505. package/dist/internal/pageBreakRunDescendantIndex.d.ts +7 -2
  506. package/dist/internal/pageBreakRunDescendantIndex.js +12 -3
  507. package/dist/internal/revisionResolutionInline.js +13 -13
  508. package/dist/internal/revisionResolutionStep.js +1 -0
  509. package/dist/internal/revisionResolutionTracking.js +2 -1
  510. package/dist/internal/subtreeHolds.d.ts +12 -0
  511. package/dist/internal/subtreeHolds.js +25 -0
  512. package/dist/internal/wholeStoryRevisionResolution.d.ts +1 -1
  513. package/dist/internal/wholeStoryRevisionResolution.js +57 -66
  514. package/dist/layout-bridge/cellSelectionHighlight.d.ts +8 -0
  515. package/dist/layout-bridge/cellSelectionHighlight.js +3 -3
  516. package/dist/layout-bridge/convert/altChunkPlaceholder.d.ts +7 -0
  517. package/dist/layout-bridge/convert/editingFont.d.ts +26 -0
  518. package/dist/layout-bridge/convert/editingFont.js +42 -0
  519. package/dist/layout-bridge/convert/endnoteLayout.d.ts +19 -1
  520. package/dist/layout-bridge/convert/flowBlockPostprocessing.d.ts +5 -0
  521. package/dist/layout-bridge/convert/flowBlockPostprocessing.js +20 -12
  522. package/dist/layout-bridge/convert/flowBorders.d.ts +10 -4
  523. package/dist/layout-bridge/convert/flowBorders.js +13 -1
  524. package/dist/layout-bridge/convert/flowConversionShared.d.ts +37 -8
  525. package/dist/layout-bridge/convert/flowConversionShared.js +39 -6
  526. package/dist/layout-bridge/convert/footnoteLayout.d.ts +12 -4
  527. package/dist/layout-bridge/convert/footnoteLayout.js +3 -1
  528. package/dist/layout-bridge/convert/headerFooterLayout.d.ts +25 -5
  529. package/dist/layout-bridge/convert/imageConversion.d.ts +5 -1
  530. package/dist/layout-bridge/convert/listMarkers.d.ts +12 -7
  531. package/dist/layout-bridge/convert/markupViewFlow.d.ts +21 -0
  532. package/dist/layout-bridge/convert/markupViewFlow.js +4 -1
  533. package/dist/layout-bridge/convert/noteReferences.d.ts +4 -0
  534. package/dist/layout-bridge/convert/pageBreakSplitting.d.ts +4 -0
  535. package/dist/layout-bridge/convert/paragraphAttrs.d.ts +25 -9
  536. package/dist/layout-bridge/convert/paragraphAttrs.js +12 -5
  537. package/dist/layout-bridge/convert/paragraphBlockCache.d.ts +36 -0
  538. package/dist/layout-bridge/convert/paragraphBlockCache.js +130 -0
  539. package/dist/layout-bridge/convert/paragraphConversion.d.ts +20 -6
  540. package/dist/layout-bridge/convert/paragraphConversion.js +37 -5
  541. package/dist/layout-bridge/convert/paragraphFrames.d.ts +2 -4
  542. package/dist/layout-bridge/convert/paragraphFrames.js +4 -4
  543. package/dist/layout-bridge/convert/paragraphMarkFormatting.d.ts +13 -4
  544. package/dist/layout-bridge/convert/paragraphRuns.d.ts +7 -2
  545. package/dist/layout-bridge/convert/paragraphRuns.js +18 -4
  546. package/dist/layout-bridge/convert/runFormattingMerge.d.ts +10 -4
  547. package/dist/layout-bridge/convert/runMarkFormatting.d.ts +8 -3
  548. package/dist/layout-bridge/convert/runMarkFormatting.js +3 -5
  549. package/dist/layout-bridge/convert/sectionBoundaries.d.ts +4 -0
  550. package/dist/layout-bridge/convert/sectionBoundaries.js +16 -0
  551. package/dist/layout-bridge/convert/tableConversion.d.ts +15 -5
  552. package/dist/layout-bridge/convert/tableConversion.js +40 -19
  553. package/dist/layout-bridge/convert/templatePreviewFlow.d.ts +38 -1
  554. package/dist/layout-bridge/convert/textBoxFill.d.ts +7 -2
  555. package/dist/layout-bridge/convert/textFormattingConversion.d.ts +18 -12
  556. package/dist/layout-bridge/convert/toFlowBlocks.d.ts +8 -2
  557. package/dist/layout-bridge/convert/toFlowBlocks.js +200 -18
  558. package/dist/layout-bridge/convert/topLevelConversion.d.ts +96 -0
  559. package/dist/layout-bridge/convert/topLevelConversion.js +109 -0
  560. package/dist/layout-bridge/convert/wrapEditorViewAsSurface.d.ts +10 -0
  561. package/dist/layout-bridge/dom/clickToPositionDom.js +45 -44
  562. package/dist/layout-bridge/dom/findBodyPmSpans.js +4 -3
  563. package/dist/layout-bridge/dom/findHfPmSpans.js +10 -15
  564. package/dist/layout-bridge/dom/imeCaretAnchor.d.ts +8 -0
  565. package/dist/layout-bridge/dom/imeCaretAnchor.js +71 -7
  566. package/dist/layout-bridge/dom/noteStoryDom.d.ts +1 -0
  567. package/dist/layout-bridge/dom/textStreamDom.js +3 -2
  568. package/dist/layout-bridge/engine/blockIndex.d.ts +3 -0
  569. package/dist/layout-bridge/engine/clickToPosition.d.ts +9 -0
  570. package/dist/layout-bridge/engine/hitTest.d.ts +6 -0
  571. package/dist/layout-bridge/engine/hitTest.js +3 -3
  572. package/dist/layout-bridge/engine/measuring/index.d.ts +20 -8
  573. package/dist/layout-bridge/engine/selectionRects.d.ts +9 -0
  574. package/dist/layout-bridge/headerFooterLayout.d.ts +12 -0
  575. package/dist/layout-bridge/headerFooterLayout.js +15 -14
  576. package/dist/layout-bridge/sectionColumns.d.ts +10 -1
  577. package/dist/layout-bridge/tableInsertHover.js +2 -1
  578. package/dist/layout-engine/footnoteContinuation.d.ts +8 -0
  579. package/dist/layout-engine/imageLayout.d.ts +4 -1
  580. package/dist/layout-engine/index.d.ts +10 -5
  581. package/dist/layout-engine/index.js +9 -3
  582. package/dist/layout-engine/keep-together.d.ts +6 -0
  583. package/dist/layout-engine/layoutFlowShared.d.ts +4 -0
  584. package/dist/layout-engine/layoutInstrumentation.d.ts +40 -1
  585. package/dist/layout-engine/layoutInstrumentation.js +26 -4
  586. package/dist/layout-engine/lineFlow.d.ts +1 -0
  587. package/dist/layout-engine/lineFlow.js +4 -1
  588. package/dist/layout-engine/measure/advanceComposition.d.ts +14 -1
  589. package/dist/layout-engine/measure/automaticTextSpacing.d.ts +1 -1
  590. package/dist/layout-engine/measure/cache.d.ts +8 -0
  591. package/dist/layout-engine/measure/cache.js +9 -1
  592. package/dist/layout-engine/measure/crossRunWords.d.ts +1 -1
  593. package/dist/layout-engine/measure/floatingLineClearance.d.ts +4 -0
  594. package/dist/layout-engine/measure/floatingTablePosition.d.ts +32 -1
  595. package/dist/layout-engine/measure/floatingTablePosition.js +49 -1
  596. package/dist/layout-engine/measure/font-metrics.worker.d.ts +16 -0
  597. package/dist/layout-engine/measure/hyphenationDictionaries.d.ts +18 -0
  598. package/dist/layout-engine/measure/hyphenationPreload.d.ts +4 -0
  599. package/dist/layout-engine/measure/index.d.ts +18 -8
  600. package/dist/layout-engine/measure/index.js +2 -1
  601. package/dist/layout-engine/measure/inlineObjectMetrics.d.ts +4 -0
  602. package/dist/layout-engine/measure/justification.d.ts +5 -1
  603. package/dist/layout-engine/measure/lineFitting.d.ts +6 -1
  604. package/dist/layout-engine/measure/lineTypography.d.ts +6 -1
  605. package/dist/layout-engine/measure/listMarkerWidth.d.ts +16 -1
  606. package/dist/layout-engine/measure/measureBlocks.d.ts +4 -1
  607. package/dist/layout-engine/measure/measureBlocks.js +127 -102
  608. package/dist/layout-engine/measure/measureContainer.d.ts +17 -0
  609. package/dist/layout-engine/measure/measureHelpers.d.ts +10 -1
  610. package/dist/layout-engine/measure/measureParagraph.d.ts +7 -1
  611. package/dist/layout-engine/measure/measureParagraph.js +51 -21
  612. package/dist/layout-engine/measure/measureProvider.d.ts +10 -0
  613. package/dist/layout-engine/measure/measureTypes.d.ts +8 -0
  614. package/dist/layout-engine/measure/measureWorker.d.ts +30 -0
  615. package/dist/layout-engine/measure/measureWorkerProtocol.d.ts +14 -0
  616. package/dist/layout-engine/measure/measuresHoldNoPositions.d.ts +40 -0
  617. package/dist/layout-engine/measure/measuresHoldNoPositions.js +14 -0
  618. package/dist/layout-engine/measure/paragraphKeyMemo.d.ts +20 -0
  619. package/dist/layout-engine/measure/paragraphKeyMemo.js +92 -0
  620. package/dist/layout-engine/measure/paragraphMeasureShared.d.ts +21 -2
  621. package/dist/layout-engine/measure/paragraphMeasureShared.js +20 -1
  622. package/dist/layout-engine/measure/paragraphTabs.d.ts +4 -0
  623. package/dist/layout-engine/measure/raisedTableWrap.d.ts +16 -0
  624. package/dist/layout-engine/measure/raisedTableWrap.js +105 -0
  625. package/dist/layout-engine/measure/tableBorderBands.d.ts +35 -0
  626. package/dist/layout-engine/measure/tableBorderBands.js +251 -0
  627. package/dist/layout-engine/measure/tableCellFloating.js +1 -1
  628. package/dist/layout-engine/measure/tableCellFlow.d.ts +4 -4
  629. package/dist/layout-engine/measure/tableCellFlow.js +7 -10
  630. package/dist/layout-engine/measure/tableCellGrid.d.ts +4 -1
  631. package/dist/layout-engine/measure/tableCellGrid.js +30 -3
  632. package/dist/layout-engine/measure/tableFragmentBorderGeometry.js +2 -1
  633. package/dist/layout-engine/measure/tableMeasureMemo.d.ts +23 -0
  634. package/dist/layout-engine/measure/tableMeasureMemo.js +40 -0
  635. package/dist/layout-engine/measure/tableNoWrapWidths.d.ts +12 -0
  636. package/dist/layout-engine/measure/tableNoWrapWidths.js +73 -0
  637. package/dist/layout-engine/measure/tableVisibleBand.d.ts +6 -0
  638. package/dist/layout-engine/measure/textMeasurementPolicy.d.ts +7 -1
  639. package/dist/layout-engine/noteAreaFlow.d.ts +10 -1
  640. package/dist/layout-engine/paginator.d.ts +6 -0
  641. package/dist/layout-engine/paginator.js +6 -5
  642. package/dist/layout-engine/paragraphLayout.d.ts +5 -1
  643. package/dist/layout-engine/paragraphSpacing.d.ts +17 -2
  644. package/dist/layout-engine/paragraphSpacing.js +103 -15
  645. package/dist/layout-engine/pmPageIndex.d.ts +14 -1
  646. package/dist/layout-engine/pmPageIndex.js +10 -1
  647. package/dist/layout-engine/section-breaks.d.ts +6 -0
  648. package/dist/layout-engine/sectionLayout.d.ts +6 -1
  649. package/dist/layout-engine/sectionVerticalAlignment.js +2 -1
  650. package/dist/layout-engine/tableHeaderCompatibility.d.ts +3 -0
  651. package/dist/layout-engine/tableHeaderCompatibility.js +5 -0
  652. package/dist/layout-engine/tableLayout.d.ts +17 -6
  653. package/dist/layout-engine/tableLayout.js +36 -25
  654. package/dist/layout-engine/tableRowBreak.d.ts +16 -0
  655. package/dist/layout-engine/tableRowBreak.js +2 -1
  656. package/dist/layout-engine/textBoxFlow.d.ts +9 -0
  657. package/dist/layout-engine/textBoxLayout.d.ts +5 -1
  658. package/dist/layout-engine/types.d.ts +41 -2
  659. package/dist/layout-engine/types.js +77 -27
  660. package/dist/layout-painter/borderStroke.d.ts +1 -1
  661. package/dist/layout-painter/characterFillBand.d.ts +14 -0
  662. package/dist/layout-painter/characterFillBand.js +79 -0
  663. package/dist/layout-painter/imageLayout.d.ts +11 -2
  664. package/dist/layout-painter/imageLayout.js +2 -1
  665. package/dist/layout-painter/index.d.ts +12 -6
  666. package/dist/layout-painter/pageShellStyles.d.ts +19 -0
  667. package/dist/layout-painter/pageShellStyles.js +32 -0
  668. package/dist/layout-painter/previewSvg.d.ts +7 -0
  669. package/dist/layout-painter/reconcileRenderedContent.d.ts +19 -0
  670. package/dist/layout-painter/reconcileRenderedContent.js +119 -0
  671. package/dist/layout-painter/registry/modules/image.d.ts +7 -0
  672. package/dist/layout-painter/registry/modules/paragraph.d.ts +8 -0
  673. package/dist/layout-painter/registry/modules/table.d.ts +6 -0
  674. package/dist/layout-painter/registry/modules/textBox.d.ts +3 -0
  675. package/dist/layout-painter/registry/modules.d.ts +10 -0
  676. package/dist/layout-painter/registry/registry.d.ts +8 -0
  677. package/dist/layout-painter/registry/types.d.ts +11 -0
  678. package/dist/layout-painter/renderFragment.d.ts +6 -0
  679. package/dist/layout-painter/renderFragment.js +4 -6
  680. package/dist/layout-painter/renderImage.d.ts +8 -0
  681. package/dist/layout-painter/renderImage.js +2 -2
  682. package/dist/layout-painter/renderPage.d.ts +10 -3
  683. package/dist/layout-painter/renderPage.js +31 -33
  684. package/dist/layout-painter/renderParagraph.d.ts +6 -0
  685. package/dist/layout-painter/renderParagraph.js +36 -19
  686. package/dist/layout-painter/renderTable.d.ts +10 -1
  687. package/dist/layout-painter/renderTable.js +121 -36
  688. package/dist/layout-painter/renderTextBox.d.ts +9 -0
  689. package/dist/layout-painter/renderTextBox.js +2 -2
  690. package/dist/layout-painter/renderUtils.d.ts +5 -1
  691. package/dist/layout-painter/renderWatermark.d.ts +11 -1
  692. package/dist/layout-painter/sdtBoundary.d.ts +10 -0
  693. package/dist/layout-painter/sdtBoundary.js +3 -2
  694. package/dist/managers/ClipboardManager.d.ts +13 -0
  695. package/dist/managers/ContextMenuManager.d.ts +16 -4
  696. package/dist/managers/ContextMenuManager.js +3 -3
  697. package/dist/managers/DocumentLoaderManager.d.ts +19 -5
  698. package/dist/managers/DocumentLoaderManager.js +48 -13
  699. package/dist/managers/EditorModeManager.d.ts +11 -0
  700. package/dist/managers/ErrorManager.d.ts +11 -0
  701. package/dist/managers/FindReplaceManager.d.ts +14 -27
  702. package/dist/managers/FindReplaceManager.js +0 -49
  703. package/dist/managers/HistoryManager.d.ts +18 -0
  704. package/dist/managers/TableSelectionManager.d.ts +18 -4
  705. package/dist/managers/TableSelectionManager.js +22 -5
  706. package/dist/managers/editorShortcuts.d.ts +14 -2
  707. package/dist/managers/editorShortcuts.js +5 -3
  708. package/dist/managers/types.d.ts +15 -1
  709. package/dist/markdown/annotations.d.ts +9 -0
  710. package/dist/markdown/countParagraphList.d.ts +8 -0
  711. package/dist/markdown/escape.d.ts +6 -4
  712. package/dist/markdown/escape.js +17 -8
  713. package/dist/markdown/images.d.ts +11 -0
  714. package/dist/markdown/index.d.ts +24 -1
  715. package/dist/markdown/index.js +18 -1
  716. package/dist/markdown/internals.d.ts +7 -0
  717. package/dist/markdown/renderBlock.d.ts +5 -0
  718. package/dist/markdown/renderBlock.js +2 -7
  719. package/dist/markdown/renderParagraph.d.ts +22 -2
  720. package/dist/markdown/renderParagraph.js +11 -9
  721. package/dist/markdown/renderRuns.d.ts +10 -0
  722. package/dist/markdown/renderRuns.js +36 -3
  723. package/dist/markdown/renderTable.d.ts +7 -0
  724. package/dist/markdown/renderTable.js +2 -2
  725. package/dist/markdown/trailers.d.ts +7 -0
  726. package/dist/markdown/types.d.ts +9 -2
  727. package/dist/model.d.ts +25 -3
  728. package/dist/paged-layout/blockGeometry.js +3 -2
  729. package/dist/paged-layout/editorScrollRoot.d.ts +9 -0
  730. package/dist/paged-layout/editorScrollRoot.js +10 -1
  731. package/dist/paged-layout/pageText.d.ts +1 -1
  732. package/dist/paged-layout/paragraphFlash.d.ts +3 -0
  733. package/dist/paged-layout/rangeProjection.d.ts +20 -1
  734. package/dist/paged-layout/rangeProjection.js +26 -7
  735. package/dist/paged-layout/scrollToPmPosition.d.ts +15 -0
  736. package/dist/paged-layout/scrollToPmPosition.js +3 -3
  737. package/dist/paged-layout/sectionBlockWidths.d.ts +2 -2
  738. package/dist/paged-layout/sectionGeometry.d.ts +4 -3
  739. package/dist/paged-layout/selectionViewportRect.d.ts +19 -0
  740. package/dist/paged-layout/selectionViewportRect.js +8 -2
  741. package/dist/panel-layout.d.ts +18 -1
  742. package/dist/panel-layout.js +36 -2
  743. package/dist/pdf/contentStream.d.ts +12 -0
  744. package/dist/pdf/fonts.d.ts +19 -0
  745. package/dist/pdf/paint.d.ts +9 -1
  746. package/dist/pdf/paint.js +51 -0
  747. package/dist/prosemirror/acceptedBlockNeighbours.d.ts +50 -0
  748. package/dist/prosemirror/acceptedBlockNeighbours.js +63 -0
  749. package/dist/prosemirror/alternateContentAttrs.d.ts +1 -1
  750. package/dist/prosemirror/anchoredTextBoxes.d.ts +20 -0
  751. package/dist/prosemirror/attrs/index.d.ts +2 -2
  752. package/dist/prosemirror/attrs/index.js +2 -1
  753. package/dist/prosemirror/authoredTransformAttrs.d.ts +14 -0
  754. package/dist/prosemirror/bookmarkBoundaryAttrs.d.ts +2 -2
  755. package/dist/prosemirror/canonicalCommands.d.ts +26 -1
  756. package/dist/prosemirror/canonicalCommands.js +12 -1
  757. package/dist/prosemirror/canonicalSelectionRange.d.ts +1 -1
  758. package/dist/prosemirror/canonicalTableCommands.d.ts +14 -0
  759. package/dist/prosemirror/canonicalTableCommands.js +18 -6
  760. package/dist/prosemirror/cellDragSelection.d.ts +9 -0
  761. package/dist/prosemirror/commands/comments.d.ts +27 -2
  762. package/dist/prosemirror/commands/comments.js +459 -159
  763. package/dist/prosemirror/commands/contentControls.d.ts +20 -3
  764. package/dist/prosemirror/commands/contentControls.js +18 -1
  765. package/dist/prosemirror/commands/contentControlsBlockFill.d.ts +11 -1
  766. package/dist/prosemirror/commands/formatPainter.d.ts +10 -0
  767. package/dist/prosemirror/commands/formatPainter.js +0 -1
  768. package/dist/prosemirror/commands/formatting.d.ts +9 -2
  769. package/dist/prosemirror/commands/hyperlink.d.ts +12 -0
  770. package/dist/prosemirror/commands/image.d.ts +12 -0
  771. package/dist/prosemirror/commands/index.d.ts +10 -5
  772. package/dist/prosemirror/commands/pageBreak.d.ts +3 -0
  773. package/dist/prosemirror/commands/paragraph.d.ts +8 -1
  774. package/dist/prosemirror/commands/pastePlainText.d.ts +8 -0
  775. package/dist/prosemirror/commands/pastePlainText.js +1 -1
  776. package/dist/prosemirror/commands/propertyChangeScope.d.ts +28 -15
  777. package/dist/prosemirror/commands/propertyChangeScope.js +5 -12
  778. package/dist/prosemirror/commands/replaceRangeText.d.ts +22 -0
  779. package/dist/prosemirror/commands/replaceRangeText.js +44 -0
  780. package/dist/prosemirror/commands/resolveAllTableChanges.js +3 -2
  781. package/dist/prosemirror/commands/resolveParagraphProperties.js +4 -8
  782. package/dist/prosemirror/commands/rulerParagraph.d.ts +25 -0
  783. package/dist/prosemirror/commands/rulerParagraph.js +18 -0
  784. package/dist/prosemirror/commands/sectionBreak.d.ts +5 -0
  785. package/dist/prosemirror/commands/table.d.ts +7 -0
  786. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +1 -1
  787. package/dist/prosemirror/commentIdAllocator.d.ts +12 -6
  788. package/dist/prosemirror/commentIdAllocator.js +38 -29
  789. package/dist/prosemirror/commentOps.d.ts +7 -0
  790. package/dist/prosemirror/commentRangeBoundaryAttrs.d.ts +1 -1
  791. package/dist/prosemirror/commentRangeInlineAtoms.d.ts +4 -3
  792. package/dist/prosemirror/commentRangeInlineAtoms.js +1 -1
  793. package/dist/prosemirror/commentRecords.d.ts +154 -0
  794. package/dist/prosemirror/commentRecords.js +527 -0
  795. package/dist/prosemirror/commentReferenceAttrs.d.ts +1 -1
  796. package/dist/prosemirror/commentReferenceIntegrity.js +93 -14
  797. package/dist/prosemirror/containerFinalParagraph.d.ts +2 -0
  798. package/dist/prosemirror/containerFinalParagraph.js +3 -1
  799. package/dist/prosemirror/contentControlRevisions.d.ts +14 -0
  800. package/dist/prosemirror/conversion/effectiveTableCellFormatting.d.ts +5 -4
  801. package/dist/prosemirror/conversion/fromProseDoc.d.ts +1 -1
  802. package/dist/prosemirror/conversion/fromProseDoc.js +81 -61
  803. package/dist/prosemirror/conversion/index.d.ts +7 -2
  804. package/dist/prosemirror/conversion/preservedSinkCarriers.d.ts +21 -0
  805. package/dist/prosemirror/conversion/runShadingMark.d.ts +13 -1
  806. package/dist/prosemirror/conversion/storyConversionOptions.d.ts +16 -0
  807. package/dist/prosemirror/conversion/storyConversionOptions.js +13 -0
  808. package/dist/prosemirror/conversion/toProseDoc.d.ts +48 -14
  809. package/dist/prosemirror/conversion/toProseDoc.js +294 -145
  810. package/dist/prosemirror/copyOriginResolution.js +23 -10
  811. package/dist/prosemirror/documentSchema.d.ts +12 -0
  812. package/dist/prosemirror/emptyRangeAnchor.d.ts +39 -8
  813. package/dist/prosemirror/emptyRangeAnchor.js +63 -10
  814. package/dist/prosemirror/extensions/ExtensionManager.d.ts +7 -0
  815. package/dist/prosemirror/extensions/ExtensionManager.js +2 -0
  816. package/dist/prosemirror/extensions/StarterKit.d.ts +11 -2
  817. package/dist/prosemirror/extensions/core/DocExtension.d.ts +3 -0
  818. package/dist/prosemirror/extensions/core/HistoryExtension.d.ts +3 -0
  819. package/dist/prosemirror/extensions/core/HistoryExtension.js +3 -2
  820. package/dist/prosemirror/extensions/core/ParagraphExtension.d.ts +13 -4
  821. package/dist/prosemirror/extensions/core/ParagraphExtension.js +5 -3
  822. package/dist/prosemirror/extensions/core/TextExtension.d.ts +3 -0
  823. package/dist/prosemirror/extensions/create.d.ts +6 -0
  824. package/dist/prosemirror/extensions/features/BaseKeymapExtension.d.ts +5 -0
  825. package/dist/prosemirror/extensions/features/BaseKeymapExtension.js +3 -3
  826. package/dist/prosemirror/extensions/features/BidiShortcutExtension.d.ts +10 -0
  827. package/dist/prosemirror/extensions/features/ContentControlWidgetsExtension.d.ts +10 -0
  828. package/dist/prosemirror/extensions/features/DropCursorExtension.d.ts +6 -0
  829. package/dist/prosemirror/extensions/features/EmptyParagraphFormatExtension.d.ts +20 -0
  830. package/dist/prosemirror/extensions/features/EmptyParagraphFormatExtension.js +20 -23
  831. package/dist/prosemirror/extensions/features/GapCursorExtension.d.ts +13 -0
  832. package/dist/prosemirror/extensions/features/ImageDragExtension.d.ts +9 -0
  833. package/dist/prosemirror/extensions/features/ImagePasteExtension.d.ts +6 -0
  834. package/dist/prosemirror/extensions/features/JoinedRunStyleExtension.d.ts +14 -0
  835. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.js +38 -21
  836. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +30 -3
  837. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.js +65 -45
  838. package/dist/prosemirror/extensions/features/PasteCleanupExtension.d.ts +17 -0
  839. package/dist/prosemirror/extensions/features/PasteCleanupExtension.js +7 -3
  840. package/dist/prosemirror/extensions/features/PasteStyleInlinerExtension.d.ts +14 -0
  841. package/dist/prosemirror/extensions/features/SelectionTrackerExtension.d.ts +4 -1
  842. package/dist/prosemirror/extensions/features/pasteCleanup.d.ts +32 -3
  843. package/dist/prosemirror/extensions/features/pasteCleanup.js +23 -3
  844. package/dist/prosemirror/extensions/features/pastedCellSections.d.ts +22 -0
  845. package/dist/prosemirror/extensions/features/pastedCellSections.js +78 -0
  846. package/dist/prosemirror/extensions/features/pastedHeadingStyles.d.ts +22 -0
  847. package/dist/prosemirror/extensions/features/pastedHtmlLists.d.ts +1 -0
  848. package/dist/prosemirror/extensions/markRegistry.d.ts +14 -1
  849. package/dist/prosemirror/extensions/marks/AllCapsExtension.d.ts +3 -0
  850. package/dist/prosemirror/extensions/marks/BoldExtension.d.ts +3 -0
  851. package/dist/prosemirror/extensions/marks/CharacterSpacingExtension.d.ts +8 -0
  852. package/dist/prosemirror/extensions/marks/CharacterStyleExtension.d.ts +14 -0
  853. package/dist/prosemirror/extensions/marks/CommentExtension.d.ts +6 -0
  854. package/dist/prosemirror/extensions/marks/CommentExtension.js +3 -1
  855. package/dist/prosemirror/extensions/marks/FontFamilyExtension.d.ts +3 -0
  856. package/dist/prosemirror/extensions/marks/FontFamilyExtension.js +4 -6
  857. package/dist/prosemirror/extensions/marks/FontSizeExtension.d.ts +3 -0
  858. package/dist/prosemirror/extensions/marks/FootnoteRefExtension.d.ts +5 -0
  859. package/dist/prosemirror/extensions/marks/HiddenTextExtension.d.ts +17 -0
  860. package/dist/prosemirror/extensions/marks/HighlightExtension.d.ts +3 -0
  861. package/dist/prosemirror/extensions/marks/HyperlinkExtension.d.ts +3 -0
  862. package/dist/prosemirror/extensions/marks/HyphenElementExtension.d.ts +19 -0
  863. package/dist/prosemirror/extensions/marks/InlineWrapperExtension.d.ts +12 -0
  864. package/dist/prosemirror/extensions/marks/ItalicExtension.d.ts +3 -0
  865. package/dist/prosemirror/extensions/marks/RunFormattingOverrideExtension.d.ts +11 -2
  866. package/dist/prosemirror/extensions/marks/RunFormattingOverrideExtension.js +2 -1
  867. package/dist/prosemirror/extensions/marks/RunIdentityExtension.d.ts +21 -0
  868. package/dist/prosemirror/extensions/marks/SmallCapsExtension.d.ts +3 -0
  869. package/dist/prosemirror/extensions/marks/StrikeExtension.d.ts +3 -0
  870. package/dist/prosemirror/extensions/marks/SubscriptExtension.d.ts +3 -0
  871. package/dist/prosemirror/extensions/marks/SuperscriptExtension.d.ts +3 -0
  872. package/dist/prosemirror/extensions/marks/TextColorExtension.d.ts +3 -0
  873. package/dist/prosemirror/extensions/marks/TextEffectsExtensions.d.ts +6 -0
  874. package/dist/prosemirror/extensions/marks/TrackedChangeExtensions.d.ts +7 -0
  875. package/dist/prosemirror/extensions/marks/UnderlineExtension.d.ts +3 -0
  876. package/dist/prosemirror/extensions/marks/markUtils.d.ts +10 -3
  877. package/dist/prosemirror/extensions/nodes/BlockBookmarkBoundaryExtension.d.ts +22 -0
  878. package/dist/prosemirror/extensions/nodes/BlockCommentRangeBoundaryExtension.d.ts +11 -0
  879. package/dist/prosemirror/extensions/nodes/BlockMoveRangeBoundaryExtension.d.ts +14 -0
  880. package/dist/prosemirror/extensions/nodes/BlockSdtExtension.d.ts +17 -0
  881. package/dist/prosemirror/extensions/nodes/BookmarkBoundaryExtension.d.ts +1 -0
  882. package/dist/prosemirror/extensions/nodes/BookmarkBoundaryExtension.js +38 -4
  883. package/dist/prosemirror/extensions/nodes/CommentReferenceExtension.d.ts +2 -1
  884. package/dist/prosemirror/extensions/nodes/CommentReferenceExtension.js +3 -1
  885. package/dist/prosemirror/extensions/nodes/FieldExtension.d.ts +8 -0
  886. package/dist/prosemirror/extensions/nodes/HardBreakExtension.d.ts +3 -0
  887. package/dist/prosemirror/extensions/nodes/HorizontalRuleExtension.d.ts +3 -0
  888. package/dist/prosemirror/extensions/nodes/ImageExtension.d.ts +3 -0
  889. package/dist/prosemirror/extensions/nodes/MathExtension.d.ts +7 -0
  890. package/dist/prosemirror/extensions/nodes/MoveRangeBoundaryExtension.d.ts +1 -0
  891. package/dist/prosemirror/extensions/nodes/PageBreakExtension.d.ts +3 -0
  892. package/dist/prosemirror/extensions/nodes/PageBreakRunExtension.d.ts +1 -0
  893. package/dist/prosemirror/extensions/nodes/PreservedBlockExtension.d.ts +25 -0
  894. package/dist/prosemirror/extensions/nodes/PreservedXmlExtension.d.ts +9 -0
  895. package/dist/prosemirror/extensions/nodes/RangeAnchorExtension.d.ts +1 -0
  896. package/dist/prosemirror/extensions/nodes/RangeAnchorExtension.js +7 -19
  897. package/dist/prosemirror/extensions/nodes/RenderedPageBreakExtension.d.ts +1 -0
  898. package/dist/prosemirror/extensions/nodes/SdtExtension.d.ts +6 -0
  899. package/dist/prosemirror/extensions/nodes/ShapeExtension.d.ts +6 -0
  900. package/dist/prosemirror/extensions/nodes/TabExtension.d.ts +3 -0
  901. package/dist/prosemirror/extensions/nodes/TableExtension.d.ts +8 -1
  902. package/dist/prosemirror/extensions/nodes/TableExtension.js +6 -6
  903. package/dist/prosemirror/extensions/nodes/TextBoxAnchorExtension.d.ts +7 -0
  904. package/dist/prosemirror/extensions/nodes/TextBoxExtension.d.ts +7 -0
  905. package/dist/prosemirror/extensions/nodes/bookmarkBoundaryDom.d.ts +9 -0
  906. package/dist/prosemirror/extensions/types.d.ts +10 -1
  907. package/dist/prosemirror/findReplaceSelection.d.ts +1 -1
  908. package/dist/prosemirror/hyperlinkRemoval.d.ts +13 -1
  909. package/dist/prosemirror/imageCommit.d.ts +10 -0
  910. package/dist/prosemirror/index.d.ts +30 -20
  911. package/dist/prosemirror/indexedNodeLookup.d.ts +11 -0
  912. package/dist/prosemirror/inlineWrapperStack.d.ts +12 -0
  913. package/dist/prosemirror/insertOperations.d.ts +10 -1
  914. package/dist/prosemirror/insertOperations.js +2 -2
  915. package/dist/prosemirror/insertionGaps.d.ts +21 -0
  916. package/dist/prosemirror/insertionGaps.js +86 -0
  917. package/dist/prosemirror/keptRangeBoundaries.d.ts +16 -12
  918. package/dist/prosemirror/keptRangeBoundaries.js +28 -34
  919. package/dist/prosemirror/listAutoformatMarkers.d.ts +11 -0
  920. package/dist/prosemirror/listInstanceReferences.d.ts +5 -0
  921. package/dist/prosemirror/listLabels.d.ts +16 -3
  922. package/dist/prosemirror/listLabels.js +0 -6
  923. package/dist/prosemirror/listMarker.d.ts +2 -2
  924. package/dist/prosemirror/listNumbering.d.ts +1 -1
  925. package/dist/prosemirror/listRendering.d.ts +2 -2
  926. package/dist/prosemirror/listRenderingAttrs.d.ts +10 -1
  927. package/dist/prosemirror/lockedControls.d.ts +6 -0
  928. package/dist/prosemirror/markupViewNotes.d.ts +11 -1
  929. package/dist/prosemirror/markupViewProjection.d.ts +21 -4
  930. package/dist/prosemirror/moveRangeBoundaryAttrs.d.ts +1 -1
  931. package/dist/prosemirror/nativeSelection.d.ts +51 -0
  932. package/dist/prosemirror/nativeSelection.js +124 -0
  933. package/dist/prosemirror/noteReferenceOccurrences.d.ts +1 -1
  934. package/dist/prosemirror/noteReferenceReview.d.ts +17 -3
  935. package/dist/prosemirror/noteReferenceReview.js +26 -5
  936. package/dist/prosemirror/numberedRefFields.d.ts +2 -0
  937. package/dist/prosemirror/numberedRefFields.js +16 -5
  938. package/dist/prosemirror/pageBreakRunProjection.d.ts +2 -1
  939. package/dist/prosemirror/paraText.d.ts +14 -0
  940. package/dist/prosemirror/paragraphFormattingProvenance.d.ts +13 -1
  941. package/dist/prosemirror/paragraphIndentation.d.ts +6 -3
  942. package/dist/prosemirror/paragraphIndentation.js +2 -3
  943. package/dist/prosemirror/paragraphList.d.ts +1 -1
  944. package/dist/prosemirror/paragraphMarkJoin.d.ts +34 -8
  945. package/dist/prosemirror/paragraphMarkJoin.js +176 -18
  946. package/dist/prosemirror/paragraphPropertyCarry.d.ts +15 -1
  947. package/dist/prosemirror/paragraphPropertyCarry.js +5 -3
  948. package/dist/prosemirror/paragraphSpacing.d.ts +1 -1
  949. package/dist/prosemirror/pastePlacement.d.ts +17 -0
  950. package/dist/prosemirror/pastePlacement.js +22 -0
  951. package/dist/prosemirror/pastedCommentCopies.d.ts +87 -0
  952. package/dist/prosemirror/pastedCommentCopies.js +379 -0
  953. package/dist/prosemirror/plugins/aiCitationDecorations.d.ts +12 -0
  954. package/dist/prosemirror/plugins/aiSuggestionDecorations.d.ts +14 -0
  955. package/dist/prosemirror/plugins/contentControlWidgets.d.ts +15 -9
  956. package/dist/prosemirror/plugins/contentControlWidgets.js +24 -30
  957. package/dist/prosemirror/plugins/createDocScanPlugin.d.ts +17 -0
  958. package/dist/prosemirror/plugins/documentNumbering.d.ts +2 -1
  959. package/dist/prosemirror/plugins/documentNumbering.js +33 -14
  960. package/dist/prosemirror/plugins/documentStyleState.d.ts +3 -4
  961. package/dist/prosemirror/plugins/documentStyles.d.ts +20 -3
  962. package/dist/prosemirror/plugins/index.d.ts +7 -1
  963. package/dist/prosemirror/plugins/paragraphStyleResolution.d.ts +18 -1
  964. package/dist/prosemirror/plugins/paragraphStyleResolution.js +12 -2
  965. package/dist/prosemirror/plugins/pmTextScan.d.ts +18 -0
  966. package/dist/prosemirror/plugins/pmTextScan.js +42 -33
  967. package/dist/prosemirror/plugins/revisionIds.d.ts +14 -1
  968. package/dist/prosemirror/plugins/revisionIds.js +5 -1
  969. package/dist/prosemirror/plugins/selectionTracker.d.ts +12 -2
  970. package/dist/prosemirror/plugins/suggestionMode.d.ts +14 -11
  971. package/dist/prosemirror/plugins/suggestionMode.js +225 -35
  972. package/dist/prosemirror/plugins/templateDirectives.d.ts +17 -0
  973. package/dist/prosemirror/plugins/templatePreviewValues.d.ts +23 -0
  974. package/dist/prosemirror/plugins/templateSlashMenu.d.ts +19 -0
  975. package/dist/prosemirror/plugins/transactionInvariants.d.ts +19 -0
  976. package/dist/prosemirror/positionSweep.d.ts +21 -0
  977. package/dist/prosemirror/queries.d.ts +9 -0
  978. package/dist/prosemirror/queries.js +2 -2
  979. package/dist/prosemirror/rangeAnchorAttrs.d.ts +2 -2
  980. package/dist/prosemirror/rangeAnchorAttrs.js +55 -33
  981. package/dist/prosemirror/rebaseParagraphRuns.js +1 -1
  982. package/dist/prosemirror/rejoinRunCarriers.d.ts +17 -0
  983. package/dist/prosemirror/replaceFindMatches.d.ts +20 -0
  984. package/dist/prosemirror/replaceFindMatches.js +33 -0
  985. package/dist/prosemirror/replacedAnnotations.d.ts +143 -0
  986. package/dist/prosemirror/replacedAnnotations.js +223 -26
  987. package/dist/prosemirror/revisionCarriers.js +9 -0
  988. package/dist/prosemirror/runFormattingFromMarks.d.ts +3 -3
  989. package/dist/prosemirror/runFormattingFromMarks.js +10 -51
  990. package/dist/prosemirror/runFormattingProvenance.d.ts +2 -1
  991. package/dist/prosemirror/runFormattingProvenance.js +2 -1
  992. package/dist/prosemirror/runFormattingReconciliation.js +3 -12
  993. package/dist/prosemirror/runIdentity.d.ts +14 -0
  994. package/dist/prosemirror/runIdentityAcrossRevisions.d.ts +30 -1
  995. package/dist/prosemirror/runIdentityAcrossRevisions.js +57 -8
  996. package/dist/prosemirror/runPropertyChangeResolution.d.ts +5 -13
  997. package/dist/prosemirror/runPropertyChangeResolution.js +13 -30
  998. package/dist/prosemirror/runStyleFormatting.d.ts +42 -113
  999. package/dist/prosemirror/runStyleFormatting.js +17 -74
  1000. package/dist/prosemirror/schema/index.d.ts +8 -1
  1001. package/dist/prosemirror/schema/marks.d.ts +21 -1
  1002. package/dist/prosemirror/schema/nodes.d.ts +15 -14
  1003. package/dist/prosemirror/sectionCarrier.d.ts +21 -0
  1004. package/dist/prosemirror/sectionMarkEdits.d.ts +18 -0
  1005. package/dist/prosemirror/selectionState.d.ts +10 -4
  1006. package/dist/prosemirror/storyListNumbering.d.ts +10 -0
  1007. package/dist/prosemirror/storyListNumbering.js +7 -2
  1008. package/dist/prosemirror/styles/index.d.ts +3 -0
  1009. package/dist/prosemirror/styles/paragraphStyleCascade.d.ts +20 -18
  1010. package/dist/prosemirror/styles/paragraphStyleCascade.js +10 -19
  1011. package/dist/prosemirror/styles/resolvedStyleAttrs.d.ts +4 -3
  1012. package/dist/prosemirror/styles/styleResolver.d.ts +40 -15
  1013. package/dist/prosemirror/styles/styleResolver.js +6 -6
  1014. package/dist/prosemirror/styles/styleToggleCascade.d.ts +18 -11
  1015. package/dist/prosemirror/styles/styleToggleCascade.js +2 -11
  1016. package/dist/prosemirror/styles/tableStyleRegions.d.ts +20 -7
  1017. package/dist/prosemirror/styles/tableStyleRegions.js +14 -13
  1018. package/dist/prosemirror/tableCellPaste.d.ts +21 -0
  1019. package/dist/prosemirror/tableCellPaste.js +32 -2
  1020. package/dist/prosemirror/tableGridMutation.d.ts +9 -0
  1021. package/dist/prosemirror/tableGridMutation.js +34 -2
  1022. package/dist/prosemirror/tablePositionedBookmarks.d.ts +6 -0
  1023. package/dist/prosemirror/tableResize.d.ts +20 -9
  1024. package/dist/prosemirror/tableResize.js +60 -49
  1025. package/dist/prosemirror/tableRunIn.d.ts +26 -1
  1026. package/dist/prosemirror/tableRunIn.js +39 -11
  1027. package/dist/prosemirror/textBoxAnchorAttrs.d.ts +1 -1
  1028. package/dist/prosemirror/textBoxHostCollapse.d.ts +11 -0
  1029. package/dist/prosemirror/textInput.d.ts +30 -1
  1030. package/dist/prosemirror/textInput.js +144 -17
  1031. package/dist/prosemirror/utils/findParagraphByParaId.d.ts +5 -0
  1032. package/dist/prosemirror/utils/tabCalculator.d.ts +6 -0
  1033. package/dist/prosemirror/utils/visualLineNavigation.js +21 -19
  1034. package/dist/prosemirror/validation.d.ts +19 -0
  1035. package/dist/prosemirror/validation.js +84 -16
  1036. package/dist/prosemirror/yjsDocumentMetadata.d.ts +9 -3
  1037. package/dist/prosemirror/yjsDocumentMetadata.js +49 -10
  1038. package/dist/prosemirror/zeroWidthAnchors.d.ts +18 -0
  1039. package/dist/redline.d.ts +4 -1
  1040. package/dist/redline.js +21 -13
  1041. package/dist/render-dom/BodySelectionOverlay.d.ts +5 -0
  1042. package/dist/render-dom/HeaderFooterSelectionOverlay.js +5 -4
  1043. package/dist/render-dom/RemoteSelectionOverlay.js +3 -3
  1044. package/dist/render-dom/RenderedDomContext.js +7 -6
  1045. package/dist/server.d.ts +30 -18
  1046. package/dist/server.js +4 -3
  1047. package/dist/shaping/placeRun.d.ts +8 -0
  1048. package/dist/shaping/shaper.d.ts +19 -0
  1049. package/dist/style-engine/index.d.ts +5 -0
  1050. package/dist/style-engine/styleEngine.d.ts +32 -13
  1051. package/dist/style-sets/extract.d.ts +1 -1
  1052. package/dist/style-sets/styleSetNormalization.d.ts +20 -1
  1053. package/dist/text-shaping.d.ts +9 -1
  1054. package/dist/types/anonymization.d.ts +17 -0
  1055. package/dist/types/anonymization.js +0 -0
  1056. package/dist/types/autocomplete.d.ts +46 -0
  1057. package/dist/types/autocomplete.js +0 -0
  1058. package/dist/types/canonicalCapabilities.d.ts +52 -53
  1059. package/dist/types/canonicalCapabilities.js +54 -56
  1060. package/dist/types/canonicalSave.d.ts +36 -0
  1061. package/dist/types/documentModel.d.ts +37 -0
  1062. package/dist/types/documentModel.js +24 -0
  1063. package/dist/types/docxSerialization.d.ts +10 -0
  1064. package/dist/types/index.d.ts +5 -0
  1065. package/dist/types/remote-selection.d.ts +2 -1
  1066. package/dist/types/selectiveSaveDecline.d.ts +44 -0
  1067. package/dist/types/selectiveSaveDecline.js +0 -0
  1068. package/dist/types/tableWidthKind.d.ts +2 -0
  1069. package/dist/types/tableWidthKind.js +9 -0
  1070. package/dist/utils/base64.d.ts +20 -0
  1071. package/dist/utils/borderCss.d.ts +18 -1
  1072. package/dist/utils/colorResolver.d.ts +12 -11
  1073. package/dist/utils/createDocument.d.ts +8 -1
  1074. package/dist/utils/createDocument.js +20 -2
  1075. package/dist/utils/diagonalHatch.d.ts +2 -0
  1076. package/dist/utils/diagonalHatch.js +16 -0
  1077. package/dist/utils/extremes.d.ts +4 -0
  1078. package/dist/utils/extremes.js +14 -0
  1079. package/dist/utils/findMatchView.d.ts +2 -2
  1080. package/dist/utils/findMatchView.js +4 -3
  1081. package/dist/utils/findReplace.d.ts +2 -2
  1082. package/dist/utils/findReplace.js +3 -2
  1083. package/dist/utils/fontFamilyMerge.d.ts +2 -1
  1084. package/dist/utils/fontResolver.d.ts +11 -2
  1085. package/dist/utils/formatToStyle.d.ts +21 -7
  1086. package/dist/utils/headerFooter.d.ts +16 -2
  1087. package/dist/utils/headerFooter.js +2 -6
  1088. package/dist/utils/imageResize.js +1 -1
  1089. package/dist/utils/listItems.d.ts +7 -0
  1090. package/dist/utils/listItems.js +9 -0
  1091. package/dist/utils/mergeDocumentContent.d.ts +7 -0
  1092. package/dist/utils/mergeDocumentContent.js +2 -2
  1093. package/dist/utils/outlineHeadings.d.ts +1 -1
  1094. package/dist/utils/paintedPositions.d.ts +60 -0
  1095. package/dist/utils/paintedPositions.js +101 -0
  1096. package/dist/utils/paragraphFormattingMerge.d.ts +11 -3
  1097. package/dist/utils/paragraphFormattingMerge.js +0 -8
  1098. package/dist/utils/paragraphInlineLayout.js +2 -1
  1099. package/dist/utils/repeatingStrokeGradient.d.ts +8 -0
  1100. package/dist/utils/repeatingStrokeGradient.js +13 -0
  1101. package/dist/utils/rotationBoundingBox.d.ts +8 -0
  1102. package/dist/utils/rulerControl.d.ts +71 -0
  1103. package/dist/utils/rulerControl.js +94 -0
  1104. package/dist/utils/tableOperations.d.ts +20 -4
  1105. package/dist/utils/tableOperations.js +1 -0
  1106. package/dist/utils/textDirectionFlow.d.ts +10 -0
  1107. package/dist/utils/textFormattingMerge.d.ts +18 -2
  1108. package/dist/utils/textFormattingMerge.js +0 -20
  1109. package/dist/utils/units.d.ts +2 -0
  1110. package/dist/utils/units.js +3 -1
  1111. package/dist/version-comparison.d.ts +63 -1
  1112. package/dist/version-comparison.js +2 -1
  1113. package/dist/watermark/index.d.ts +11 -0
  1114. package/dist/watermark/index.js +0 -5
  1115. package/package.json +7 -8
  1116. package/dist/controller/canonicalLockGuard.d.ts +0 -8
  1117. package/dist/controller/canonicalLockGuard.js +0 -88
  1118. package/dist/controller/canonicalPublicOperations.js +0 -900
  1119. package/dist/controller/canonicalSession.d.ts +0 -256
  1120. package/dist/controller/canonicalSession.js +0 -1717
  1121. package/dist/docx/canonicalResourceSave.d.ts +0 -15
  1122. package/dist/docx/canonicalResourceSave.js +0 -27
  1123. package/dist/internal/acceptedBlockProjection.d.ts +0 -9
  1124. package/dist/internal/acceptedBlockProjection.js +0 -50
  1125. package/dist/prosemirror/plugins/anonymizationDecorations.d.ts +0 -60
  1126. package/dist/prosemirror/plugins/anonymizationDecorations.js +0 -111
  1127. package/dist/prosemirror/plugins/autocompleteSuggestion.d.ts +0 -127
  1128. package/dist/prosemirror/plugins/autocompleteSuggestion.js +0 -282
  1129. package/dist/utils/replaceText.d.ts +0 -25
  1130. package/dist/utils/replaceText.js +0 -242
  1131. /package/dist/{controller → canonical}/canonicalListRendering.d.ts +0 -0
  1132. /package/dist/{controller → canonical}/canonicalOperations.d.ts +0 -0
  1133. /package/dist/{controller → canonical}/canonicalSelection.d.ts +0 -0
  1134. /package/dist/{controller → canonical}/canonicalTocSelection.d.ts +0 -0
@@ -0,0 +1,2892 @@
1
+ import { splitsGraphemeCluster, splitsSurrogatePair } from "../ai-edits/character-boundaries.js";
2
+ import { getTrackedChangeGroupsForIds } from "../ai-edits/read.js";
3
+ import { CommentMarkerCache, paragraphCommentMarkers, positionedCommentGaps, visitCommentMarkerItems } from "../docx/commentAnchorIndex.js";
4
+ import { copyHeaderFooterBaselineHandles, getDocumentSourceBaseline } from "../docx/headerFooterVerbatim.js";
5
+ import { ListNormalizationCache } from "../docx/listModelNormalization.js";
6
+ import { cloneDocumentWithParagraphPropertySources, getProseParagraphPropertySourceToken, markParagraphPropertySourceTransfers } from "../docx/paragraphPropertySource.js";
7
+ import { visitInlineContentSlots } from "../docx/paragraphTraversal.js";
8
+ import { isCellMergeContinuation } from "../docx/tableParser.js";
9
+ import { referencedHeaderFooters, retiredHeaderFooters } from "../docx/unreferencedHeaderFooters.js";
10
+ import { calculateRowSpans } from "../docx/verticalMergeProjection.js";
11
+ import { canonicalOperationStagingAccess } from "../internal/canonicalOperationStaging.js";
12
+ import { recordCanonicalTyping } from "../internal/canonicalTyping.js";
13
+ import { canonicalCellSelectionRanges, canonicalContentPosition, canonicalSelectionRange } from "../prosemirror/canonicalSelectionRange.js";
14
+ import { expectCommentRangeBoundaryAttrs } from "../prosemirror/commentRangeBoundaryAttrs.js";
15
+ import { storyConversionOptions } from "../prosemirror/conversion/storyConversionOptions.js";
16
+ import { ProjectionBlockCache, collectPairedBookmarkIds, footnoteToProseDoc, headerFooterToProseDoc, toProseDoc } from "../prosemirror/conversion/toProseDoc.js";
17
+ import { heldUnreferencedNotes } from "../prosemirror/noteReferenceReview.js";
18
+ import { preservesReplacementCommentAlignment } from "../prosemirror/replacedAnnotations.js";
19
+ import { runFormattingPatchFromMarks } from "../prosemirror/runFormattingFromMarks.js";
20
+ import { CANONICAL_GAP, CANONICAL_RULE } from "../types/canonicalCapabilities.js";
21
+ import { canonicalJson } from "../utils/canonicalJson.js";
22
+ import { itemBefore } from "../utils/listItems.js";
23
+ import { CanonicalIdLease } from "./canonicalIdLease.js";
24
+ import { InlineProjectionCache, canonicalNativeCells, projectCanonicalInline } from "./canonicalInlineProjection.js";
25
+ import { normalizeCanonicalListRendering } from "./canonicalListRendering.js";
26
+ import { lockViolationBetween } from "./canonicalLockGuard.js";
27
+ import { ParagraphIdIndex, sameIdOrder, storyFactContributions } from "./canonicalProjectionBlocks.js";
28
+ import { rebaseHistorySteps, remoteSelection } from "./canonicalRemoteHistory.js";
29
+ import { canonicalRevisionLocks } from "./canonicalRevisionLocks.js";
30
+ import { changedWindow, unsupportedEditReason, unsupportedSeedReason } from "./canonicalSeedContent.js";
31
+ import { restoreCanonicalSelection } from "./canonicalSelection.js";
32
+ import { canonicalSourceRestores, normalizeCanonicalSource, withUneditedSourceRestored } from "./canonicalSourceNormalization.js";
33
+ import { mapTocSelection } from "./canonicalTocSelection.js";
34
+ import { controlEdgesAt } from "./controlEdges.js";
35
+ import { ownedSourceCopies, preservePropertySources, preservePropertySourcesWholeStories } from "./propertySourcePreservation.js";
36
+ import { Result, TaggedError, panic } from "better-result";
37
+ import { hasIllegalXmlCharacters } from "@stll/docx-core";
38
+ import { lockedControlMessage } from "@stll/docx-core/model";
39
+ import { Fragment } from "prosemirror-model";
40
+ import { CellSelection } from "prosemirror-tables";
41
+ import { DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_TYPES, ID_LEASE_KINDS, OP_STORIES, applyDocumentOp, applyDocumentOps, combineEdits, combineRecordedRevisions, compileEditorIntent, createEditorIntentIdAllocator, documentStories, editorParagraphGroups, findStoryBody, formatParaId, freshLeasedIds, inverseMeetingDocument, isBlockBoundary, normalizeForOps, packageParagraphIds, paragraphIdsIn, paragraphsThroughTextBoxes, planWholeParagraphReplacement, sameStory, suggestedCommentIds, suggestionRevisionInfos, survivingComments, validateOpsDocument, withParagraphCopies } from "@stll/docx-core/ops";
42
+ import { AllSelection, NodeSelection, Selection, TextSelection } from "prosemirror-state";
43
+ // src/canonical/canonicalSession.ts
44
+ const CanonicalSessionErrorBase = TaggedError("CanonicalSessionError");
45
+ 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({
53
+ ground,
54
+ message,
55
+ reason: "refused"
56
+ }));
57
+ /** A change a content control's lock forbids: the document's rule, not a gap. */
58
+ const lockRefusal = (violation) => Result.err(new CanonicalSessionError({
59
+ ground: { rule: CANONICAL_RULE.contentControlLock },
60
+ message: `Refused: ${lockedControlMessage(violation)}`,
61
+ reason: "refused"
62
+ }));
63
+ const noChange = (message) => Result.err(new CanonicalSessionError({
64
+ ground: { gap: CANONICAL_GAP.dispatch },
65
+ message,
66
+ reason: "noChange"
67
+ }));
68
+ /**
69
+ * 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.
73
+ */
74
+ const intentRefusal = (intent, mode, { reason, message }) => {
75
+ 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
+ }));
97
+ };
98
+ const COMMENT_OPERATION_TYPES = /* @__PURE__ */ new Set([
99
+ DOCUMENT_OP_TYPES.CREATE_COMMENT,
100
+ DOCUMENT_OP_TYPES.UPDATE_COMMENT_CONTENT,
101
+ DOCUMENT_OP_TYPES.SET_COMMENT_RESOLUTION,
102
+ DOCUMENT_OP_TYPES.DELETE_COMMENT,
103
+ DOCUMENT_OP_TYPES.RESTORE_COMMENT_STATE
104
+ ]);
105
+ /** The story an operation edits, or null for one that edits the package. */
106
+ const operationStory = (op) => {
107
+ switch (op.type) {
108
+ case DOCUMENT_OP_TYPES.CREATE_COMMENT:
109
+ case DOCUMENT_OP_TYPES.UPDATE_COMMENT_CONTENT:
110
+ case DOCUMENT_OP_TYPES.SET_COMMENT_RESOLUTION:
111
+ case DOCUMENT_OP_TYPES.DELETE_COMMENT:
112
+ case DOCUMENT_OP_TYPES.RESTORE_COMMENT_STATE:
113
+ case DOCUMENT_OP_TYPES.CREATE_HEADER_FOOTER:
114
+ case DOCUMENT_OP_TYPES.REMOVE_HEADER_FOOTER:
115
+ case DOCUMENT_OP_TYPES.ADD_NOTE:
116
+ case DOCUMENT_OP_TYPES.REMOVE_NOTE:
117
+ case DOCUMENT_OP_TYPES.SET_SECTION_PROPS:
118
+ case DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS:
119
+ case DOCUMENT_OP_TYPES.SET_PACKAGE_RESOURCES:
120
+ case DOCUMENT_OP_TYPES.CREATE_NUMBERING_INSTANCE:
121
+ case DOCUMENT_OP_TYPES.DELETE_NUMBERING_INSTANCE:
122
+ case DOCUMENT_OP_TYPES.SET_SECTION_ENDPOINT: return null;
123
+ default:
124
+ if ("story" in op) return op.story;
125
+ if ("at" in op) return op.at.story;
126
+ if ("from" in op) return op.from.story;
127
+ return op;
128
+ }
129
+ };
130
+ /**
131
+ * An edit inside a header or footer: the selective save writes every header
132
+ * and footer part whole, and declines one that needs a resource of its own,
133
+ * so the edit leaves the body's paragraph splice standing.
134
+ */
135
+ const editsHeaderFooter = (op) => {
136
+ const story = operationStory(op);
137
+ return story !== null && story !== OP_STORIES.MAIN && (story.kind === "header" || story.kind === "footer");
138
+ };
139
+ const operationChangesPackage = (op) => {
140
+ const story = operationStory(op);
141
+ return story === null || !sameStory(story, OP_STORIES.MAIN) && !editsHeaderFooter(op);
142
+ };
143
+ const operationChangesStructure = (op) => {
144
+ switch (op.type) {
145
+ case DOCUMENT_OP_TYPES.DELETE_BLOCKS:
146
+ case DOCUMENT_OP_TYPES.INSERT_BLOCKS:
147
+ case DOCUMENT_OP_TYPES.SPLIT_BLOCK:
148
+ case DOCUMENT_OP_TYPES.JOIN_BLOCKS:
149
+ case DOCUMENT_OP_TYPES.REPLACE_BLOCKS:
150
+ case DOCUMENT_OP_TYPES.INSERT_TABLE:
151
+ case DOCUMENT_OP_TYPES.DELETE_TABLE:
152
+ case DOCUMENT_OP_TYPES.SET_CONTAINER_BLOCKS:
153
+ case DOCUMENT_OP_TYPES.INSERT_ROW:
154
+ case DOCUMENT_OP_TYPES.DELETE_ROW:
155
+ case DOCUMENT_OP_TYPES.SET_TABLE_ROWS:
156
+ case DOCUMENT_OP_TYPES.INSERT_COLUMN:
157
+ case DOCUMENT_OP_TYPES.DELETE_COLUMN:
158
+ case DOCUMENT_OP_TYPES.MERGE_CELLS:
159
+ case DOCUMENT_OP_TYPES.SPLIT_CELL:
160
+ case DOCUMENT_OP_TYPES.SET_TABLE:
161
+ case DOCUMENT_OP_TYPES.RESOLVE_REVISION:
162
+ case DOCUMENT_OP_TYPES.SET_TABLE_GRID:
163
+ case DOCUMENT_OP_TYPES.SET_CELL_PROPS:
164
+ case DOCUMENT_OP_TYPES.SET_ROW_PROPS:
165
+ case DOCUMENT_OP_TYPES.SET_TABLE_PROPS:
166
+ case DOCUMENT_OP_TYPES.SET_REVISION_INFO:
167
+ case DOCUMENT_OP_TYPES.SET_CONTENT_CONTROL: return true;
168
+ case DOCUMENT_OP_TYPES.CREATE_HEADER_FOOTER:
169
+ case DOCUMENT_OP_TYPES.REMOVE_HEADER_FOOTER:
170
+ case DOCUMENT_OP_TYPES.ADD_NOTE:
171
+ case DOCUMENT_OP_TYPES.REMOVE_NOTE:
172
+ case DOCUMENT_OP_TYPES.SET_SECTION_PROPS:
173
+ case DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS:
174
+ case DOCUMENT_OP_TYPES.SET_PACKAGE_RESOURCES:
175
+ case DOCUMENT_OP_TYPES.CREATE_NUMBERING_INSTANCE:
176
+ case DOCUMENT_OP_TYPES.DELETE_NUMBERING_INSTANCE:
177
+ case DOCUMENT_OP_TYPES.SET_SECTION_ENDPOINT: return true;
178
+ case DOCUMENT_OP_TYPES.INSERT_TEXT:
179
+ case DOCUMENT_OP_TYPES.INSERT_CONTENT:
180
+ case DOCUMENT_OP_TYPES.DELETE_RANGE:
181
+ case DOCUMENT_OP_TYPES.SPLIT_INLINE:
182
+ case DOCUMENT_OP_TYPES.JOIN_INLINE:
183
+ case DOCUMENT_OP_TYPES.SET_RUN_PROPS:
184
+ case DOCUMENT_OP_TYPES.SET_PARAGRAPH_PROPS:
185
+ case DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW:
186
+ case DOCUMENT_OP_TYPES.REPLACE_INLINE:
187
+ case DOCUMENT_OP_TYPES.CREATE_COMMENT:
188
+ case DOCUMENT_OP_TYPES.UPDATE_COMMENT_CONTENT:
189
+ case DOCUMENT_OP_TYPES.SET_COMMENT_RESOLUTION:
190
+ case DOCUMENT_OP_TYPES.DELETE_COMMENT:
191
+ case DOCUMENT_OP_TYPES.RESTORE_COMMENT_STATE: return false;
192
+ default: return op;
193
+ }
194
+ };
195
+ const operationChangesBodyProjection = (op) => {
196
+ switch (op.type) {
197
+ case DOCUMENT_OP_TYPES.CREATE_COMMENT:
198
+ case DOCUMENT_OP_TYPES.UPDATE_COMMENT_CONTENT:
199
+ case DOCUMENT_OP_TYPES.SET_COMMENT_RESOLUTION:
200
+ case DOCUMENT_OP_TYPES.DELETE_COMMENT:
201
+ case DOCUMENT_OP_TYPES.RESTORE_COMMENT_STATE:
202
+ case DOCUMENT_OP_TYPES.CREATE_HEADER_FOOTER:
203
+ case DOCUMENT_OP_TYPES.REMOVE_HEADER_FOOTER:
204
+ case DOCUMENT_OP_TYPES.ADD_NOTE:
205
+ case DOCUMENT_OP_TYPES.REMOVE_NOTE:
206
+ case DOCUMENT_OP_TYPES.SET_SECTION_PROPS:
207
+ case DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS:
208
+ case DOCUMENT_OP_TYPES.SET_PACKAGE_RESOURCES:
209
+ case DOCUMENT_OP_TYPES.CREATE_NUMBERING_INSTANCE:
210
+ case DOCUMENT_OP_TYPES.DELETE_NUMBERING_INSTANCE:
211
+ case DOCUMENT_OP_TYPES.SET_SECTION_ENDPOINT: return true;
212
+ default:
213
+ if ("story" in op) return sameStory(op.story, OP_STORIES.MAIN);
214
+ if ("at" in op) return sameStory(op.at.story, OP_STORIES.MAIN);
215
+ if ("from" in op) return sameStory(op.from.story, OP_STORIES.MAIN);
216
+ return op;
217
+ }
218
+ };
219
+ const CANONICAL_PROJECTION_META = "folioCanonicalProjection";
220
+ /** Paragraph gaps bind logical units and source zero-width ordinals to PM positions. */
221
+ var CanonicalProjection = class CanonicalProjection {
222
+ doc;
223
+ story;
224
+ content;
225
+ blocks;
226
+ index;
227
+ facts;
228
+ reusable;
229
+ /** Where each top-level node starts. */
230
+ starts;
231
+ addresses;
232
+ constructor(options, held) {
233
+ this.doc = options.doc;
234
+ this.story = options.story;
235
+ this.content = options.content;
236
+ this.blocks = options.blocks;
237
+ this.index = options.index;
238
+ this.facts = options.facts;
239
+ this.reusable = options.reusable;
240
+ this.addresses = held?.addresses ?? /* @__PURE__ */ new Map();
241
+ if (held !== void 0) {
242
+ this.starts = held.starts;
243
+ return;
244
+ }
245
+ const starts = [];
246
+ let position = 0;
247
+ for (let child = 0; child < this.doc.childCount; child += 1) {
248
+ starts.push(position);
249
+ position += this.doc.child(child).nodeSize;
250
+ }
251
+ this.starts = starts;
252
+ }
253
+ /**
254
+ * The same projection held as `doc`, a document equal to this one's. A
255
+ * commit's transaction ends on a document equal to the projection it staged,
256
+ * sharing the blocks it left; holding that document lets the next commit see
257
+ * the state it was given is the projection without comparing every node.
258
+ */
259
+ heldAs(doc) {
260
+ return new CanonicalProjection({
261
+ doc,
262
+ story: this.story,
263
+ content: this.content,
264
+ blocks: this.blocks,
265
+ index: this.index,
266
+ facts: this.facts,
267
+ reusable: this.reusable
268
+ }, {
269
+ starts: this.starts,
270
+ addresses: this.addresses
271
+ });
272
+ }
273
+ addressOf(block, paragraph) {
274
+ const entry = this.blocks[block]?.paragraphs[paragraph] ?? panic("Missing canonical paragraph");
275
+ const known = this.addresses.get(entry.blockId);
276
+ if (known !== void 0) return known;
277
+ const address = {
278
+ blockId: entry.blockId,
279
+ container: entry.container ?? this.content,
280
+ start: (this.starts[block] ?? panic("Missing block start")) + entry.offset,
281
+ text: entry.inline.text,
282
+ boundaries: entry.inline.boundaries,
283
+ seams: entry.inline.seams,
284
+ node: entry.node,
285
+ source: entry.source
286
+ };
287
+ this.addresses.set(entry.blockId, address);
288
+ return address;
289
+ }
290
+ /** The paragraph whose content holds `position`, its ends included. */
291
+ /** Whether `position` lies in a text box's content. */
292
+ insideTextBox(position) {
293
+ const resolved = this.doc.resolve(Math.max(0, Math.min(position, this.doc.content.size)));
294
+ for (let depth = resolved.depth; depth > 0; depth -= 1) if (resolved.node(depth).type.name === "textBox") return true;
295
+ return false;
296
+ }
297
+ paragraphAround(position) {
298
+ let low = 0;
299
+ let high = this.starts.length - 1;
300
+ let block = -1;
301
+ while (low <= high) {
302
+ const middle = low + high >> 1;
303
+ if ((this.starts[middle] ?? 0) < position) {
304
+ block = middle;
305
+ low = middle + 1;
306
+ } else high = middle - 1;
307
+ }
308
+ const paragraphs = this.blocks[block]?.paragraphs;
309
+ if (paragraphs === void 0) return void 0;
310
+ const relative = position - (this.starts[block] ?? 0);
311
+ low = 0;
312
+ high = paragraphs.length - 1;
313
+ let found = -1;
314
+ while (low <= high) {
315
+ const middle = low + high >> 1;
316
+ if ((paragraphs[middle]?.offset ?? 0) <= relative) {
317
+ found = middle;
318
+ low = middle + 1;
319
+ } else high = middle - 1;
320
+ }
321
+ const paragraph = paragraphs[found];
322
+ if (paragraph === void 0 || relative > paragraph.offset + paragraph.node.content.size) return void 0;
323
+ return this.addressOf(block, found);
324
+ }
325
+ addressAt(position, edge = "caret") {
326
+ if (!Number.isInteger(position)) return refuse("The input position is not an integer.");
327
+ position = canonicalContentPosition(this.doc, position);
328
+ const paragraph = this.paragraphAround(position);
329
+ if (paragraph === void 0) return this.insideTextBox(position) ? refuseUnder({ gap: CANONICAL_GAP.publicUnsupportedInline }, "The canonical session holds no address in this paragraph, such as one in a text box.") : refuse("The input is outside a plain paragraph.");
330
+ const relative = position - paragraph.start;
331
+ const offset = paragraph.boundaries.findIndex((gaps) => gaps.some((gap) => gap.position === relative));
332
+ if (offset < 0) return refuse("The input splits an indivisible inline element.");
333
+ if (splitsSurrogatePair(paragraph.text, offset)) return refuse("The input would split a surrogate pair.");
334
+ const gaps = paragraph.boundaries.at(offset) ?? panic("Missing canonical boundary");
335
+ const index = gaps.findIndex((entry) => entry.position === relative);
336
+ const gap = gaps[index] ?? panic("Missing canonical native gap");
337
+ const seam = paragraph.seams.at(offset)?.[index] ?? panic("Missing canonical seam");
338
+ let ordinal = gap.zeroWidthBefore;
339
+ if (edge === "afterMarkers") ordinal = seam.last;
340
+ if (edge === "beforeMarkers") ordinal = seam.first;
341
+ return Result.ok({
342
+ story: this.story,
343
+ blockId: paragraph.blockId,
344
+ offset,
345
+ ...gaps.length > 1 || ordinal > 0 || seam.first !== seam.last ? { zeroWidthBefore: ordinal } : {}
346
+ });
347
+ }
348
+ /**
349
+ * The source gaps a selection from `from` to `to` replaces between. Its
350
+ * edges stay inside the markers beside them, so replacing exactly the
351
+ * words a comment covers keeps the comment on the new text. A selection of
352
+ * a paragraph's whole text takes that paragraph's markers with it: an edge
353
+ * at the very start of a paragraph whose text the selection covers to its
354
+ * end reaches before the markers there, and an edge at the very end of a
355
+ * paragraph the selection covers from its start reaches after them, so a
356
+ * comment on nothing but the replaced text is emptied, as removing the
357
+ * text would empty it.
358
+ */
359
+ rangeEdgesAt(from, to) {
360
+ const paragraphOf = (position) => this.paragraphAround(canonicalContentPosition(this.doc, position));
361
+ const first = paragraphOf(from);
362
+ const last = paragraphOf(to);
363
+ const startsWhole = first !== void 0 && canonicalContentPosition(this.doc, from) === first.start && canonicalContentPosition(this.doc, to) >= first.start + first.node.content.size;
364
+ const endsWhole = last !== void 0 && canonicalContentPosition(this.doc, to) === last.start + last.node.content.size && canonicalContentPosition(this.doc, from) <= last.start;
365
+ return {
366
+ start: startsWhole ? "beforeMarkers" : "afterMarkers",
367
+ end: endsWhole ? "afterMarkers" : "beforeMarkers"
368
+ };
369
+ }
370
+ inputAddressAt(position, edge = "caret") {
371
+ const address = this.addressAt(position, edge);
372
+ if (address.isErr()) return address;
373
+ const paragraph = this.paragraph(address.value.blockId);
374
+ if (paragraph === void 0) panic("Input lost its paragraph.");
375
+ let destination = position;
376
+ paragraph.node.forEach((node, start) => {
377
+ if (node.marks.some((mark) => mark.type.name === "deletion") && destination > paragraph.start + start && destination < paragraph.start + start + node.nodeSize) destination = paragraph.start + start + node.nodeSize;
378
+ });
379
+ return destination === position ? address : this.addressAt(destination, edge);
380
+ }
381
+ positionAt(address) {
382
+ const paragraph = this.paragraph(address.blockId);
383
+ if (!sameStory(address.story, this.story) || paragraph === void 0 || !Number.isInteger(address.offset) || address.offset < 0 || address.offset > paragraph.text.length || splitsSurrogatePair(paragraph.text, address.offset)) return refuse("The canonical selection is outside a plain paragraph.");
384
+ const gaps = paragraph.boundaries.at(address.offset) ?? panic("Missing canonical boundary");
385
+ const seams = paragraph.seams.at(address.offset) ?? panic("Missing canonical seams");
386
+ const lastOrdinal = (seams.at(-1) ?? panic("Missing canonical seam")).last;
387
+ const ordinal = address.zeroWidthBefore ?? lastOrdinal;
388
+ const gap = gaps.find(({ zeroWidthBefore }) => zeroWidthBefore === ordinal) ?? gaps.find((_, index) => {
389
+ const seam = seams[index];
390
+ return seam !== void 0 && seam.first <= ordinal && ordinal <= seam.last;
391
+ });
392
+ if (!Number.isInteger(ordinal) || ordinal < 0 || ordinal > lastOrdinal) return refuse("The canonical selection is outside a paragraph gap.");
393
+ if (gap === void 0) return refuse("This source gap is inside a collapsed or erased inline boundary and has no editor position.");
394
+ return Result.ok(paragraph.start + gap.position);
395
+ }
396
+ selectionAt(state) {
397
+ const selection = state.selection;
398
+ let type;
399
+ let anchorPosition = selection.anchor;
400
+ let headPosition = selection.head;
401
+ if (selection instanceof TextSelection) type = "text";
402
+ else if (selection instanceof CellSelection) {
403
+ type = "cell";
404
+ anchorPosition = Selection.atStart(selection.$anchorCell.nodeAfter ?? panic("Missing anchor cell")).from + selection.$anchorCell.pos + 1;
405
+ headPosition = Selection.atEnd(selection.$headCell.nodeAfter ?? panic("Missing head cell")).to + selection.$headCell.pos + 1;
406
+ } else if (selection instanceof NodeSelection && selection.node.isInline && selection.node.isAtom && selection.node.type.name !== "noteMarker") type = "inlineNode";
407
+ else if (selection instanceof AllSelection) {
408
+ type = "all";
409
+ const range = canonicalSelectionRange(state);
410
+ anchorPosition = range.from;
411
+ headPosition = range.to;
412
+ } else return refuse("Canonical input requires text, an inline atom, or the whole document selection.");
413
+ const anchor = this.addressAt(anchorPosition);
414
+ if (anchor.isErr()) return anchor;
415
+ const head = this.addressAt(headPosition);
416
+ if (head.isErr()) return head;
417
+ return Result.ok({
418
+ type,
419
+ anchor: anchor.value,
420
+ head: head.value
421
+ });
422
+ }
423
+ /** The first paragraph the projection addresses, in document order. */
424
+ get firstParagraph() {
425
+ const block = this.blocks.findIndex(({ paragraphs }) => paragraphs.length > 0);
426
+ return block < 0 ? void 0 : this.addressOf(block, 0);
427
+ }
428
+ paragraph(blockId) {
429
+ const slot = this.index.get(blockId);
430
+ if (slot === void 0 || slot.paragraph < 0) return void 0;
431
+ return this.addressOf(slot.block, slot.paragraph);
432
+ }
433
+ /** The paragraph whose node starts at `before`. */
434
+ paragraphStartingAt(before) {
435
+ const paragraph = this.paragraphAround(before + 1);
436
+ return paragraph?.start === before + 1 ? paragraph : void 0;
437
+ }
438
+ nextParagraphInContainer(blockId) {
439
+ const slot = this.index.get(blockId);
440
+ if (slot === void 0 || slot.paragraph < 0) return void 0;
441
+ const paragraph = this.addressOf(slot.block, slot.paragraph);
442
+ const index = paragraph.container.indexOf(paragraph.source);
443
+ if (index >= 0) {
444
+ let at = index + 1;
445
+ while (paragraph.source.sectionProperties === void 0 && paragraph.container[at] !== void 0 && isBlockBoundary(paragraph.container[at] ?? panic("A block is listed."))) at += 1;
446
+ const following = paragraph.container[at];
447
+ if (following?.type !== "paragraph" || following.paraId === void 0) return void 0;
448
+ const address = this.paragraph(following.paraId);
449
+ return address?.container === paragraph.container ? address : void 0;
450
+ }
451
+ let block = slot.block;
452
+ let next = slot.paragraph + 1;
453
+ while (block < this.blocks.length && next >= (this.blocks[block]?.paragraphs.length ?? 0)) {
454
+ block += 1;
455
+ next = 0;
456
+ }
457
+ if (block >= this.blocks.length) return void 0;
458
+ const following = this.addressOf(block, next);
459
+ return paragraph.container === following.container ? following : void 0;
460
+ }
461
+ };
462
+ /** Immutable operations retain content identities for every untouched story. */
463
+ const changedStories = ({ document, previous }) => {
464
+ const stories = [];
465
+ if (document.package.document.content !== previous.package.document.content) stories.push(OP_STORIES.MAIN);
466
+ for (const kind of ["header", "footer"]) {
467
+ const parts = kind === "header" ? document.package.headers : document.package.footers;
468
+ const prior = kind === "header" ? previous.package.headers : previous.package.footers;
469
+ if (parts === prior) continue;
470
+ for (const [rId, body] of parts ?? []) if (body.content !== prior?.get(rId)?.content) stories.push({
471
+ kind,
472
+ rId
473
+ });
474
+ }
475
+ for (const kind of ["footnote", "endnote"]) {
476
+ const notes = kind === "footnote" ? document.package.footnotes : document.package.endnotes;
477
+ const prior = kind === "footnote" ? previous.package.footnotes : previous.package.endnotes;
478
+ if (notes === prior) continue;
479
+ const priorById = new Map(prior?.map((note) => [note.id, note]));
480
+ for (const note of notes ?? []) {
481
+ const original = priorById.get(note.id);
482
+ if (note.content !== original?.content || note.noteType !== original?.noteType) stories.push({
483
+ kind,
484
+ id: note.id
485
+ });
486
+ }
487
+ }
488
+ return stories;
489
+ };
490
+ const newStoryProjectionCaches = () => ({
491
+ blocks: new ProjectionBlockCache(),
492
+ inline: new InlineProjectionCache(),
493
+ lists: new ListNormalizationCache(),
494
+ comments: new CommentMarkerCache()
495
+ });
496
+ /** Whether a paragraph anchors a text box, which converts to a block of its own. */
497
+ const holdsTextBox = (paragraph) => {
498
+ let found = false;
499
+ visitInlineContentSlots(paragraph, ({ item }) => {
500
+ if (item.type === "run" && item.content.some((content) => content.type === "shape" && content.shape.textBody !== void 0)) found = true;
501
+ });
502
+ return found;
503
+ };
504
+ /**
505
+ * The selection a publish shows, read back as addresses, with the
506
+ * transaction's text selection moved to exactly where those addresses place
507
+ * it. Undo and redo restore a selection by its addresses, so a publish must
508
+ * show the position its address gives back: one of several editor positions
509
+ * an address names (either side of a link's edge) becomes the one restoring
510
+ * gives, and a position no address names (inside a character, or where an
511
+ * unplaceable selection fell back) moves to the nearest one that has one.
512
+ */
513
+ const placeShownSelection = (transaction, projection) => {
514
+ const current = transaction.selection;
515
+ if (current instanceof TextSelection) {
516
+ const size = transaction.doc.content.size;
517
+ const nearestAddressable = (position) => {
518
+ for (let distance = 0; distance <= size; distance += 1) for (const candidate of [position - distance, position + distance]) if (candidate >= 0 && candidate <= size && projection.addressAt(candidate).isOk()) return candidate;
519
+ };
520
+ const anchor = nearestAddressable(current.anchor);
521
+ const head = nearestAddressable(current.head);
522
+ if (anchor === void 0 || head === void 0) return void 0;
523
+ const addressed = {
524
+ anchor: projection.addressAt(anchor).unwrap(),
525
+ head: projection.addressAt(head).unwrap()
526
+ };
527
+ const placed = {
528
+ anchor: projection.positionAt(addressed.anchor),
529
+ head: projection.positionAt(addressed.head)
530
+ };
531
+ if (placed.anchor.isErr() || placed.head.isErr()) return void 0;
532
+ if (placed.anchor.value !== current.anchor || placed.head.value !== current.head) transaction.setSelection(TextSelection.create(transaction.doc, placed.anchor.value, placed.head.value));
533
+ return {
534
+ type: "text",
535
+ ...addressed
536
+ };
537
+ }
538
+ const read = projection.selectionAt(transaction);
539
+ return read.isOk() ? read.value : void 0;
540
+ };
541
+ const structureRefusal = () => new CanonicalSessionError({
542
+ ground: { gap: CANONICAL_GAP.storyContentProjection },
543
+ reason: "refused",
544
+ message: "The projection changed paragraph structure."
545
+ });
546
+ /**
547
+ * Every paragraph a projection addresses or skips under `blocks`, with
548
+ * whether it lies in a merged cell's skipped continuation, in document order.
549
+ */
550
+ const visitSourceParagraphs = (blocks, visit, insideSkippedContinuation = false) => {
551
+ for (const block of blocks) visitBlockSources(block, blocks, visit, insideSkippedContinuation);
552
+ };
553
+ const visitBlockSources = (block, container, visit, insideSkippedContinuation) => {
554
+ if (block.type === "paragraph") {
555
+ visit(block, container, insideSkippedContinuation);
556
+ return;
557
+ }
558
+ if (block.type === "blockSdt" || block.type === "blockCustomXml") {
559
+ visitSourceParagraphs(block.content, visit, insideSkippedContinuation);
560
+ return;
561
+ }
562
+ if (block.type !== "table") return;
563
+ const rowSpans = calculateRowSpans(block);
564
+ for (const [rowIndex, row] of block.rows.entries()) {
565
+ let column = row.formatting?.gridBefore ?? 0;
566
+ for (const cell of row.cells) {
567
+ const skippedContinuation = isCellMergeContinuation(cell) && (rowSpans.get(`${rowIndex}-${column}`)?.skip ?? false);
568
+ visitSourceParagraphs(cell.content, visit, insideSkippedContinuation || skippedContinuation);
569
+ column += cell.formatting?.gridSpan ?? 1;
570
+ }
571
+ }
572
+ };
573
+ /** The paragraphs of the text boxes a paragraph draws, those inside them included. */
574
+ const visitTextBoxSources = (paragraph, visit) => {
575
+ visitInlineContentSlots(paragraph, ({ item }) => {
576
+ if (item.type !== "run") return;
577
+ for (const content of item.content) if (content.type === "shape" && content.shape.textBody !== void 0) visitSourceParagraphs(content.shape.textBody.content, (source, container) => {
578
+ visit(source, container);
579
+ visitTextBoxSources(source, visit);
580
+ });
581
+ });
582
+ };
583
+ const collectSources = (content, start, end, takenElsewhere) => {
584
+ const found = {
585
+ located: /* @__PURE__ */ new Map(),
586
+ boxed: /* @__PURE__ */ new Map(),
587
+ idsByBlock: [],
588
+ all: [],
589
+ continuation: /* @__PURE__ */ new Set(),
590
+ repeated: false
591
+ };
592
+ const at = {
593
+ top: start,
594
+ ids: []
595
+ };
596
+ const visit = (source, container, continuation) => {
597
+ found.all.push(source);
598
+ visitTextBoxSources(source, (boxed, boxContent) => {
599
+ if (boxed.paraId !== void 0 && !found.boxed.has(boxed.paraId)) found.boxed.set(boxed.paraId, {
600
+ source: boxed,
601
+ container: boxContent,
602
+ top: at.top
603
+ });
604
+ });
605
+ if (continuation) found.continuation.add(source);
606
+ if (source.paraId === void 0) return;
607
+ if (found.located.has(source.paraId) || takenElsewhere(source.paraId)) found.repeated = true;
608
+ found.located.set(source.paraId, {
609
+ source,
610
+ container,
611
+ top: at.top
612
+ });
613
+ at.ids.push(source.paraId);
614
+ };
615
+ for (let top = start; top < end; top += 1) {
616
+ at.top = top;
617
+ at.ids = [];
618
+ found.idsByBlock.push(at.ids);
619
+ visitBlockSources(content[top] ?? panic("Missing story block"), content, visit, false);
620
+ }
621
+ return found;
622
+ };
623
+ /** The comment ranges open as a walk goes, with a copy kept while they stay the same. */
624
+ var OpenComments = class {
625
+ ids;
626
+ kept;
627
+ constructor(open) {
628
+ this.ids = new Set(open);
629
+ this.kept = open;
630
+ }
631
+ /** The open ranges now, in their set's order. */
632
+ get current() {
633
+ let same = this.kept.length === this.ids.size;
634
+ let at = 0;
635
+ for (const id of this.ids) {
636
+ if (!same) break;
637
+ same = this.kept[at] === id;
638
+ at += 1;
639
+ }
640
+ if (!same) this.kept = [...this.ids];
641
+ return this.kept;
642
+ }
643
+ };
644
+ /**
645
+ * The paragraphs of a text box's editor node, addressed as its story's
646
+ * paragraphs. A paragraph the session cannot place in the box's source (one
647
+ * the conversion drew without it) gets no address, so input there refuses
648
+ * and the box keeps its source as it was.
649
+ */
650
+ const projectTextBoxParagraphs = ({ box, offset, walk, paragraphs }) => {
651
+ const open = new OpenComments([]);
652
+ const commentContext = {
653
+ rangedIds: walk.facts.rangedIds,
654
+ pointIds: walk.facts.pointIds,
655
+ openIds: open.ids
656
+ };
657
+ box.descendants((node, childOffset) => {
658
+ if (node.type.name !== "paragraph") return true;
659
+ const paraId = node.attrs["paraId"];
660
+ const located = typeof paraId === "string" ? walk.locateBoxed(paraId) : void 0;
661
+ if (typeof paraId !== "string" || located === void 0 || !walk.takeBoxed(located.source)) return false;
662
+ const inlineArgs = {
663
+ source: located.source,
664
+ paragraph: node,
665
+ pairedBookmarkIds: walk.facts.pairedBookmarkIds,
666
+ commentContext
667
+ };
668
+ const inline = walk.inline === void 0 ? projectCanonicalInline(inlineArgs) : walk.inline.project(inlineArgs);
669
+ if (inline.isOk()) paragraphs.push({
670
+ blockId: paraId,
671
+ container: located.container,
672
+ offset: offset + 1 + childOffset + 1,
673
+ inline: inline.value,
674
+ node,
675
+ source: located.source
676
+ });
677
+ passCommentMarkers(walk.markersOf(located.source), open);
678
+ return false;
679
+ });
680
+ };
681
+ /**
682
+ * The paragraphs of the top-level node at `index`, each start from the
683
+ * node's own, and whether each came from the story block at that index.
684
+ */
685
+ const projectBlock = (top, index, walk) => {
686
+ const paragraphs = [];
687
+ let local = true;
688
+ let failure;
689
+ const commentContext = {
690
+ rangedIds: walk.facts.rangedIds,
691
+ pointIds: walk.facts.pointIds,
692
+ openIds: walk.open.ids
693
+ };
694
+ const visit = (node, offset, parent) => {
695
+ if (failure !== void 0) return false;
696
+ if (node.type.name === "textBox") {
697
+ if (node.attrs["_docxPlacement"] === "standalone" && node.attrs["_docxHostParagraph"] != null && !walk.claimTextBoxHost()) failure = structureRefusal();
698
+ else projectTextBoxParagraphs({
699
+ box: node,
700
+ offset,
701
+ walk,
702
+ paragraphs
703
+ });
704
+ return false;
705
+ }
706
+ if (node.type.name === "blockCommentRangeBoundary") {
707
+ const { marker } = expectCommentRangeBoundaryAttrs(node);
708
+ if (marker.type === "commentRangeStart") walk.open.ids.add(marker.id);
709
+ else walk.open.ids.delete(marker.id);
710
+ return false;
711
+ }
712
+ if (node.type.name !== "paragraph") return true;
713
+ if (parent?.attrs["_omittedGridSlot"] != null) return false;
714
+ if ((parent?.type.name === "blockSdt" || parent?.type.name === "blockCustomXml") && parent.attrs["_originallyEmpty"] === true) return false;
715
+ const paraId = node.attrs["paraId"];
716
+ const located = typeof paraId === "string" ? walk.locate(paraId) : void 0;
717
+ if (typeof paraId !== "string" || located === void 0) {
718
+ failure = structureRefusal();
719
+ return false;
720
+ }
721
+ const { source, container } = located;
722
+ if (!walk.take(source)) {
723
+ failure = structureRefusal();
724
+ return false;
725
+ }
726
+ if (located.top !== index) local = false;
727
+ passCommentMarkers(walk.positionedComments.before.get(source), walk.open);
728
+ const inlineArgs = {
729
+ source,
730
+ paragraph: node,
731
+ pairedBookmarkIds: walk.facts.pairedBookmarkIds,
732
+ commentContext
733
+ };
734
+ const inline = walk.inline === void 0 ? projectCanonicalInline(inlineArgs) : walk.inline.project(inlineArgs);
735
+ if (inline.isErr()) {
736
+ failure = new CanonicalSessionError({
737
+ ground: { gap: CANONICAL_GAP.dispatch },
738
+ reason: "refused",
739
+ message: inline.error.message
740
+ });
741
+ return false;
742
+ }
743
+ paragraphs.push({
744
+ blockId: paraId,
745
+ container: container === walk.content ? void 0 : container,
746
+ offset: offset + 1,
747
+ inline: inline.value,
748
+ node,
749
+ source
750
+ });
751
+ walk.passComments(source);
752
+ passCommentMarkers(walk.positionedComments.after.get(source), walk.open);
753
+ return false;
754
+ };
755
+ if (visit(top, 0, null) && top.content.size > 0) top.descendants((node, offset, parent) => visit(node, offset + 1, parent));
756
+ if (failure !== void 0) return Result.err(failure);
757
+ return Result.ok({
758
+ paragraphs,
759
+ local
760
+ });
761
+ };
762
+ const passCommentMarkers = (markers, open) => {
763
+ for (const item of markers ?? []) {
764
+ if (item.type === "commentRangeStart") open.ids.add(item.id);
765
+ if (item.type === "commentRangeEnd") open.ids.delete(item.id);
766
+ }
767
+ };
768
+ /** Opens and closes the ranges a paragraph's markers start and end. */
769
+ const commentPasser = (markersOf, open) => (paragraph) => passCommentMarkers(markersOf(paragraph), open);
770
+ /** Every paragraph's address, walking every top-level node. */
771
+ const projectEveryBlock = ({ doc, content, story, markersOf, inline }) => {
772
+ const pairedBookmarkIds = collectPairedBookmarkIds(content);
773
+ const rangedIds = /* @__PURE__ */ new Set();
774
+ const referencedIds = /* @__PURE__ */ new Set();
775
+ const commentWalk = {
776
+ markersOf,
777
+ visit(item) {
778
+ if (item.type === "commentRangeStart") rangedIds.add(item.id);
779
+ if (item.type === "commentReference") referencedIds.add(item.id);
780
+ }
781
+ };
782
+ visitCommentMarkerItems(content, commentWalk);
783
+ visitSourceParagraphs(content, (source) => visitTextBoxSources(source, (boxed) => visitCommentMarkerItems([boxed], commentWalk)));
784
+ const facts = {
785
+ pairedBookmarkIds,
786
+ rangedIds,
787
+ pointIds: new Set([...referencedIds].filter((id) => !rangedIds.has(id)))
788
+ };
789
+ const open = new OpenComments([]);
790
+ const passComments = commentPasser(markersOf, open);
791
+ const aligned = doc.childCount === content.length;
792
+ const found = collectSources(content, 0, content.length, () => false);
793
+ let reusable = aligned && !found.repeated;
794
+ const sources = found.located;
795
+ const allSources = new Set(found.all);
796
+ const continuationSources = found.continuation;
797
+ const idsByBlock = found.idsByBlock;
798
+ const projectedSources = /* @__PURE__ */ new Set();
799
+ const projectedBoxed = /* @__PURE__ */ new Set();
800
+ const orderedSources = [...allSources];
801
+ const sourceOrder = new Map(orderedSources.map((source, index) => [source, index]));
802
+ const textBoxHosts = /* @__PURE__ */ new Set();
803
+ const positionedComments = positionedCommentGaps(content, continuationSources);
804
+ let nextSource = 0;
805
+ const walk = {
806
+ facts,
807
+ open,
808
+ content,
809
+ locate: (paraId) => sources.get(paraId),
810
+ locateBoxed: (paraId) => found.boxed.get(paraId),
811
+ takeBoxed: (source) => {
812
+ if (projectedBoxed.has(source)) return false;
813
+ projectedBoxed.add(source);
814
+ return true;
815
+ },
816
+ markersOf,
817
+ claimTextBoxHost: () => {
818
+ reusable = false;
819
+ let index = nextSource;
820
+ while (index < orderedSources.length && continuationSources.has(orderedSources[index] ?? panic("No source"))) index += 1;
821
+ const host = orderedSources[index];
822
+ if (host === void 0 || !holdsTextBox(host)) return false;
823
+ textBoxHosts.add(host);
824
+ nextSource = index + 1;
825
+ passCommentMarkers(positionedComments.before.get(host), open);
826
+ passComments(host);
827
+ passCommentMarkers(positionedComments.after.get(host), open);
828
+ return true;
829
+ },
830
+ take: (source) => {
831
+ if (projectedSources.has(source)) return false;
832
+ projectedSources.add(source);
833
+ nextSource = (sourceOrder.get(source) ?? panic("Unordered source")) + 1;
834
+ return true;
835
+ },
836
+ passComments,
837
+ positionedComments,
838
+ inline
839
+ };
840
+ const blocks = [];
841
+ for (let index = 0; index < doc.childCount; index += 1) {
842
+ const node = doc.child(index);
843
+ const openBefore = open.current;
844
+ const projected = projectBlock(node, index, walk);
845
+ if (projected.isErr()) return projected;
846
+ if (!projected.value.local) reusable = false;
847
+ blocks.push({
848
+ node,
849
+ source: aligned ? content[index] : void 0,
850
+ paragraphs: projected.value.paragraphs,
851
+ sourceIds: aligned ? idsByBlock[index] ?? [] : [],
852
+ openBefore,
853
+ openAfter: open.current
854
+ });
855
+ }
856
+ if (projectedSources.size + continuationSources.size + textBoxHosts.size !== allSources.size || [...projectedSources].some((source) => continuationSources.has(source) || textBoxHosts.has(source)) || [...textBoxHosts].some((source) => continuationSources.has(source))) return refuse("The projection changed paragraph structure.");
857
+ return Result.ok(new CanonicalProjection({
858
+ doc,
859
+ story,
860
+ content,
861
+ blocks,
862
+ index: ParagraphIdIndex.of(blocks),
863
+ facts,
864
+ reusable
865
+ }));
866
+ };
867
+ /**
868
+ * The projection keeping every top-level block of `previous` an edit left:
869
+ * the run of blocks from the start and the run to the end whose story block
870
+ * and converted node are both the ones `previous` walked. Only the blocks
871
+ * between are walked, from the comment ranges open where they start. Nothing
872
+ * when the kept blocks would read other story facts than they did, or the
873
+ * walked ones reach outside themselves; the story is then walked in full.
874
+ */
875
+ const projectChangedBlocks = (previous, { doc, content, story, markersOf, inline }) => {
876
+ if (!previous.reusable || !sameStory(previous.story, story)) return void 0;
877
+ const before = previous.blocks;
878
+ const count = content.length;
879
+ if (doc.childCount !== count) return void 0;
880
+ const unchanged = (block, at) => block !== void 0 && block.source === content[at] && block.node === doc.child(at);
881
+ let start = 0;
882
+ while (start < count && start < before.length && unchanged(before[start], start)) start += 1;
883
+ let after = 0;
884
+ while (after < count - start && after < before.length - start && unchanged(before[before.length - 1 - after], count - 1 - after)) after += 1;
885
+ const end = before.length - after;
886
+ const newEnd = count - after;
887
+ if (!sameIdOrder(storyFactContributions(previous.content.slice(start, end), markersOf), storyFactContributions(content.slice(start, newEnd), markersOf))) return void 0;
888
+ const removed = /* @__PURE__ */ new Set();
889
+ for (let index = start; index < end; index += 1) for (const id of before[index]?.sourceIds ?? []) removed.add(id);
890
+ const found = collectSources(content, start, newEnd, (paraId) => previous.index.get(paraId) !== void 0 && !removed.has(paraId));
891
+ if (found.repeated) return void 0;
892
+ const sources = found.located;
893
+ const continuationSources = found.continuation;
894
+ const open = new OpenComments(before[start - 1]?.openAfter ?? []);
895
+ const projectedSources = /* @__PURE__ */ new Set();
896
+ const projectedBoxed = /* @__PURE__ */ new Set();
897
+ const walk = {
898
+ facts: previous.facts,
899
+ open,
900
+ content,
901
+ locate: (paraId) => sources.get(paraId),
902
+ locateBoxed: (paraId) => found.boxed.get(paraId),
903
+ takeBoxed: (source) => {
904
+ if (projectedBoxed.has(source)) return false;
905
+ projectedBoxed.add(source);
906
+ return true;
907
+ },
908
+ markersOf,
909
+ claimTextBoxHost: () => false,
910
+ take: (source) => {
911
+ if (projectedSources.has(source)) return false;
912
+ projectedSources.add(source);
913
+ return true;
914
+ },
915
+ passComments: commentPasser(markersOf, open),
916
+ positionedComments: positionedCommentGaps(content.slice(start, newEnd), continuationSources),
917
+ inline
918
+ };
919
+ const window = [];
920
+ for (let index = start; index < newEnd; index += 1) {
921
+ const node = doc.child(index);
922
+ const openBefore = open.current;
923
+ const projected = projectBlock(node, index, walk);
924
+ if (projected.isErr() || !projected.value.local) return void 0;
925
+ window.push({
926
+ node,
927
+ source: content[index],
928
+ paragraphs: projected.value.paragraphs,
929
+ sourceIds: found.idsByBlock[index - start] ?? [],
930
+ openBefore,
931
+ openAfter: open.current
932
+ });
933
+ }
934
+ if (projectedSources.size + continuationSources.size !== found.all.length || [...projectedSources].some((source) => continuationSources.has(source))) return void 0;
935
+ const following = before[end];
936
+ if (following !== void 0 && !sameIdOrder(open.current, following.openBefore)) return void 0;
937
+ const blocks = [
938
+ ...before.slice(0, start),
939
+ ...window,
940
+ ...before.slice(end)
941
+ ];
942
+ return new CanonicalProjection({
943
+ doc,
944
+ story,
945
+ content,
946
+ blocks,
947
+ index: previous.index.replaced({
948
+ start,
949
+ end,
950
+ removed,
951
+ window,
952
+ blocks
953
+ }),
954
+ facts: previous.facts,
955
+ reusable: true
956
+ });
957
+ };
958
+ const project = ({ document, styles, story = OP_STORIES.MAIN, caches, previous }) => {
959
+ const body = findStoryBody(document, story);
960
+ if (!body) return refuse("The canonical story no longer exists.");
961
+ const currentStyles = Object.hasOwn(document.package, "styles") ? document.package.styles : styles;
962
+ const options = storyConversionOptions({
963
+ styles: currentStyles,
964
+ theme: document.package.theme,
965
+ numbering: document.package.numbering
966
+ });
967
+ const converted = Result.try({
968
+ try: () => {
969
+ if (story === OP_STORIES.MAIN) return toProseDoc(document, caches === void 0 ? options : {
970
+ ...options,
971
+ blockCache: caches.blocks
972
+ });
973
+ if (story.kind === "header" || story.kind === "footer") return headerFooterToProseDoc(body.content, options);
974
+ return footnoteToProseDoc(body.content, options);
975
+ },
976
+ catch: (cause) => new CanonicalSessionError({
977
+ ground: { gap: CANONICAL_GAP.dispatch },
978
+ reason: "refused",
979
+ message: `Canonical projection failed: ${cause instanceof Error ? cause.message : String(cause)}`
980
+ })
981
+ });
982
+ if (converted.isErr()) return converted;
983
+ const walk = {
984
+ doc: converted.value,
985
+ content: body.content,
986
+ story,
987
+ markersOf: caches?.comments.read ?? paragraphCommentMarkers,
988
+ inline: caches?.inline
989
+ };
990
+ const kept = previous === void 0 ? void 0 : projectChangedBlocks(previous, walk);
991
+ return kept === void 0 ? projectEveryBlock(walk) : Result.ok(kept);
992
+ };
993
+ const intentStory = (intent) => {
994
+ switch (intent.type) {
995
+ case "setHyperlink":
996
+ case "removeHyperlink":
997
+ case "insertHyperlink":
998
+ case "replaceFragment":
999
+ case "moveFragment":
1000
+ case "replaceText":
1001
+ case "formatRun":
1002
+ case "insertAtom": return intent.from.story;
1003
+ case "generateTOC":
1004
+ case "splitParagraph":
1005
+ case "formatParagraph": return intent.at.story;
1006
+ case "setList": return intent.items.at(0)?.at.story ?? panic("A list intent requires a paragraph.");
1007
+ case "joinParagraphs":
1008
+ case "insertParagraphs":
1009
+ case "deleteParagraphs": return intent.story;
1010
+ case "table":
1011
+ case "tableRow":
1012
+ case "tableBlock": return intent.operation.story;
1013
+ default: return intent;
1014
+ }
1015
+ };
1016
+ const UNDO_GROUP_WINDOW_MS = 500;
1017
+ const samePosition = (left, right) => sameStory(left.story, right.story) && left.blockId === right.blockId && left.offset === right.offset && (left.zeroWidthBefore ?? 0) === (right.zeroWidthBefore ?? 0);
1018
+ const sameSelection = (left, right) => left.type === right.type && samePosition(left.anchor, right.anchor) && samePosition(left.head, right.head);
1019
+ /** The ops that undo `group`, applied to the document it left. */
1020
+ const undoOpsOf = (group) => group.undo.type === "replayed" ? group.undo.inverse : group.entries.toReversed().flatMap((entry) => entry.inverse);
1021
+ const continuesGroup = (previous, next) => {
1022
+ switch (next.semantic) {
1023
+ case "typing":
1024
+ case "deleteBackward":
1025
+ case "deleteForward": return previous.grouping === "run" && next.grouping === "run" && previous.semantic === next.semantic && previous.boundary === next.boundary && next.time >= previous.time && next.time - previous.time <= UNDO_GROUP_WINDOW_MS && sameSelection(previous.postSelection, next.preSelection) && samePosition(next.preSelection.anchor, next.preSelection.head);
1026
+ case "composition": return next.grouping === "compositionCorrection" && previous.semantic === "composition" && previous.boundary === next.boundary && sameSelection(previous.postSelection, next.preSelection);
1027
+ case "paste":
1028
+ case "replacement":
1029
+ case "structure": return false;
1030
+ default: {
1031
+ const unreachable = next.semantic;
1032
+ return panic(`Unknown canonical input semantic ${unreachable}`);
1033
+ }
1034
+ }
1035
+ };
1036
+ const authorizedProjections = /* @__PURE__ */ new WeakMap();
1037
+ /** Metadata is descriptive; transaction identity and session version authorize mutations. */
1038
+ const isCanonicalProjectionTransaction = (transaction, session) => {
1039
+ const authorization = authorizedProjections.get(transaction);
1040
+ return authorization?.session === session && authorization.version === session.version && transaction.doc.eq(authorization.doc);
1041
+ };
1042
+ /** A node's shape without its text, for a refusal that names a change. */
1043
+ const nodeShapeOf = (node) => JSON.stringify({
1044
+ type: node.type.name,
1045
+ attrs: node.attrs,
1046
+ children: node.content.content.map((child) => ({
1047
+ type: child.type.name,
1048
+ marks: child.marks.map((mark) => mark.toJSON())
1049
+ }))
1050
+ });
1051
+ /**
1052
+ * Where an appended transaction moved the published document off the
1053
+ * projection: the innermost node holding the first difference, by its type,
1054
+ * attributes and children's marks, so the refusal carries no document text.
1055
+ */
1056
+ const projectionChangeOf = (projected, published) => {
1057
+ const at = projected.content.findDiffStart(published.content);
1058
+ if (at === null) return "a plugin appended a document change";
1059
+ const expected = projected.resolve(Math.min(at, projected.content.size));
1060
+ const actual = published.resolve(Math.min(at, published.content.size));
1061
+ return `a plugin changed the ${expected.parent.type.name} in body block ${expected.index(0)} from ${nodeShapeOf(expected.parent)} to ${nodeShapeOf(actual.parent)}`;
1062
+ };
1063
+ /** The model publishes only after PM and every plugin accept its exact projection. */
1064
+ const publishCanonicalProjection = ({ state, commit, session }) => {
1065
+ if (!isCanonicalProjectionTransaction(commit.transaction, session)) return refuse("The staged canonical projection is unauthorized.");
1066
+ const applied = Result.try({
1067
+ try: () => state.applyTransaction(commit.transaction),
1068
+ catch: (cause) => new CanonicalSessionError({
1069
+ ground: { gap: CANONICAL_GAP.dispatch },
1070
+ reason: "refused",
1071
+ message: `Canonical plugin staging failed: ${cause instanceof Error ? cause.message : String(cause)}`
1072
+ })
1073
+ });
1074
+ if (applied.isErr()) return applied;
1075
+ const staged = applied.value;
1076
+ if (!staged.transactions.includes(commit.transaction)) return refuse("A plugin refused or changed the canonical projection: a plugin filtered the projection transaction.");
1077
+ 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)}.`);
1078
+ const published = commit.publish();
1079
+ if (published.isErr()) return published;
1080
+ return Result.ok(staged);
1081
+ };
1082
+ /**
1083
+ * How a change is admitted against content-control locks. An edit is judged
1084
+ * on its result. A restage rebuilds a pending suggestion recorded before the
1085
+ * save: no new edit, so a lock that arrived since does not refuse it, while
1086
+ * resolving the suggestion stays under the lock.
1087
+ */
1088
+ const CANONICAL_ADMISSION = {
1089
+ edit: "edit",
1090
+ restage: "restage"
1091
+ };
1092
+ const storyProjectionKey = (story) => {
1093
+ switch (story.kind) {
1094
+ case "header":
1095
+ case "footer": return `${story.kind}:${story.rId}`;
1096
+ case "footnote":
1097
+ case "endnote": return `${story.kind}:${story.id}`;
1098
+ default: return panic(`Unknown canonical story ${story}`);
1099
+ }
1100
+ };
1101
+ const sameStoryParts = (left, right) => ["headers", "footers"].every((kind) => canonicalJson([...left.package[kind]?.keys() ?? []].toSorted()) === canonicalJson([...right.package[kind]?.keys() ?? []].toSorted()));
1102
+ /**
1103
+ * What a save baseline keeps of the parsed saved package: its buffer, the
1104
+ * capture of its body, and its headers and footers with their verbatim
1105
+ * sources. The body content itself is not kept.
1106
+ */
1107
+ const saveBaselineOf = (saved, buffer) => {
1108
+ const baseline = {
1109
+ originalBuffer: buffer,
1110
+ package: {
1111
+ document: {
1112
+ ...saved.package.document,
1113
+ content: []
1114
+ },
1115
+ ...saved.package.headers === void 0 ? {} : { headers: saved.package.headers },
1116
+ ...saved.package.footers === void 0 ? {} : { footers: saved.package.footers }
1117
+ }
1118
+ };
1119
+ copyHeaderFooterBaselineHandles(baseline, saved);
1120
+ return baseline;
1121
+ };
1122
+ /** Every note paragraph of `document`, in its text boxes too, by its id's key. */
1123
+ const noteParagraphsOf = (document) => {
1124
+ const paragraphs = /* @__PURE__ */ new Map();
1125
+ const notes = [...(document.package.footnotes ?? []).map(({ id, content }) => ({
1126
+ story: {
1127
+ kind: "footnote",
1128
+ id
1129
+ },
1130
+ content
1131
+ })), ...(document.package.endnotes ?? []).map(({ id, content }) => ({
1132
+ story: {
1133
+ kind: "endnote",
1134
+ id
1135
+ },
1136
+ content
1137
+ }))];
1138
+ for (const { story, content } of notes) for (const { paragraph } of paragraphsThroughTextBoxes(document, story)) if (paragraph.paraId !== void 0) paragraphs.set(paragraph.paraId.toUpperCase(), {
1139
+ paragraph,
1140
+ note: content
1141
+ });
1142
+ return paragraphs;
1143
+ };
1144
+ /** Every paragraph of `document`, in every story and text box, by its id's key. */
1145
+ const storyParagraphsOf = (document) => {
1146
+ const paragraphs = /* @__PURE__ */ new Map();
1147
+ for (const story of documentStories(document)) for (const { paragraph } of paragraphsThroughTextBoxes(document, story)) if (paragraph.paraId !== void 0) paragraphs.set(paragraph.paraId.toUpperCase(), paragraph);
1148
+ return paragraphs;
1149
+ };
1150
+ /** Immutable model authority with a journal staged independently of the PM view. */
1151
+ var CanonicalSession = class {
1152
+ currentDocument;
1153
+ currentProjection;
1154
+ sourceBlockIds;
1155
+ currentVersion = 0;
1156
+ saveTouched = /* @__PURE__ */ new Set();
1157
+ /** Every paragraph an edit touched since the session opened, undo and redo included. */
1158
+ touchedSinceOpen = /* @__PURE__ */ new Set();
1159
+ /** The document as the session opened it, which note parts are written against. */
1160
+ openedDocument;
1161
+ saveStructure = "stable";
1162
+ /**
1163
+ * The package a save wrote, parsed, once it is the baseline later saves
1164
+ * patch against: `saveTouched` and `saveStructure` then count from its
1165
+ * version. Holding only the latest releases every earlier one.
1166
+ */
1167
+ saveBaseline = null;
1168
+ /** A save whose package is being read to become the baseline. */
1169
+ pendingSaveBaseline = null;
1170
+ allocateIntentIds = createEditorIntentIdAllocator();
1171
+ mode = { type: "editing" };
1172
+ allocatedBlockIds = /* @__PURE__ */ new Set();
1173
+ nextBlockId = 1;
1174
+ leased;
1175
+ sourceOwners = /* @__PURE__ */ new Map();
1176
+ storyProjections = /* @__PURE__ */ new Map();
1177
+ currentSelection = null;
1178
+ /**
1179
+ * The selection the editor of each header, footer or note last showed,
1180
+ * keyed by story. Its editor records it whenever it changes, an edit in the
1181
+ * story commits it, and every peer's edit moves it with the text, as the
1182
+ * body's selection moves.
1183
+ */
1184
+ storySelections = /* @__PURE__ */ new Map();
1185
+ applied = [];
1186
+ groupingBoundary = 0;
1187
+ lifecycle = { type: "committed" };
1188
+ undone = [];
1189
+ historyDropListeners = /* @__PURE__ */ new Set();
1190
+ committedListeners = /* @__PURE__ */ new Set();
1191
+ newOpId;
1192
+ styles;
1193
+ sourceRestores;
1194
+ /**
1195
+ * The ids of the paragraphs the session added to the stories it read in its
1196
+ * own form (a story's closing paragraph), which no package names: a reader
1197
+ * reports them as positional.
1198
+ */
1199
+ get sourceMintedParaIds() {
1200
+ return new Set(this.sourceRestores.flatMap(({ minted }) => minted));
1201
+ }
1202
+ /** Notes the opened package held without a reference: content, kept on save. */
1203
+ heldUnreferencedNotes;
1204
+ /** Headers and footers a section of the opened package referenced. */
1205
+ referencedHeaderFootersAtOpen;
1206
+ /** {@link retiredHeaderFooters} of the document it was read from. */
1207
+ retiredHeaderFootersCache;
1208
+ /** What earlier projections converted, reused by every later one. */
1209
+ caches;
1210
+ constructor({ document, projection, styles, sourceRestores = [], caches, idLease, newOpId = () => crypto.randomUUID() }) {
1211
+ this.newOpId = newOpId;
1212
+ this.leased = idLease === void 0 ? void 0 : new CanonicalIdLease(idLease, document);
1213
+ this.sourceRestores = sourceRestores;
1214
+ this.caches = caches;
1215
+ this.heldUnreferencedNotes = heldUnreferencedNotes(document);
1216
+ this.referencedHeaderFootersAtOpen = referencedHeaderFooters(document);
1217
+ this.openedDocument = document;
1218
+ this.currentDocument = document;
1219
+ this.currentProjection = projection;
1220
+ const blockIds = packageParagraphIds(document.package);
1221
+ this.sourceBlockIds = new Set(blockIds);
1222
+ for (const blockId of blockIds) this.allocatedBlockIds.add(blockId.toUpperCase());
1223
+ this.advanceBlockId();
1224
+ this.styles = styles == null ? styles : structuredClone(styles);
1225
+ this.rememberSources(document.package.document.content);
1226
+ }
1227
+ /** Render only the committed comment projection while provisional IME blocks document snapshots. */
1228
+ getCommittedComments() {
1229
+ return structuredClone(survivingComments(this.currentDocument));
1230
+ }
1231
+ setMode(mode) {
1232
+ if (this.mode.type !== mode.type || this.mode.type === "suggesting" && mode.type === "suggesting" && this.mode.author !== mode.author) this.breakUndoGroup();
1233
+ this.mode = mode.type === "editing" ? { type: "editing" } : {
1234
+ type: "suggesting",
1235
+ author: mode.author
1236
+ };
1237
+ }
1238
+ hasStyle(styleId) {
1239
+ return (this.styles ?? this.currentDocument.package.styles)?.styles.some((style) => style.styleId === styleId) ?? false;
1240
+ }
1241
+ /** How a replacement in the current mode removes the words it changes. */
1242
+ replacementRemoval() {
1243
+ switch (this.mode.type) {
1244
+ case "editing": return {
1245
+ type: "direct",
1246
+ comments: this.currentDocument.package.document.comments ?? []
1247
+ };
1248
+ case "suggesting": return { type: "tracked" };
1249
+ default: {
1250
+ const unhandled = this.mode;
1251
+ return panic(`Unknown canonical session mode ${String(unhandled)}`);
1252
+ }
1253
+ }
1254
+ }
1255
+ advanceBlockId() {
1256
+ while (this.allocatedBlockIds.has(this.nextBlockId.toString(16).padStart(8, "0").toUpperCase())) this.nextBlockId += 1;
1257
+ }
1258
+ freshBlockId() {
1259
+ if (this.leased !== void 0) {
1260
+ const fresh = this.freshBlockIds([1]);
1261
+ if (fresh.isErr()) return fresh;
1262
+ const id = fresh.value[0]?.[0];
1263
+ return id === void 0 ? refuse("The paragraph identity lease is exhausted.") : Result.ok(id);
1264
+ }
1265
+ if (this.nextBlockId > 2147483647) return refuse("The paragraph identity space is exhausted.");
1266
+ return Result.ok(this.nextBlockId.toString(16).padStart(8, "0").toUpperCase());
1267
+ }
1268
+ /**
1269
+ * Paragraph identities for one prepared batch, one group per requested count;
1270
+ * none matches a live or retired identity and no two groups overlap. Nothing is
1271
+ * reserved until the batch applies, so a batch asks once for all its groups.
1272
+ */
1273
+ freshBlockIds(counts) {
1274
+ const total = counts.reduce((sum, count) => sum + count, 0);
1275
+ const ids = [];
1276
+ if (this.leased !== void 0) {
1277
+ const leased = freshLeasedIds({
1278
+ lease: this.leased.lease,
1279
+ kind: ID_LEASE_KINDS.PARAGRAPH,
1280
+ count: total,
1281
+ taken: (id) => this.allocatedBlockIds.has(formatParaId(id))
1282
+ });
1283
+ if (leased.length < total) return refuse("The paragraph identity lease is exhausted.");
1284
+ ids.push(...leased.map(formatParaId));
1285
+ }
1286
+ for (let candidate = this.nextBlockId; ids.length < total; candidate += 1) {
1287
+ if (candidate > 2147483647) return refuse("The paragraph identity space is exhausted.");
1288
+ const id = candidate.toString(16).padStart(8, "0").toUpperCase();
1289
+ if (!this.allocatedBlockIds.has(id)) ids.push(id);
1290
+ }
1291
+ const groups = [];
1292
+ let offset = 0;
1293
+ for (const count of counts) {
1294
+ groups.push(ids.slice(offset, offset + count));
1295
+ offset += count;
1296
+ }
1297
+ return Result.ok(groups);
1298
+ }
1299
+ intentMode(document, intent) {
1300
+ const leased = this.leased === void 0 ? {} : { idLease: this.leased.lease };
1301
+ if (this.mode.type === "editing" && !this.intentNeedsIdentityIds(document, intent)) return {
1302
+ type: "editing",
1303
+ reservedBlockIds: this.allocatedBlockIds,
1304
+ ...leased
1305
+ };
1306
+ const ids = this.allocateIntentIds(document, intent, this.leased?.lease);
1307
+ return this.mode.type === "editing" ? {
1308
+ type: "editing",
1309
+ newIds: ids.newIds,
1310
+ reservedBlockIds: this.allocatedBlockIds,
1311
+ ...leased
1312
+ } : {
1313
+ type: "suggesting",
1314
+ reservedBlockIds: this.allocatedBlockIds,
1315
+ ...leased,
1316
+ revision: {
1317
+ id: ids.revisionId,
1318
+ author: this.mode.author,
1319
+ date: (/* @__PURE__ */ new Date()).toISOString()
1320
+ },
1321
+ newIds: ids.newIds
1322
+ };
1323
+ }
1324
+ intentNeedsIdentityIds(document, intent) {
1325
+ let blockIds;
1326
+ switch (intent.type) {
1327
+ case "table":
1328
+ case "tableRow":
1329
+ case "tableBlock":
1330
+ case "insertParagraphs":
1331
+ case "deleteParagraphs": return true;
1332
+ case "generateTOC":
1333
+ case "setList":
1334
+ case "formatParagraph": return false;
1335
+ case "setHyperlink":
1336
+ case "removeHyperlink":
1337
+ case "insertHyperlink":
1338
+ case "replaceFragment":
1339
+ case "moveFragment": return true;
1340
+ case "replaceText":
1341
+ case "insertAtom":
1342
+ case "formatRun":
1343
+ if (intent.from.blockId !== intent.to.blockId) return true;
1344
+ blockIds = [intent.from.blockId];
1345
+ break;
1346
+ case "splitParagraph":
1347
+ if (intent.to !== void 0 && intent.at.blockId !== intent.to.blockId) return true;
1348
+ blockIds = [intent.at.blockId];
1349
+ break;
1350
+ case "joinParagraphs":
1351
+ blockIds = [intent.blockId, intent.nextBlockId];
1352
+ break;
1353
+ default: return intent;
1354
+ }
1355
+ const hasIdentity = (value) => {
1356
+ if (typeof value !== "object" || value === null) return false;
1357
+ if (Array.isArray(value)) return value.some(hasIdentity);
1358
+ if ("id" in value && typeof value.id === "number" && ("author" in value || "sdtType" in value)) return true;
1359
+ return Object.values(value).some(hasIdentity);
1360
+ };
1361
+ const story = intentStory(intent);
1362
+ return blockIds.some((blockId) => {
1363
+ const paragraph = document === this.currentDocument && story === OP_STORIES.MAIN ? this.currentProjection.paragraph(blockId)?.source : findStoryBody(document, story)?.content.find((block) => block.type === "paragraph" && block.paraId === blockId);
1364
+ return paragraph !== void 0 && hasIdentity(paragraph);
1365
+ });
1366
+ }
1367
+ /** Record each paragraph among `blocks` as the owner of its id. */
1368
+ rememberSources(blocks) {
1369
+ for (const block of blocks) if (block.type === "paragraph" && block.paraId !== void 0) this.sourceOwners.set(block.paraId, block);
1370
+ }
1371
+ get document() {
1372
+ if (this.isComposing) throw new CanonicalSessionError({
1373
+ ground: { gap: CANONICAL_GAP.dispatch },
1374
+ reason: "refused",
1375
+ message: "Composition must finish before taking a snapshot."
1376
+ });
1377
+ return this.currentDocument;
1378
+ }
1379
+ /**
1380
+ * The `header:<rId>` and `footer:<rId>` parts a resolution retired: the
1381
+ * opened package referenced them and no section names them now. A save
1382
+ * drops them; a reader lists them no more.
1383
+ */
1384
+ retiredHeaderFooters() {
1385
+ const document = this.currentDocument;
1386
+ if (this.retiredHeaderFootersCache?.document !== document) this.retiredHeaderFootersCache = {
1387
+ document,
1388
+ retired: retiredHeaderFooters(document, this.referencedHeaderFootersAtOpen)
1389
+ };
1390
+ return this.retiredHeaderFootersCache.retired;
1391
+ }
1392
+ captureSaveSnapshot() {
1393
+ if (this.isComposing) throw new CanonicalSessionError({
1394
+ ground: { gap: CANONICAL_GAP.save },
1395
+ reason: "refused",
1396
+ message: "Composition must finish before saving the canonical document."
1397
+ });
1398
+ const retainedBlockIdKeys = new Set([
1399
+ ...this.sourceBlockIds,
1400
+ ...this.saveBaseline?.blockIds ?? [],
1401
+ ...packageParagraphIds(this.currentDocument.package)
1402
+ ].map((blockId) => blockId.toUpperCase()));
1403
+ const document = withUneditedSourceRestored(cloneDocumentWithParagraphPropertySources(this.currentDocument), this.sourceRestores);
1404
+ const noteParagraphs = this.noteParagraphChanges();
1405
+ return {
1406
+ document,
1407
+ ...this.saveBaseline === null ? {} : { saveBaseline: {
1408
+ buffer: this.saveBaseline.buffer,
1409
+ document: this.saveBaseline.document
1410
+ } },
1411
+ version: this.currentVersion,
1412
+ changedBlockIds: [...this.saveTouched].filter((blockId) => retainedBlockIdKeys.has(blockId.toUpperCase())),
1413
+ structure: this.saveStructure,
1414
+ heldUnreferencedNotes: this.heldUnreferencedNotes,
1415
+ referencedHeaderFootersAtOpen: this.referencedHeaderFootersAtOpen,
1416
+ noteParagraphs,
1417
+ restoredSinceSource: this.paragraphsRestoredSinceSource(new Set(noteParagraphs.changedSinceSource.map((id) => id.toUpperCase())))
1418
+ };
1419
+ }
1420
+ /**
1421
+ * The paragraphs an edit touched since the session opened whose content is
1422
+ * again what the opened document held, between the same neighbours: an
1423
+ * edit and its undo, or a change and its rejection, left them as they were.
1424
+ * A paragraph added or removed beside one is placed by it, so it stays a
1425
+ * change, and so does a note paragraph in `changedNotes`, whose note
1426
+ * changed around it.
1427
+ */
1428
+ paragraphsRestoredSinceSource(changedNotes) {
1429
+ if (this.touchedSinceOpen.size === 0) return [];
1430
+ const current = storyParagraphsOf(this.currentDocument);
1431
+ const opened = storyParagraphsOf(this.openedDocument);
1432
+ const neighbours = (paragraphs) => {
1433
+ const ids = [...paragraphs.keys()];
1434
+ return new Map(ids.map((id, index) => [id, `${ids[index - 1] ?? ""}|${ids[index + 1] ?? ""}`]));
1435
+ };
1436
+ const currentNeighbours = neighbours(current);
1437
+ const openedNeighbours = neighbours(opened);
1438
+ return [...this.touchedSinceOpen].filter((id) => {
1439
+ const key = id.toUpperCase();
1440
+ const now = current.get(key);
1441
+ const then = opened.get(key);
1442
+ return now !== void 0 && then !== void 0 && !changedNotes.has(key) && currentNeighbours.get(key) === openedNeighbours.get(key) && (now === then || canonicalJson(now) === canonicalJson(then));
1443
+ });
1444
+ }
1445
+ /**
1446
+ * The note paragraphs touched since the save baseline, and those that
1447
+ * differ from the opened document among the ones touched since it opened:
1448
+ * a note an edit and its undo left as it was is no change. A paragraph the
1449
+ * edit left as it was still counts when its note changed around it (cells
1450
+ * merged, a row's or cell's revision), which no paragraph records.
1451
+ */
1452
+ noteParagraphChanges() {
1453
+ if (this.touchedSinceOpen.size === 0) return {
1454
+ touched: [],
1455
+ changedSinceSource: []
1456
+ };
1457
+ const current = noteParagraphsOf(this.currentDocument);
1458
+ const opened = noteParagraphsOf(this.openedDocument);
1459
+ const isNote = (id) => current.has(id.toUpperCase()) || opened.has(id.toUpperCase());
1460
+ const noteJson = /* @__PURE__ */ new Map();
1461
+ const jsonOf = (note) => {
1462
+ const known = noteJson.get(note);
1463
+ if (known !== void 0) return known;
1464
+ const json = canonicalJson(note);
1465
+ noteJson.set(note, json);
1466
+ return json;
1467
+ };
1468
+ return {
1469
+ touched: [...this.saveTouched].filter(isNote),
1470
+ changedSinceSource: [...this.touchedSinceOpen].filter((id) => {
1471
+ const now = current.get(id.toUpperCase());
1472
+ const then = opened.get(id.toUpperCase());
1473
+ if (now === void 0 || then === void 0) return now !== then;
1474
+ if (now.paragraph !== then.paragraph && canonicalJson(now.paragraph) !== canonicalJson(then.paragraph)) return true;
1475
+ return now.note !== then.note && jsonOf(now.note) !== jsonOf(then.note);
1476
+ })
1477
+ };
1478
+ }
1479
+ /**
1480
+ * Start making the package saved at `version` the baseline later saves
1481
+ * patch against. Edits from now on are counted from that version too, so
1482
+ * {@link completeSaveBaseline} can swap the counts without losing one.
1483
+ * Refused unless `version` is the current one.
1484
+ */
1485
+ beginSaveBaseline(version) {
1486
+ if (this.isComposing || version !== this.currentVersion) return false;
1487
+ this.pendingSaveBaseline = {
1488
+ version,
1489
+ blockIds: packageParagraphIds(this.currentDocument.package),
1490
+ touched: /* @__PURE__ */ new Set(),
1491
+ structure: "stable"
1492
+ };
1493
+ return true;
1494
+ }
1495
+ /**
1496
+ * Make `saved`, the package written at `version` as parsed, the baseline:
1497
+ * later saves patch it and count changes from that version, and an undo
1498
+ * past it counts as a change like any other edit. Declined, keeping the
1499
+ * previous baseline and its counts, when a later save started, or when
1500
+ * `saved` does not hold the body paragraphs the session held at `version`
1501
+ * in the same order, or the same headers and footers.
1502
+ */
1503
+ completeSaveBaseline(version, saved) {
1504
+ const pending = this.pendingSaveBaseline;
1505
+ if (pending?.version !== version) return false;
1506
+ this.pendingSaveBaseline = null;
1507
+ const blockIds = packageParagraphIds(saved.package);
1508
+ const buffer = saved.originalBuffer;
1509
+ if (buffer === void 0 || getDocumentSourceBaseline(saved).type !== "captured" || blockIds.length !== pending.blockIds.length || blockIds.some((blockId, index) => blockId.toUpperCase() !== pending.blockIds[index]?.toUpperCase()) || !sameStoryParts(saved, this.currentDocument)) return false;
1510
+ this.saveBaseline = {
1511
+ version,
1512
+ blockIds,
1513
+ buffer,
1514
+ document: saveBaselineOf(saved, buffer)
1515
+ };
1516
+ this.saveTouched = pending.touched;
1517
+ this.saveStructure = pending.structure;
1518
+ return true;
1519
+ }
1520
+ get projection() {
1521
+ return this.currentProjection;
1522
+ }
1523
+ /** The caret the last published edit returned, when the editor shows it at `position`. */
1524
+ editCaretAt(projection, position) {
1525
+ const caret = this.currentSelection;
1526
+ if (caret === null || caret.type !== "text" || caret.anchor.offset !== caret.head.offset || caret.anchor.blockId !== caret.head.blockId || (caret.anchor.zeroWidthBefore ?? null) !== (caret.head.zeroWidthBefore ?? null) || !sameStory(caret.head.story, projection.story)) return void 0;
1527
+ const shown = projection.positionAt(caret.head);
1528
+ return shown.isOk() && shown.value === position ? caret.head : void 0;
1529
+ }
1530
+ get selection() {
1531
+ return this.currentSelection;
1532
+ }
1533
+ /**
1534
+ * Record the selection the editor of a header, footer or note shows, so a
1535
+ * peer's edit to the story moves it with the text (`storySelection`). The
1536
+ * state must show the story's current projection.
1537
+ */
1538
+ recordStorySelection(state, story) {
1539
+ const projected = this.projectStory(story);
1540
+ if (projected.isErr()) return projected;
1541
+ const projection = projected.value;
1542
+ if (state.doc !== projection.doc && !state.doc.eq(projection.doc)) return refuse("The story editor shows a stale canonical projection.");
1543
+ const selection = projection.selectionAt(state);
1544
+ if (selection.isErr()) {
1545
+ this.storySelections.delete(storyProjectionKey(story));
1546
+ return selection;
1547
+ }
1548
+ this.storySelections.set(storyProjectionKey(story), selection.value);
1549
+ return Result.ok(void 0);
1550
+ }
1551
+ /**
1552
+ * The selection the editor of `story` last recorded or committed, moved
1553
+ * over every peer's edit since; null before its editor recorded one.
1554
+ */
1555
+ storySelection(story) {
1556
+ return this.storySelections.get(storyProjectionKey(story)) ?? null;
1557
+ }
1558
+ /** Every paragraph identity this session has read or minted, live or retired. */
1559
+ get reservedBlockIds() {
1560
+ return this.allocatedBlockIds;
1561
+ }
1562
+ /** The ids this session may still mint, when it holds a lease. */
1563
+ get idLease() {
1564
+ return this.leased?.lease;
1565
+ }
1566
+ /**
1567
+ * Take the lease a room granted a session opened before it joined: from
1568
+ * then on every id it mints comes from the lease. Only an unedited session
1569
+ * without a lease takes one.
1570
+ */
1571
+ adoptIdLease(lease) {
1572
+ if (this.leased !== void 0) return refuse("The session already holds an id lease.");
1573
+ if (this.currentVersion !== 0) return refuse("The session was edited before it took an id lease.");
1574
+ this.leased = new CanonicalIdLease(lease, this.currentDocument);
1575
+ return Result.ok(void 0);
1576
+ }
1577
+ /** Add blocks the authority granted; ids this session already minted stay spent. */
1578
+ extendIdLease(lease) {
1579
+ if (this.leased === void 0) return refuse("The session was created without an id lease.");
1580
+ this.leased.extend(lease);
1581
+ return Result.ok(void 0);
1582
+ }
1583
+ get version() {
1584
+ return this.currentVersion;
1585
+ }
1586
+ get canUndo() {
1587
+ return this.applied.length > 0;
1588
+ }
1589
+ get canRedo() {
1590
+ return this.undone.length > 0;
1591
+ }
1592
+ get isComposing() {
1593
+ return this.lifecycle.type === "composing";
1594
+ }
1595
+ breakUndoGroup() {
1596
+ this.groupingBoundary += 1;
1597
+ }
1598
+ beginComposition() {
1599
+ if (this.isComposing) return refuse("A canonical composition is already pending.");
1600
+ this.lifecycle = { type: "composing" };
1601
+ this.breakUndoGroup();
1602
+ return Result.ok(void 0);
1603
+ }
1604
+ endComposition() {
1605
+ this.lifecycle = { type: "committed" };
1606
+ this.breakUndoGroup();
1607
+ }
1608
+ checkState(state, projection = this.projection) {
1609
+ if (this.isComposing) return refuse("Composition must finish before committing another edit.");
1610
+ if (state.doc !== projection.doc && !state.doc.eq(projection.doc)) return refuse("The input uses a stale canonical projection.");
1611
+ return Result.ok(void 0);
1612
+ }
1613
+ prepareReplace(state, { from, to, text, story = OP_STORIES.MAIN, semantic = "replacement", compositionPhase, time = Date.now() }) {
1614
+ const projected = this.projectStory(story);
1615
+ if (projected.isErr()) return projected;
1616
+ const projection = projected.value;
1617
+ const checked = this.checkState(state, projection);
1618
+ if (checked.isErr()) return checked;
1619
+ if (!Number.isFinite(time)) return refuse("The input time is invalid.");
1620
+ 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.");
1621
+ if (from === to && text.length === 0) return noChange("The input makes no text change.");
1622
+ const replacesStructuralSelection = state.selection instanceof AllSelection && from === state.selection.from && to === state.selection.to;
1623
+ if (state.selection instanceof CellSelection) {
1624
+ if (from !== state.selection.from || to !== state.selection.to) return refuse("A replacement range cannot partially address a cell selection.");
1625
+ const ranges = canonicalCellSelectionRanges(state.selection);
1626
+ const firstRange = ranges.at(0);
1627
+ const lastRange = ranges.at(-1);
1628
+ if (firstRange === void 0 || lastRange === void 0) return refuse("The selected cells contain no editable text.");
1629
+ const intents = [];
1630
+ const commentChanges = [];
1631
+ let first = true;
1632
+ for (const range of ranges) {
1633
+ const edges = projection.rangeEdgesAt(range.from, range.to);
1634
+ const cellFrom = projection.inputAddressAt(range.from, edges.start);
1635
+ if (cellFrom.isErr()) return cellFrom;
1636
+ const cellTo = projection.inputAddressAt(range.to, edges.end);
1637
+ if (cellTo.isErr()) return cellTo;
1638
+ intents.push({
1639
+ type: "replaceText",
1640
+ from: cellFrom.value,
1641
+ to: cellTo.value,
1642
+ text: first ? text : ""
1643
+ });
1644
+ commentChanges.push({
1645
+ from: range.from,
1646
+ to: range.to,
1647
+ text: first ? text : "",
1648
+ markers: edges.start === "beforeMarkers" || edges.end === "afterMarkers" ? "selected" : "retained"
1649
+ });
1650
+ first = false;
1651
+ }
1652
+ if (text !== "" && !preservesReplacementCommentAlignment({
1653
+ doc: state.doc,
1654
+ source: {
1655
+ from: firstRange.from,
1656
+ to: lastRange.to
1657
+ },
1658
+ changes: commentChanges,
1659
+ removal: this.replacementRemoval()
1660
+ })) return refuseUnder({ gap: CANONICAL_GAP.commentReplacementAlignment }, "Canonical replacement cannot preserve the aligned comment ranges.");
1661
+ return this.prepareIntents(state, {
1662
+ intents,
1663
+ semantic
1664
+ });
1665
+ }
1666
+ const range = canonicalSelectionRange(state);
1667
+ const inputFrom = replacesStructuralSelection ? range.from : from;
1668
+ const inputTo = replacesStructuralSelection ? range.to : to;
1669
+ const edges = inputFrom === inputTo ? {
1670
+ start: "caret",
1671
+ end: "caret"
1672
+ } : projection.rangeEdgesAt(inputFrom, inputTo);
1673
+ const editCaret = this.editCaretAt(projection, inputFrom);
1674
+ const start = inputFrom === inputTo && editCaret !== void 0 ? Result.ok(editCaret) : projection.inputAddressAt(inputFrom, edges.start);
1675
+ if (start.isErr()) return start;
1676
+ const end = inputFrom === inputTo && editCaret !== void 0 ? Result.ok(editCaret) : projection.inputAddressAt(inputTo, edges.end);
1677
+ if (end.isErr()) return end;
1678
+ if (inputFrom < inputTo && text !== "") {
1679
+ const retirement = planWholeParagraphReplacement({
1680
+ document: this.currentDocument,
1681
+ from: start.value,
1682
+ to: end.value,
1683
+ suggesting: this.mode.type === "suggesting" ? { author: this.mode.author } : void 0
1684
+ });
1685
+ if (retirement.isErr()) return refuse(retirement.error.message);
1686
+ if (!preservesReplacementCommentAlignment({
1687
+ doc: state.doc,
1688
+ retiredCommentIds: retirement.value?.commentIds,
1689
+ removal: this.replacementRemoval(),
1690
+ source: {
1691
+ from: inputFrom,
1692
+ to: inputTo
1693
+ },
1694
+ changes: [{
1695
+ from: inputFrom,
1696
+ to: inputTo,
1697
+ text,
1698
+ markers: edges.start === "beforeMarkers" || edges.end === "afterMarkers" ? "selected" : "retained"
1699
+ }]
1700
+ })) return refuseUnder({ gap: CANONICAL_GAP.commentReplacementAlignment }, "Canonical replacement cannot preserve the aligned comment ranges.");
1701
+ }
1702
+ const preSelection = projection.selectionAt(state);
1703
+ if (preSelection.isErr()) return preSelection;
1704
+ const inside = controlEdgesAt(state.doc, inputFrom, inputTo);
1705
+ const intent = {
1706
+ type: "replaceText",
1707
+ from: start.value,
1708
+ to: end.value,
1709
+ text,
1710
+ ...Object.keys(inside).length === 0 ? {} : { inside },
1711
+ ...state.storedMarks === null ? {} : { runPropsPatch: runFormattingPatchFromMarks(state.selection.$from.marks(), state.storedMarks) }
1712
+ };
1713
+ const compiled = compileEditorIntent(this.currentDocument, {
1714
+ intent,
1715
+ mode: this.intentMode(this.currentDocument, intent)
1716
+ });
1717
+ if (compiled.isErr()) return compiled.error.reason === DOCUMENT_OP_REFUSAL_REASONS.NO_CHANGE ? noChange(compiled.error.message) : refuse(compiled.error.message);
1718
+ const { ops, selection: caret } = compiled.value;
1719
+ const postSelection = {
1720
+ type: "text",
1721
+ anchor: caret,
1722
+ head: caret
1723
+ };
1724
+ const preDocument = this.currentDocument;
1725
+ const isCaret = state.selection.empty;
1726
+ const deletion = isCaret && text.length === 0 && (semantic === "deleteBackward" || semantic === "deleteForward") ? deletionRange(state, semantic === "deleteBackward" ? "backward" : "forward") : null;
1727
+ const grouping = isCaret && (semantic === "typing" && from === to && from === state.selection.head || deletion?.isOk() && deletion.value.from === from && deletion.value.to === to) ? "run" : "isolated";
1728
+ const groupingKey = {
1729
+ preSelection: preSelection.value,
1730
+ postSelection,
1731
+ semantic,
1732
+ grouping: compositionPhase === "correction" ? "compositionCorrection" : grouping,
1733
+ time,
1734
+ boundary: this.groupingBoundary
1735
+ };
1736
+ const group = this.applied.at(-1);
1737
+ const previous = group?.entries.at(-1);
1738
+ const joins = group !== void 0 && previous !== void 0 && continuesGroup(previous, groupingKey);
1739
+ return this.stage({
1740
+ state,
1741
+ story,
1742
+ ops,
1743
+ selection: postSelection,
1744
+ origin: "input",
1745
+ history: joins ? "joined" : "opened",
1746
+ ...semantic === "typing" && inputFrom === inputTo && text.length > 0 ? { typing: {
1747
+ at: start.value,
1748
+ after: caret,
1749
+ text
1750
+ } } : {},
1751
+ ...compiled.value.applied === void 0 ? {} : { stagedApplied: compiled.value.applied },
1752
+ onPublish: (inverse, version, shown) => {
1753
+ const entry = {
1754
+ type: "applied",
1755
+ ops,
1756
+ inverse,
1757
+ ...groupingKey,
1758
+ preDocument,
1759
+ postDocument: this.currentDocument,
1760
+ version,
1761
+ origin: "input"
1762
+ };
1763
+ if (group !== void 0 && joins) {
1764
+ group.entries.push(entry);
1765
+ group.postSelection = shown;
1766
+ } else this.applied.push({
1767
+ entries: [entry],
1768
+ undo: { type: "entries" },
1769
+ preSelection: preSelection.value,
1770
+ postSelection: shown
1771
+ });
1772
+ this.undone.length = 0;
1773
+ }
1774
+ });
1775
+ }
1776
+ /**
1777
+ * A structural edit over selected cells: each selected cell is cleared and
1778
+ * the edit happens at the start of the first, as the editor's own command
1779
+ * does over a cell selection. One commit, so one undo step.
1780
+ */
1781
+ prepareCellSelectionStructure(state, structure, { resourceOps = [], semantic = "structure" } = {}) {
1782
+ if (!(state.selection instanceof CellSelection)) return refuse("The structural edit needs a cell selection.");
1783
+ const projected = this.projectStory(OP_STORIES.MAIN);
1784
+ if (projected.isErr()) return projected;
1785
+ const projection = projected.value;
1786
+ const intents = [];
1787
+ let first;
1788
+ for (const range of canonicalCellSelectionRanges(state.selection)) {
1789
+ const edges = projection.rangeEdgesAt(range.from, range.to);
1790
+ const cellFrom = projection.inputAddressAt(range.from, edges.start);
1791
+ if (cellFrom.isErr()) return cellFrom;
1792
+ const cellTo = projection.inputAddressAt(range.to, edges.end);
1793
+ if (cellTo.isErr()) return cellTo;
1794
+ first ??= cellFrom.value;
1795
+ if (cellFrom.value.blockId !== cellTo.value.blockId || cellFrom.value.offset !== cellTo.value.offset) intents.push({
1796
+ type: "replaceText",
1797
+ from: cellFrom.value,
1798
+ to: cellTo.value,
1799
+ text: ""
1800
+ });
1801
+ }
1802
+ if (first === void 0) return refuse("The cell selection is empty.");
1803
+ intents.push(structure({
1804
+ ...first,
1805
+ offset: 0,
1806
+ zeroWidthBefore: 0
1807
+ }));
1808
+ return this.prepareIntents(state, {
1809
+ intents,
1810
+ resourceOps,
1811
+ semantic
1812
+ });
1813
+ }
1814
+ prepareIntent(state, intent) {
1815
+ return this.prepareIntents(state, { intents: [intent] });
1816
+ }
1817
+ prepareIntents(state, { intents, resourceOps = [], semantic = "structure" }) {
1818
+ const first = intents.at(0);
1819
+ if (first === void 0) return noChange("The intent batch is empty.");
1820
+ const story = intentStory(first);
1821
+ if (intents.some((intent) => !sameStory(story, intentStory(intent)))) return refuse("A compound input must address one story.");
1822
+ const projected = this.projectStory(story);
1823
+ if (projected.isErr()) return projected;
1824
+ const checked = this.checkState(state, projected.value);
1825
+ if (checked.isErr()) return checked;
1826
+ const preSelection = projected.value.selectionAt(state);
1827
+ if (preSelection.isErr()) return preSelection;
1828
+ let document = this.currentDocument;
1829
+ let postSelection = preSelection.value;
1830
+ const ops = [...resourceOps];
1831
+ const edits = [];
1832
+ if (resourceOps.length > 0) {
1833
+ const imported = applyDocumentOps(document, resourceOps);
1834
+ if (imported.isErr()) return refuse(imported.error.message);
1835
+ document = imported.value.document;
1836
+ edits.push(imported.value);
1837
+ }
1838
+ for (const intent of intents) {
1839
+ const compiled = compileEditorIntent(document, {
1840
+ intent,
1841
+ mode: this.intentMode(document, intent),
1842
+ firstBlockId: this.nextBlockId
1843
+ });
1844
+ if (compiled.isErr()) return intentRefusal(intent, this.mode, compiled.error);
1845
+ const applied = compiled.value.applied === void 0 ? applyDocumentOps(document, compiled.value.ops) : Result.ok(compiled.value.applied);
1846
+ if (applied.isErr()) return intentRefusal(intent, this.mode, applied.error);
1847
+ document = applied.value.document;
1848
+ edits.push(applied.value);
1849
+ ops.push(...compiled.value.ops);
1850
+ if (this.mode.type === "suggesting" && (intent.type === "setHyperlink" || intent.type === "removeHyperlink")) postSelection = {
1851
+ type: "text",
1852
+ anchor: intent.from,
1853
+ head: compiled.value.selection
1854
+ };
1855
+ else if (this.mode.type === "suggesting" && intent.type === "generateTOC") postSelection = {
1856
+ type: "text",
1857
+ anchor: compiled.value.selection,
1858
+ head: compiled.value.selection
1859
+ };
1860
+ else if (intent.type === "generateTOC") {
1861
+ const mapping = {
1862
+ at: intent.at,
1863
+ after: compiled.value.selection,
1864
+ ops: compiled.value.ops
1865
+ };
1866
+ postSelection = Object.assign({}, postSelection, {
1867
+ anchor: mapTocSelection(postSelection.anchor, mapping),
1868
+ head: mapTocSelection(postSelection.head, mapping)
1869
+ });
1870
+ } else if (intent.type !== "setHyperlink" && intent.type !== "removeHyperlink" && intent.type !== "formatRun" && intent.type !== "formatParagraph" && intent.type !== "setList") postSelection = {
1871
+ type: "text",
1872
+ anchor: compiled.value.selection,
1873
+ head: compiled.value.selection
1874
+ };
1875
+ }
1876
+ const stagedApplied = {
1877
+ ...combineEdits(this.currentDocument, edits),
1878
+ ...combineRecordedRevisions(edits)
1879
+ };
1880
+ return this.prepareJournalledOps({
1881
+ state,
1882
+ ops,
1883
+ postSelection,
1884
+ stagedApplied,
1885
+ semantic
1886
+ });
1887
+ }
1888
+ prepareOps(state, ops, postSelection) {
1889
+ return this.prepareJournalledOps({
1890
+ state,
1891
+ ops,
1892
+ postSelection
1893
+ });
1894
+ }
1895
+ /** Verify compiled insertions and stage only the chain this session applied. */
1896
+ beginVerifiedOperationStaging(access, admission) {
1897
+ if (access !== canonicalOperationStagingAccess) panic("Only the public-operation compiler may stage verified operations.");
1898
+ const base = this.currentDocument;
1899
+ const version = this.currentVersion;
1900
+ const verified = /* @__PURE__ */ new WeakMap();
1901
+ let document = base;
1902
+ const ops = [];
1903
+ const effects = [];
1904
+ const recorded = [];
1905
+ return {
1906
+ apply: (before, input) => {
1907
+ const op = structuredClone(input);
1908
+ return applyDocumentOps(before, [op]).map((applied) => {
1909
+ const { document: next, inverse, touched, revisions, folded } = applied;
1910
+ const view = Object.freeze({
1911
+ document: next,
1912
+ revisions: Object.freeze([...revisions]),
1913
+ folded: Object.freeze([...folded])
1914
+ });
1915
+ verified.set(view, {
1916
+ before,
1917
+ document: next,
1918
+ op,
1919
+ effect: {
1920
+ inverse,
1921
+ touched
1922
+ },
1923
+ recorded: {
1924
+ revisions,
1925
+ folded
1926
+ }
1927
+ });
1928
+ return view;
1929
+ });
1930
+ },
1931
+ append: (view) => {
1932
+ const step = verified.get(view);
1933
+ if (step === void 0 || step.before !== document) return false;
1934
+ verified.delete(view);
1935
+ document = step.document;
1936
+ ops.push(step.op);
1937
+ effects.push(step.effect);
1938
+ recorded.push(step.recorded);
1939
+ return true;
1940
+ },
1941
+ prepare: (state, postSelection) => {
1942
+ if (version !== this.currentVersion || base !== this.currentDocument) return refuse("The compiled operations use a stale canonical document.");
1943
+ const combined = combineEdits(document, effects.map(({ inverse, touched }) => ({
1944
+ document,
1945
+ inverse,
1946
+ touched
1947
+ })));
1948
+ return this.prepareJournalledOps({
1949
+ state,
1950
+ ops: [...ops],
1951
+ postSelection,
1952
+ stagedApplied: {
1953
+ ...combined,
1954
+ ...combineRecordedRevisions(recorded)
1955
+ },
1956
+ admission
1957
+ });
1958
+ },
1959
+ /** Stage operations the compiler applied itself, under this admission. */
1960
+ prepareOps: (state, compiled, postSelection) => this.prepareJournalledOps({
1961
+ state,
1962
+ ops: compiled,
1963
+ postSelection,
1964
+ admission
1965
+ })
1966
+ };
1967
+ }
1968
+ prepareJournalledOps({ state, ops, postSelection, stagedApplied, semantic = "structure", admission }) {
1969
+ const story = postSelection.anchor.story;
1970
+ const projected = this.projectStory(story);
1971
+ if (projected.isErr()) return projected;
1972
+ const preSelection = projected.value.selectionAt(state);
1973
+ if (preSelection.isErr()) return preSelection;
1974
+ if (ops.length === 0 || stagedApplied?.inverse.length === 0) return noChange("The intent makes no document change.");
1975
+ const preDocument = this.currentDocument;
1976
+ return this.stage({
1977
+ state,
1978
+ story,
1979
+ ops,
1980
+ selection: postSelection,
1981
+ origin: "input",
1982
+ history: "opened",
1983
+ ...stagedApplied === void 0 ? {} : { stagedApplied },
1984
+ ...admission === void 0 ? {} : { admission },
1985
+ onPublish: (inverse, version, shown) => {
1986
+ const entry = {
1987
+ type: "applied",
1988
+ ops,
1989
+ inverse,
1990
+ preSelection: preSelection.value,
1991
+ postSelection: shown,
1992
+ preDocument,
1993
+ postDocument: this.currentDocument,
1994
+ version,
1995
+ origin: "input",
1996
+ semantic,
1997
+ grouping: "isolated",
1998
+ time: Date.now(),
1999
+ boundary: this.groupingBoundary
2000
+ };
2001
+ this.applied.push({
2002
+ entries: [entry],
2003
+ undo: { type: "entries" },
2004
+ preSelection: preSelection.value,
2005
+ postSelection: shown
2006
+ });
2007
+ this.undone.length = 0;
2008
+ }
2009
+ });
2010
+ }
2011
+ prepareSplit(state) {
2012
+ const from = this.projection.inputAddressAt(state.selection.from);
2013
+ if (from.isErr()) return from;
2014
+ const to = this.projection.inputAddressAt(state.selection.to);
2015
+ if (to.isErr()) return to;
2016
+ const source = this.projection.paragraph(from.value.blockId);
2017
+ const nextStyle = (Object.hasOwn(this.currentDocument.package, "styles") ? this.currentDocument.package.styles : this.styles)?.styles.find(({ styleId }) => styleId === source?.source.formatting?.styleId)?.next;
2018
+ const fresh = this.freshBlockId();
2019
+ if (fresh.isErr()) return fresh;
2020
+ const intents = [{
2021
+ type: "splitParagraph",
2022
+ at: from.value,
2023
+ to: to.value,
2024
+ newBlockId: fresh.value
2025
+ }];
2026
+ if (state.selection.empty && source !== void 0 && from.value.offset === source.text.length && nextStyle !== void 0 && nextStyle !== source.source.formatting?.styleId) intents.push({
2027
+ type: "formatParagraph",
2028
+ at: {
2029
+ ...from.value,
2030
+ offset: 0
2031
+ },
2032
+ patch: { styleId: nextStyle }
2033
+ });
2034
+ return this.prepareIntents(state, { intents });
2035
+ }
2036
+ prepareJoin(state, direction) {
2037
+ const checked = this.checkState(state);
2038
+ if (checked.isErr()) return checked;
2039
+ if (!state.selection.empty) return refuse("Join requires a collapsed text selection.");
2040
+ const at = this.projection.inputAddressAt(state.selection.from);
2041
+ if (at.isErr()) return at;
2042
+ const groups = editorParagraphGroups(this.currentDocument, at.value.story);
2043
+ const index = groups.findIndex(({ paragraphs }) => paragraphs.some((paragraph) => paragraph.paraId === at.value.blockId));
2044
+ if (index < 0 || direction === "backward" && index === 0) return noChange("There is no adjacent paragraph to join.");
2045
+ const firstGroup = groups.at(direction === "backward" ? index - 1 : index);
2046
+ const secondGroup = groups.at(direction === "backward" ? index : index + 1);
2047
+ const first = firstGroup?.paragraphs.at(-1);
2048
+ const second = secondGroup?.paragraphs.at(0);
2049
+ if (!first?.paraId || !second?.paraId) return noChange("There is no adjacent paragraph to join.");
2050
+ if (this.projection.paragraph(first.paraId)?.container !== this.projection.paragraph(second.paraId)?.container) return noChange("There is no adjacent paragraph to join.");
2051
+ if (!isCanonicalJoinBoundary(state, direction)) return refuse("Join requires a caret at a paragraph boundary.");
2052
+ return this.prepareIntent(state, {
2053
+ type: "joinParagraphs",
2054
+ story: at.value.story,
2055
+ blockId: first.paraId,
2056
+ nextBlockId: second.paraId
2057
+ });
2058
+ }
2059
+ prepareResolve(state, { revisionIds, resolution, before = [] }) {
2060
+ const checked = this.checkState(state);
2061
+ if (checked.isErr()) return checked;
2062
+ const preSelection = this.projection.selectionAt(state);
2063
+ if (preSelection.isErr()) return preSelection;
2064
+ const resolve = (ids) => [{
2065
+ type: DOCUMENT_OP_TYPES.RESOLVE_REVISION,
2066
+ story: OP_STORIES.MAIN,
2067
+ revisionIds: ids,
2068
+ decision: resolution
2069
+ }];
2070
+ const changes = getTrackedChangeGroupsForIds(state.doc, revisionIds);
2071
+ const locks = canonicalRevisionLocks({
2072
+ document: this.currentDocument,
2073
+ story: OP_STORIES.MAIN,
2074
+ groups: changes,
2075
+ decision: resolution
2076
+ });
2077
+ const firstHeld = locks.held.at(0);
2078
+ if (firstHeld !== void 0 && locks.held.length === changes.length) return lockRefusal(firstHeld.violation);
2079
+ const lockHeld = locks.held.flatMap(({ ids }) => ids);
2080
+ const resolved = locks.unlocked.flat();
2081
+ const ops = [...before, ...resolved.length === 0 ? [] : resolve(resolved)];
2082
+ const applied = applyDocumentOps(this.currentDocument, ops);
2083
+ if (applied.isErr()) return refuse(applied.error.message);
2084
+ const projected = project({
2085
+ document: applied.value.document,
2086
+ styles: this.styles,
2087
+ caches: this.caches,
2088
+ previous: this.currentProjection
2089
+ });
2090
+ if (projected.isErr()) return projected;
2091
+ const surviving = projected.value.paragraph(preSelection.value.head.blockId);
2092
+ const first = projected.value.firstParagraph;
2093
+ if (first === void 0) return refuse("Resolution left no paragraph.");
2094
+ let offset = surviving ? Math.min(preSelection.value.head.offset, surviving.text.length) : 0;
2095
+ if (surviving && splitsSurrogatePair(surviving.text, offset)) offset -= 1;
2096
+ const caret = {
2097
+ story: OP_STORIES.MAIN,
2098
+ blockId: surviving?.blockId ?? first.blockId,
2099
+ offset
2100
+ };
2101
+ const prepared = this.prepareJournalledOps({
2102
+ state,
2103
+ ops,
2104
+ postSelection: {
2105
+ type: "text",
2106
+ anchor: caret,
2107
+ head: caret
2108
+ },
2109
+ stagedApplied: applied.value
2110
+ });
2111
+ return prepared.isOk() && lockHeld.length > 0 ? Result.ok({
2112
+ ...prepared.value,
2113
+ lockHeld
2114
+ }) : prepared;
2115
+ }
2116
+ /**
2117
+ * Accept or reject one pending suggestion. Rejecting it rejects its
2118
+ * revisions and removes the comments it proposes. Accepting it adopts its
2119
+ * revisions as ordinary tracked changes by `author`, keeping their ids, as
2120
+ * the editor does: the change then waits for review like any other. Its
2121
+ * comments stay as ordinary comments.
2122
+ */
2123
+ prepareSuggestion(state, { suggestionId, resolution, author, date }) {
2124
+ const revisions = documentStories(this.currentDocument).map((story) => ({
2125
+ story,
2126
+ infos: suggestionRevisionInfos(this.currentDocument, story, suggestionId)
2127
+ })).filter(({ infos }) => infos.length > 0);
2128
+ const commentIds = suggestedCommentIds(this.currentDocument, suggestionId);
2129
+ if (revisions.length === 0 && commentIds.length === 0) return noChange(`No pending suggestion ${suggestionId}.`);
2130
+ if (resolution === "reject") return this.prepareResolve(state, {
2131
+ revisionIds: [],
2132
+ resolution: "reject",
2133
+ before: [...commentIds.map((id) => ({
2134
+ type: DOCUMENT_OP_TYPES.DELETE_COMMENT,
2135
+ id,
2136
+ scope: "thread"
2137
+ })), ...revisions.toSorted(({ story: left }, { story: right }) => Number(left === OP_STORIES.MAIN) - Number(right === OP_STORIES.MAIN)).map(({ story, infos }) => ({
2138
+ type: DOCUMENT_OP_TYPES.RESOLVE_REVISION,
2139
+ story,
2140
+ revisionIds: infos.map(({ id }) => id),
2141
+ decision: "reject"
2142
+ }))]
2143
+ });
2144
+ const checked = this.checkState(state);
2145
+ if (checked.isErr()) return checked;
2146
+ const selection = this.projection.selectionAt(state);
2147
+ if (selection.isErr()) return selection;
2148
+ const comments = this.currentDocument.package.document.comments ?? [];
2149
+ const ops = [];
2150
+ for (const { story, infos } of revisions) ops.push({
2151
+ type: DOCUMENT_OP_TYPES.SET_REVISION_INFO,
2152
+ story,
2153
+ infos: infos.map(({ id }) => ({
2154
+ id,
2155
+ author,
2156
+ date
2157
+ }))
2158
+ });
2159
+ for (const comment of comments) if (commentIds.includes(comment.id)) ops.push({
2160
+ type: DOCUMENT_OP_TYPES.UPDATE_COMMENT_CONTENT,
2161
+ id: comment.id,
2162
+ content: comment.content,
2163
+ patch: { suggestionId: null }
2164
+ });
2165
+ return this.prepareJournalledOps({
2166
+ state,
2167
+ ops,
2168
+ postSelection: selection.value
2169
+ });
2170
+ }
2171
+ projectStory(story) {
2172
+ if (story === OP_STORIES.MAIN) return Result.ok(this.projection);
2173
+ const key = storyProjectionKey(story);
2174
+ const body = findStoryBody(this.currentDocument, story);
2175
+ if (body === void 0) {
2176
+ this.storyProjections.delete(key);
2177
+ return refuse("The canonical story no longer exists.");
2178
+ }
2179
+ const cached = this.storyProjections.get(key);
2180
+ const { styles, theme } = this.currentDocument.package;
2181
+ if (cached?.content === body.content && cached.styles === styles && cached.theme === theme) return Result.ok(cached.projection);
2182
+ const projected = project({
2183
+ document: this.currentDocument,
2184
+ styles: this.styles,
2185
+ caches: this.caches,
2186
+ story,
2187
+ ...cached === void 0 ? {} : { previous: cached.projection }
2188
+ });
2189
+ if (projected.isOk()) this.storyProjections.set(key, {
2190
+ content: body.content,
2191
+ styles,
2192
+ theme,
2193
+ projection: projected.value
2194
+ });
2195
+ return projected;
2196
+ }
2197
+ prepareOperations(state, ops) {
2198
+ if (ops.length === 0) return refuse("The operation batch is empty.");
2199
+ const selected = this.projection.selectionAt(state);
2200
+ if (selected.isErr()) return selected;
2201
+ let preparedOps = ops;
2202
+ if (ops.every((op) => op.type === DOCUMENT_OP_TYPES.ADD_NOTE || op.type === DOCUMENT_OP_TYPES.REMOVE_NOTE)) {
2203
+ const tracked = [];
2204
+ let document = this.currentDocument;
2205
+ for (const op of ops) {
2206
+ if (op.type !== DOCUMENT_OP_TYPES.ADD_NOTE && op.type !== DOCUMENT_OP_TYPES.REMOVE_NOTE) panic("A note operation batch contains only note operations.");
2207
+ const allocation = this.allocateIntentIds(document, {
2208
+ type: "replaceFragment",
2209
+ from: {
2210
+ ...op.at,
2211
+ offset: 0
2212
+ },
2213
+ to: {
2214
+ ...op.at,
2215
+ offset: Number.MAX_SAFE_INTEGER
2216
+ },
2217
+ paragraphs: [{
2218
+ type: "paragraph",
2219
+ content: [{
2220
+ type: "run",
2221
+ content: [{
2222
+ type: "break",
2223
+ breakType: "page"
2224
+ }]
2225
+ }]
2226
+ }],
2227
+ openStart: 0,
2228
+ openEnd: 0
2229
+ }, this.leased?.lease);
2230
+ const next = {
2231
+ ...op,
2232
+ ...this.mode.type === "suggesting" ? { revision: {
2233
+ id: allocation.revisionId,
2234
+ author: this.mode.author,
2235
+ date: (/* @__PURE__ */ new Date()).toISOString()
2236
+ } } : {},
2237
+ newIds: allocation.newIds
2238
+ };
2239
+ if (ops.length > 1) {
2240
+ const applied = applyDocumentOp(cloneDocumentWithParagraphPropertySources(document), structuredClone(next));
2241
+ if (applied.isErr()) return refuse(applied.error.message);
2242
+ document = applied.value.document;
2243
+ }
2244
+ tracked.push(next);
2245
+ }
2246
+ preparedOps = tracked;
2247
+ }
2248
+ const addedNotes = preparedOps.filter((op) => op.type === DOCUMENT_OP_TYPES.ADD_NOTE);
2249
+ const atSelection = addedNotes.find(({ at }) => [selected.value.anchor, selected.value.head].some((end) => sameStory(at.story, end.story) && at.blockId === end.blockId && at.offset === end.offset));
2250
+ const caret = atSelection === void 0 ? void 0 : {
2251
+ ...atSelection.at,
2252
+ offset: atSelection.at.offset + addedNotes.filter(({ at }) => sameStory(at.story, atSelection.at.story) && at.blockId === atSelection.at.blockId && at.offset <= atSelection.at.offset).length
2253
+ };
2254
+ const postSelection = addedNotes.length === preparedOps.length && caret !== void 0 ? {
2255
+ type: "text",
2256
+ anchor: caret,
2257
+ head: caret
2258
+ } : selected.value;
2259
+ const preDocument = this.currentDocument;
2260
+ return this.stage({
2261
+ state,
2262
+ ops: preparedOps,
2263
+ selection: postSelection,
2264
+ origin: "input",
2265
+ history: "opened",
2266
+ onPublish: (inverse, version, shown) => {
2267
+ this.applied.push({
2268
+ entries: [{
2269
+ type: "applied",
2270
+ ops: preparedOps,
2271
+ inverse,
2272
+ preSelection: selected.value,
2273
+ postSelection: shown,
2274
+ preDocument,
2275
+ postDocument: this.currentDocument,
2276
+ version,
2277
+ origin: "input",
2278
+ semantic: "structure",
2279
+ grouping: "isolated",
2280
+ time: Date.now(),
2281
+ boundary: this.groupingBoundary
2282
+ }],
2283
+ undo: { type: "entries" },
2284
+ preSelection: selected.value,
2285
+ postSelection: shown
2286
+ });
2287
+ this.undone.length = 0;
2288
+ }
2289
+ });
2290
+ }
2291
+ /**
2292
+ * A step rebased over a remote edit keeps its inverse's preconditions, so
2293
+ * it may no longer apply. Such a step is dropped with every step beneath
2294
+ * it, which were recorded on top of what it would have restored.
2295
+ */
2296
+ rebasedStepApplies(group, ops, stack) {
2297
+ if (group.rebased !== true) return Result.ok(void 0);
2298
+ const applied = applyDocumentOps(this.currentDocument, ops);
2299
+ if (applied.isOk()) return Result.ok(applied.value);
2300
+ const dropped = stack === "undo" ? {
2301
+ undo: this.applied.length,
2302
+ redo: 0
2303
+ } : {
2304
+ undo: 0,
2305
+ redo: this.undone.length
2306
+ };
2307
+ if (stack === "undo") this.applied.length = 0;
2308
+ else this.undone.length = 0;
2309
+ this.reportHistoryDrop(dropped);
2310
+ return refuse(`The ${stack} step no longer applies after a remote edit: ${applied.error.message}`);
2311
+ }
2312
+ /** Called with every history drop a remote edit causes; returns the unsubscribe. */
2313
+ onHistoryDrop(listener) {
2314
+ this.historyDropListeners.add(listener);
2315
+ return () => {
2316
+ this.historyDropListeners.delete(listener);
2317
+ };
2318
+ }
2319
+ /**
2320
+ * Called with every commit once it is published, after the editor and its
2321
+ * plugins accepted the projection and the session's history recorded it;
2322
+ * returns the unsubscribe. A collaboration binding sends exactly these.
2323
+ */
2324
+ onCommitted(listener) {
2325
+ this.committedListeners.add(listener);
2326
+ return () => {
2327
+ this.committedListeners.delete(listener);
2328
+ };
2329
+ }
2330
+ reportHistoryDrop(drop) {
2331
+ if (drop.undo === 0 && drop.redo === 0) return;
2332
+ for (const listener of this.historyDropListeners) listener(drop);
2333
+ }
2334
+ /**
2335
+ * Stage another actor's sequenced edit through the same path as a local
2336
+ * one. `change` is what the optimistic client reported: its ops apply to
2337
+ * this session's document, already rebased over the pending local batches.
2338
+ * It journals no undo step and opens no undo group. The local undo and redo
2339
+ * steps are rebased over it; a step that no longer rebases is dropped with
2340
+ * every step beneath it and reported to `onHistoryDrop`, and a `replaced`
2341
+ * change drops them all. The selection moves by paragraph id and offset,
2342
+ * over a `replaced` change's `moves` when it has them. It waits while a composition is pending; any other refusal means this
2343
+ * session no longer follows the shared document.
2344
+ */
2345
+ prepareRemote(state, change, story = OP_STORIES.MAIN) {
2346
+ const projected = this.projectStory(story);
2347
+ if (projected.isErr()) return projected;
2348
+ const checked = this.checkState(state, projected.value);
2349
+ if (checked.isErr()) return checked;
2350
+ const applied = applyDocumentOps(this.currentDocument, change.batch.ops);
2351
+ if (applied.isErr()) return refuse(applied.error.message);
2352
+ const shown = projected.value.selectionAt(state);
2353
+ const before = shown.isOk() ? shown.value : this.currentSelection;
2354
+ const selection = remoteSelection({
2355
+ selection: before,
2356
+ over: change.type === "replaced" ? change.moves ?? change.batch : change.batch,
2357
+ previous: this.currentDocument,
2358
+ document: applied.value.document,
2359
+ story
2360
+ });
2361
+ const history = this.rebasedHistory(change, selection);
2362
+ const storySelections = [...this.storySelections].flatMap(([key, held]) => findStoryBody(applied.value.document, held.head.story) === void 0 ? [] : [[key, remoteSelection({
2363
+ selection: held,
2364
+ over: change.batch,
2365
+ previous: this.currentDocument,
2366
+ document: applied.value.document,
2367
+ story: held.head.story
2368
+ })]]);
2369
+ return this.stage({
2370
+ state,
2371
+ story,
2372
+ ops: change.batch.ops,
2373
+ selection,
2374
+ origin: "remote",
2375
+ history: "remote",
2376
+ stagedApplied: applied.value,
2377
+ previousProjection: projected.value,
2378
+ opId: change.batch.opId,
2379
+ onPublish: () => {
2380
+ this.storySelections.clear();
2381
+ for (const [key, moved] of storySelections) this.storySelections.set(key, moved);
2382
+ const shownStory = selection.head.story;
2383
+ if (shownStory !== OP_STORIES.MAIN && findStoryBody(applied.value.document, shownStory) !== void 0) this.storySelections.set(storyProjectionKey(shownStory), selection);
2384
+ this.applied.splice(0, this.applied.length, ...history.applied);
2385
+ this.undone.splice(0, this.undone.length, ...history.undone);
2386
+ this.breakUndoGroup();
2387
+ this.reportHistoryDrop(history.dropped);
2388
+ }
2389
+ });
2390
+ }
2391
+ /** Both history stacks as they stand after `change`, top steps first rebased. */
2392
+ rebasedHistory(change, fallback) {
2393
+ if (change.type === "replaced") return {
2394
+ applied: [],
2395
+ undone: [],
2396
+ dropped: {
2397
+ undo: this.applied.length,
2398
+ redo: this.undone.length
2399
+ }
2400
+ };
2401
+ const groups = this.applied.toReversed();
2402
+ const applied = rebaseHistorySteps({
2403
+ document: this.currentDocument,
2404
+ over: change.batch,
2405
+ fallback,
2406
+ steps: groups.map((group) => ({
2407
+ ops: undoOpsOf(group),
2408
+ before: group.postSelection,
2409
+ after: group.preSelection
2410
+ }))
2411
+ }).flatMap((step, index) => {
2412
+ const group = groups.at(index);
2413
+ return group === void 0 ? [] : [{
2414
+ entries: group.entries,
2415
+ undo: {
2416
+ type: "replayed",
2417
+ inverse: step.ops
2418
+ },
2419
+ preSelection: step.after,
2420
+ postSelection: step.before,
2421
+ rebased: true
2422
+ }];
2423
+ });
2424
+ const undoneSteps = this.undone.toReversed();
2425
+ const undone = rebaseHistorySteps({
2426
+ document: this.currentDocument,
2427
+ over: change.batch,
2428
+ fallback,
2429
+ steps: undoneSteps.map(({ group, redoOps }) => ({
2430
+ ops: redoOps,
2431
+ before: group.preSelection,
2432
+ after: group.postSelection
2433
+ }))
2434
+ }).flatMap((step, index) => {
2435
+ const entry = undoneSteps.at(index);
2436
+ return entry === void 0 ? [] : [{
2437
+ type: "undone",
2438
+ group: {
2439
+ ...entry.group,
2440
+ preSelection: step.before,
2441
+ postSelection: step.after,
2442
+ rebased: true
2443
+ },
2444
+ redoOps: step.ops
2445
+ }];
2446
+ });
2447
+ return {
2448
+ applied: applied.toReversed(),
2449
+ undone: undone.toReversed(),
2450
+ dropped: {
2451
+ undo: groups.length - applied.length,
2452
+ redo: undoneSteps.length - undone.length
2453
+ }
2454
+ };
2455
+ }
2456
+ prepareUndo(state, story = OP_STORIES.MAIN) {
2457
+ const group = this.applied.at(-1);
2458
+ if (group === void 0) return refuse("There is no canonical edit to undo.");
2459
+ const ops = undoOpsOf(group);
2460
+ const rebased = this.rebasedStepApplies(group, ops, "undo");
2461
+ if (rebased.isErr()) return rebased;
2462
+ const propertySourceDocument = group.rebased === true ? void 0 : group.entries.at(0)?.preDocument;
2463
+ return this.stage({
2464
+ state,
2465
+ story,
2466
+ ops,
2467
+ selection: group.preSelection,
2468
+ origin: "undo",
2469
+ history: "undo",
2470
+ ...propertySourceDocument === void 0 ? {} : { propertySourceDocument },
2471
+ ...rebased.value === void 0 ? {} : { stagedApplied: rebased.value },
2472
+ onPublish: (redoOps) => {
2473
+ this.applied.pop();
2474
+ this.undone.push({
2475
+ type: "undone",
2476
+ group,
2477
+ redoOps
2478
+ });
2479
+ this.breakUndoGroup();
2480
+ }
2481
+ });
2482
+ }
2483
+ prepareRedo(state, story = OP_STORIES.MAIN) {
2484
+ const undone = this.undone.at(-1);
2485
+ if (undone === void 0) return refuse("There is no canonical edit to redo.");
2486
+ const rebased = this.rebasedStepApplies(undone.group, undone.redoOps, "redo");
2487
+ if (rebased.isErr()) return rebased;
2488
+ const propertySourceDocument = undone.group.rebased === true ? void 0 : undone.group.entries.at(-1)?.postDocument;
2489
+ return this.stage({
2490
+ state,
2491
+ story,
2492
+ ops: undone.redoOps,
2493
+ selection: undone.group.postSelection,
2494
+ origin: "redo",
2495
+ history: "redo",
2496
+ ...propertySourceDocument === void 0 ? {} : { propertySourceDocument },
2497
+ ...rebased.value === void 0 ? {} : { stagedApplied: rebased.value },
2498
+ onPublish: (inverse) => {
2499
+ this.undone.pop();
2500
+ this.applied.push({
2501
+ entries: undone.group.entries,
2502
+ undo: {
2503
+ type: "replayed",
2504
+ inverse
2505
+ },
2506
+ preSelection: undone.group.preSelection,
2507
+ postSelection: undone.group.postSelection,
2508
+ ...undone.group.rebased === true ? { rebased: true } : {}
2509
+ });
2510
+ this.breakUndoGroup();
2511
+ }
2512
+ });
2513
+ }
2514
+ stage({ state, ops, selection, origin, history, onPublish, propertySourceDocument, stagedApplied, story = OP_STORIES.MAIN, previousProjection, opId, typing, admission = CANONICAL_ADMISSION.edit }) {
2515
+ const previous = previousProjection === void 0 ? this.projectStory(story) : Result.ok(previousProjection);
2516
+ if (previous.isErr()) return previous;
2517
+ const checked = this.checkState(state, previous.value);
2518
+ if (checked.isErr()) return checked;
2519
+ const applied = stagedApplied === void 0 ? applyDocumentOps(this.currentDocument, ops) : Result.ok(stagedApplied);
2520
+ if (applied.isErr()) return refuse(applied.error.message);
2521
+ if (applied.value.inverse.length === 0) return noChange("The intent makes no document change.");
2522
+ const locked = admission === CANONICAL_ADMISSION.restage ? null : lockViolationBetween(this.currentDocument, applied.value.document);
2523
+ if (locked !== null) return lockRefusal(locked);
2524
+ if (propertySourceDocument !== void 0) applied.value.document = preservePropertySources({
2525
+ target: applied.value.document,
2526
+ source: propertySourceDocument,
2527
+ indentation: "restore"
2528
+ });
2529
+ const normalized = normalizeCanonicalListRendering(applied.value.document, this.caches.lists);
2530
+ applied.value.document = normalized.document;
2531
+ applied.value.inverse = inverseMeetingDocument(normalized.document, normalized.inverse.concat(applied.value.inverse));
2532
+ const leaseJudgement = origin === "remote" ? this.leased?.admit(applied.value.document) : this.leased?.judge(applied.value.document);
2533
+ if (leaseJudgement?.type === "outside") return refuse(`The ${leaseJudgement.id.kind} id ${leaseJudgement.id.id} is outside this author's id lease.`);
2534
+ const changed = changedStories({
2535
+ document: applied.value.document,
2536
+ previous: this.currentDocument
2537
+ });
2538
+ if (unsupportedEditReason({
2539
+ previous: this.currentDocument,
2540
+ document: applied.value.document,
2541
+ stories: changed
2542
+ }) !== null) return Result.err(new CanonicalSessionError({
2543
+ ground: { gap: CANONICAL_GAP.storyContentProjection },
2544
+ reason: "refused",
2545
+ message: "The operations produce unsupported canonical story content."
2546
+ }));
2547
+ applied.value.document = preservePropertySources({
2548
+ target: applied.value.document,
2549
+ source: this.currentDocument,
2550
+ stories: changed
2551
+ });
2552
+ if (propertySourceDocument !== void 0) applied.value.document = preservePropertySources({
2553
+ target: applied.value.document,
2554
+ source: propertySourceDocument
2555
+ });
2556
+ applied.value.document = withParagraphCopies({
2557
+ document: applied.value.document,
2558
+ story: OP_STORIES.MAIN,
2559
+ copies: ownedSourceCopies(this.sourceOwners, changedWindow(this.currentDocument.package.document.content, applied.value.document.package.document.content).added)
2560
+ });
2561
+ const remembered = changedWindow(this.currentDocument.package.document.content, applied.value.document.package.document.content).added;
2562
+ const projectedStory = findStoryBody(applied.value.document, story) ? story : OP_STORIES.MAIN;
2563
+ const projected = project({
2564
+ document: applied.value.document,
2565
+ styles: this.styles,
2566
+ caches: this.caches,
2567
+ story: projectedStory,
2568
+ previous: sameStory(projectedStory, OP_STORIES.MAIN) ? this.currentProjection : previous.value
2569
+ });
2570
+ if (projected.isErr()) return projected;
2571
+ const bodyProjection = (() => {
2572
+ if (sameStory(projectedStory, OP_STORIES.MAIN)) return projected;
2573
+ if (ops.some(operationChangesBodyProjection)) return project({
2574
+ document: applied.value.document,
2575
+ styles: this.styles,
2576
+ caches: this.caches,
2577
+ previous: this.currentProjection
2578
+ });
2579
+ return Result.ok(this.currentProjection);
2580
+ })();
2581
+ if (bodyProjection.isErr()) return bodyProjection;
2582
+ const transaction = state.tr;
2583
+ const before = state.doc;
2584
+ const after = projected.value.doc;
2585
+ const retainedTokens = /* @__PURE__ */ new Set();
2586
+ const retainPropertyOwner = (node) => {
2587
+ if (node.type.name !== "paragraph") return true;
2588
+ const id = node.attrs["paraId"];
2589
+ const token = getProseParagraphPropertySourceToken(node);
2590
+ const owner = typeof id === "string" ? previous.value.paragraph(id) : void 0;
2591
+ if (typeof token === "string" && owner !== void 0 && getProseParagraphPropertySourceToken(owner.node) === token) retainedTokens.add(token);
2592
+ return false;
2593
+ };
2594
+ const retainPropertyOwnersIn = (node) => {
2595
+ if (retainPropertyOwner(node)) node.descendants(retainPropertyOwner);
2596
+ };
2597
+ let prefix = 0;
2598
+ let from = 0;
2599
+ while (prefix < before.childCount && prefix < after.childCount && before.child(prefix).eq(after.child(prefix))) {
2600
+ from += before.child(prefix).nodeSize;
2601
+ prefix += 1;
2602
+ }
2603
+ let oldEnd = before.childCount;
2604
+ let newEnd = after.childCount;
2605
+ let to = before.content.size;
2606
+ while (oldEnd > prefix && newEnd > prefix && before.child(oldEnd - 1).eq(after.child(newEnd - 1))) {
2607
+ oldEnd -= 1;
2608
+ newEnd -= 1;
2609
+ to -= before.child(oldEnd).nodeSize;
2610
+ }
2611
+ if (oldEnd !== prefix || newEnd !== prefix) {
2612
+ const replacement = [];
2613
+ for (let index = prefix; index < newEnd; index += 1) replacement.push(after.child(index));
2614
+ transaction.replaceWith(from, to, Fragment.fromArray(replacement));
2615
+ replacement.forEach(retainPropertyOwnersIn);
2616
+ }
2617
+ if (!transaction.doc.eq(projected.value.doc)) {
2618
+ transaction.replaceWith(0, transaction.doc.content.size, projected.value.doc.content);
2619
+ after.forEach(retainPropertyOwnersIn);
2620
+ }
2621
+ markParagraphPropertySourceTransfers(transaction, [...retainedTokens].map((selectedToken) => ({
2622
+ displacedToken: null,
2623
+ selectedToken
2624
+ })));
2625
+ for (const [name, value] of Object.entries(projected.value.doc.attrs)) if (transaction.doc.attrs[name] !== value) transaction.setDocAttribute(name, value);
2626
+ if (sameStory(selection.anchor.story, projectedStory) && sameStory(selection.head.story, projectedStory)) {
2627
+ if (!restoreCanonicalSelection({
2628
+ transaction,
2629
+ projection: projected.value,
2630
+ selection,
2631
+ unavailable: {
2632
+ type: "near",
2633
+ anchor: state.selection.anchor
2634
+ }
2635
+ })) return refuse("Canonical history cannot restore the selected inline atom.");
2636
+ }
2637
+ const shown = (sameStory(selection.anchor.story, projectedStory) && sameStory(selection.head.story, projectedStory) ? placeShownSelection(transaction, projected.value) : void 0) ?? selection;
2638
+ const held = projected.value.heldAs(transaction.doc);
2639
+ const heldBody = bodyProjection.value === projected.value ? held : bodyProjection.value;
2640
+ transaction.setMeta(CANONICAL_PROJECTION_META, {
2641
+ type: "canonical",
2642
+ origin,
2643
+ version: this.version + 1
2644
+ });
2645
+ transaction.setMeta("addToHistory", false);
2646
+ const baseVersion = this.version;
2647
+ const baseBoundary = this.groupingBoundary;
2648
+ authorizedProjections.set(transaction, {
2649
+ session: this,
2650
+ version: baseVersion,
2651
+ doc: projected.value.doc
2652
+ });
2653
+ return Result.ok({
2654
+ transaction,
2655
+ ops,
2656
+ document: applied.value.document,
2657
+ projection: held,
2658
+ bodyProjection: heldBody,
2659
+ selection,
2660
+ touched: applied.value.touched,
2661
+ version: baseVersion + 1,
2662
+ origin,
2663
+ history,
2664
+ publish: () => {
2665
+ if (this.isComposing || this.groupingBoundary !== baseBoundary) return refuse("The staged canonical commit crossed a composition or selection boundary.");
2666
+ if (this.version !== baseVersion) return refuse("The staged canonical commit is stale.");
2667
+ if (!isCanonicalProjectionTransaction(transaction, this)) return refuse("The staged canonical projection was changed after preparation.");
2668
+ for (const blockId of applied.value.touched.inserted) this.allocatedBlockIds.add(blockId.toUpperCase());
2669
+ for (const op of ops) {
2670
+ if (op.type === DOCUMENT_OP_TYPES.SPLIT_BLOCK) this.allocatedBlockIds.add(op.newBlockId.toUpperCase());
2671
+ if (op.type === DOCUMENT_OP_TYPES.ADD_NOTE) for (const blockId of paragraphIdsIn(op.note.content)) this.allocatedBlockIds.add(blockId.toUpperCase());
2672
+ }
2673
+ this.advanceBlockId();
2674
+ this.rememberSources(remembered);
2675
+ if (projectedStory !== OP_STORIES.MAIN) {
2676
+ const body = findStoryBody(applied.value.document, projectedStory);
2677
+ if (body === void 0) panic("A staged story projection lost its source.");
2678
+ this.storyProjections.set(storyProjectionKey(projectedStory), {
2679
+ content: body.content,
2680
+ styles: applied.value.document.package.styles,
2681
+ theme: applied.value.document.package.theme,
2682
+ projection: held
2683
+ });
2684
+ }
2685
+ this.currentSelection = selection;
2686
+ const selectedStory = selection.head.story;
2687
+ if (selectedStory !== OP_STORIES.MAIN) this.storySelections.set(storyProjectionKey(selectedStory), selection);
2688
+ for (const [key, kept] of this.storySelections) if (findStoryBody(applied.value.document, kept.head.story) === void 0) this.storySelections.delete(key);
2689
+ this.currentDocument = applied.value.document;
2690
+ this.currentProjection = heldBody;
2691
+ if (leaseJudgement?.type === "allowed") this.leased?.commit(leaseJudgement.census, leaseJudgement.ids);
2692
+ const pending = this.pendingSaveBaseline;
2693
+ for (const ids of [
2694
+ applied.value.touched.modified,
2695
+ applied.value.touched.inserted,
2696
+ applied.value.touched.removed
2697
+ ]) for (const id of ids) {
2698
+ this.saveTouched.add(id);
2699
+ this.touchedSinceOpen.add(id);
2700
+ pending?.touched.add(id);
2701
+ }
2702
+ const bodyOps = ops.filter((op) => !COMMENT_OPERATION_TYPES.has(op.type) && !editsHeaderFooter(op));
2703
+ if (bodyOps.some(operationChangesStructure) || bodyOps.some(operationChangesPackage) || bodyOps.length > 0 && (applied.value.touched.inserted.length > 0 || applied.value.touched.removed.length > 0)) {
2704
+ this.saveStructure = "changed";
2705
+ if (pending) pending.structure = "changed";
2706
+ }
2707
+ this.currentVersion = baseVersion + 1;
2708
+ onPublish(applied.value.inverse, this.currentVersion, shown);
2709
+ const committed = {
2710
+ opId: opId ?? this.newOpId(),
2711
+ ops,
2712
+ inverse: applied.value.inverse,
2713
+ version: this.currentVersion,
2714
+ origin
2715
+ };
2716
+ if (typing !== void 0) recordCanonicalTyping(committed, typing);
2717
+ for (const listener of this.committedListeners) listener(committed);
2718
+ return Result.ok(void 0);
2719
+ }
2720
+ });
2721
+ }
2722
+ };
2723
+ const createCanonicalSession = (document, styles, { idLease, newOpId } = {}) => {
2724
+ const owned = cloneDocumentWithParagraphPropertySources(document);
2725
+ const source = normalizeCanonicalSource(owned);
2726
+ const unsupported = unsupportedSeedReason(source.document);
2727
+ if (unsupported !== null) return refuse(unsupported);
2728
+ const identified = preservePropertySourcesWholeStories({
2729
+ target: normalizeForOps(source.document),
2730
+ source: owned
2731
+ });
2732
+ const validated = validateOpsDocument(identified);
2733
+ if (validated.isErr()) return refuse(validated.error.message);
2734
+ const caches = newStoryProjectionCaches();
2735
+ const normalized = preservePropertySourcesWholeStories({
2736
+ target: normalizeCanonicalListRendering(identified, caches.lists).document,
2737
+ source: owned
2738
+ });
2739
+ const projected = project({
2740
+ document: normalized,
2741
+ styles,
2742
+ caches
2743
+ });
2744
+ if (projected.isErr()) return projected;
2745
+ return Result.ok(new CanonicalSession({
2746
+ document: normalized,
2747
+ projection: projected.value,
2748
+ styles,
2749
+ sourceRestores: canonicalSourceRestores(normalized, source.normalized),
2750
+ caches,
2751
+ idLease,
2752
+ newOpId
2753
+ }));
2754
+ };
2755
+ const hasDeletedParagraphMark = (node) => {
2756
+ const mark = node.attrs["pPrMark"];
2757
+ return typeof mark === "object" && mark !== null && "kind" in mark && (mark.kind === "del" || mark.kind === "moveFrom");
2758
+ };
2759
+ /** Visible graphemes concatenate across retained deletions and deleted paragraph marks. */
2760
+ const visibleDeletionContext = (state) => {
2761
+ const { selection } = state;
2762
+ const paragraphDepth = selection.$from.depth;
2763
+ const containerDepth = paragraphDepth - 1;
2764
+ if (containerDepth < 0 || selection.$from.node(paragraphDepth).type.name !== "paragraph") return refuse("Canonical deletion requires a caret inside a paragraph.");
2765
+ const container = selection.$from.node(containerDepth);
2766
+ const containerStart = selection.$from.start(containerDepth);
2767
+ const index = selection.$from.index(containerDepth);
2768
+ let first = index;
2769
+ while (first > 0 && hasDeletedParagraphMark(container.child(first - 1))) first -= 1;
2770
+ let last = index;
2771
+ while (last + 1 < container.childCount && hasDeletedParagraphMark(container.child(last))) last += 1;
2772
+ let text = "";
2773
+ const physicalStarts = [];
2774
+ const physicalEnds = [];
2775
+ let visibleOffset = 0;
2776
+ let issue;
2777
+ container.forEach((paragraph, paragraphOffset, paragraphIndex) => {
2778
+ if (paragraphIndex < first || paragraphIndex > last) return;
2779
+ const native = canonicalNativeCells(paragraph);
2780
+ if (native.isErr()) {
2781
+ issue = new CanonicalSessionError({
2782
+ ground: { gap: CANONICAL_GAP.dispatch },
2783
+ reason: "refused",
2784
+ message: native.error.message
2785
+ });
2786
+ return;
2787
+ }
2788
+ for (const cell of native.value) {
2789
+ if (cell.type === "zeroWidth" || cell.node.marks.some((mark) => mark.type.name === "deletion")) continue;
2790
+ const value = cell.type === "text" ? cell.text : "";
2791
+ const from = containerStart + paragraphOffset + 1 + cell.from;
2792
+ const to = containerStart + paragraphOffset + 1 + cell.to;
2793
+ if (cell.type !== "text" && selection.from > from && selection.from < to) {
2794
+ issue = new CanonicalSessionError({
2795
+ ground: { gap: CANONICAL_GAP.dispatch },
2796
+ reason: "refused",
2797
+ message: "Character deletion cannot start inside an inline atom."
2798
+ });
2799
+ return;
2800
+ }
2801
+ for (let unit = 0; unit < value.length; unit += 1) {
2802
+ const position = from + (cell.type === "text" ? unit : 0);
2803
+ physicalStarts.push(position);
2804
+ text += value.charAt(unit);
2805
+ physicalEnds.push(cell.type === "text" ? position + 1 : to);
2806
+ if (position < selection.from) visibleOffset += 1;
2807
+ }
2808
+ }
2809
+ });
2810
+ return issue === void 0 ? Result.ok({
2811
+ text,
2812
+ physicalStarts,
2813
+ physicalEnds,
2814
+ visibleOffset
2815
+ }) : Result.err(issue);
2816
+ };
2817
+ const isCanonicalJoinBoundary = (state, direction) => {
2818
+ if (!(state.selection instanceof TextSelection) || !state.selection.empty) return false;
2819
+ const context = visibleDeletionContext(state);
2820
+ if (context.isErr()) return false;
2821
+ const { text, visibleOffset } = context.value;
2822
+ return visibleOffset === (direction === "backward" ? 0 : text.length);
2823
+ };
2824
+ /** Native character deletion consumes one whole visible grapheme. */
2825
+ const deletionRange = (state, direction) => {
2826
+ const { selection } = state;
2827
+ if (selection instanceof NodeSelection && selection.node.isInline && selection.node.isAtom && selection.node.type.name !== "noteMarker") return Result.ok({
2828
+ from: selection.from,
2829
+ to: selection.to
2830
+ });
2831
+ if (selection instanceof CellSelection) return Result.ok({
2832
+ from: selection.from,
2833
+ to: selection.to
2834
+ });
2835
+ if (selection instanceof AllSelection) return Result.ok(canonicalSelectionRange(state));
2836
+ if (!(selection instanceof TextSelection)) return refuse("Canonical deletion requires text, an inline atom, or the whole document selection.");
2837
+ if (!selection.empty) return Result.ok({
2838
+ from: selection.from,
2839
+ to: selection.to
2840
+ });
2841
+ const parent = selection.$from.parent;
2842
+ const offset = selection.$from.parentOffset;
2843
+ if ((direction === "backward" ? parent.childBefore(offset).node : parent.childAfter(offset).node)?.type.name === "noteMarker") return refuse("Automatic note marks cannot be deleted as characters.");
2844
+ const context = visibleDeletionContext(state);
2845
+ if (context.isErr()) return context;
2846
+ const { text, physicalStarts, physicalEnds, visibleOffset } = context.value;
2847
+ if (splitsSurrogatePair(text, visibleOffset)) return refuse("The deletion would split a surrogate pair.");
2848
+ if (splitsGraphemeCluster(text, visibleOffset)) return refuse("Character deletion requires a caret at a grapheme boundary.");
2849
+ if (direction === "backward" && visibleOffset === 0 || direction === "forward" && visibleOffset === text.length) return refuse("There is no visible character to delete in this paragraph.");
2850
+ let boundary = visibleOffset + (direction === "backward" ? -1 : 1);
2851
+ while (splitsGraphemeCluster(text, boundary)) boundary += direction === "backward" ? -1 : 1;
2852
+ const from = physicalStarts.at(direction === "backward" ? boundary : visibleOffset);
2853
+ const to = itemBefore(physicalEnds, direction === "backward" ? visibleOffset : boundary);
2854
+ if (from === void 0 || to === void 0) panic("Canonical deletion lost a grapheme boundary.");
2855
+ return Result.ok({
2856
+ from,
2857
+ to
2858
+ });
2859
+ };
2860
+ /**
2861
+ * The deletion a browser measured (by word or by line) as the visible
2862
+ * characters its range covers whole, in the caret's paragraph: from the first
2863
+ * such character's start to the last one's end. Zero-width anchors at the
2864
+ * range's edges stay, as they do beside a plain character deletion; an inline
2865
+ * atom only partly covered stays; `null` when the range covers no visible
2866
+ * character.
2867
+ */
2868
+ const measuredDeletionRange = (state, measured) => {
2869
+ const context = visibleDeletionContext(state);
2870
+ if (context.isErr()) return context;
2871
+ const { physicalStarts, physicalEnds } = context.value;
2872
+ let from;
2873
+ let to;
2874
+ for (const [unit, start] of physicalStarts.entries()) {
2875
+ const end = physicalEnds.at(unit);
2876
+ if (end === void 0) panic("Canonical deletion lost a visible character's end.");
2877
+ if (start < measured.from || end > measured.to) continue;
2878
+ from ??= start;
2879
+ to = end;
2880
+ }
2881
+ if (from === void 0 || to === void 0) return Result.ok(null);
2882
+ let noteMarkers = 0;
2883
+ state.doc.nodesBetween(from, to, (node) => {
2884
+ if (node.type.name === "noteMarker") noteMarkers += 1;
2885
+ });
2886
+ if (noteMarkers > 0) return refuse("Automatic note marks cannot be deleted as characters.");
2887
+ return Result.ok({
2888
+ from,
2889
+ to
2890
+ });
2891
+ };
2892
+ export { CANONICAL_ADMISSION, CANONICAL_PROJECTION_META, CanonicalSessionError, createCanonicalSession, deletionRange, isCanonicalJoinBoundary, isCanonicalProjectionTransaction, measuredDeletionRange, newStoryProjectionCaches, project as projectCanonicalStory, publishCanonicalProjection };