@blocknote/core 0.54.2 → 0.56.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 (491) hide show
  1. package/dist/BlockNoteExtension-DjEkXkR5.cjs +2 -0
  2. package/dist/BlockNoteExtension-DjEkXkR5.cjs.map +1 -0
  3. package/dist/{BlockNoteExtension-CbvDA0F7.js → BlockNoteExtension-TsTGtIeX.js} +34 -27
  4. package/dist/BlockNoteExtension-TsTGtIeX.js.map +1 -0
  5. package/dist/{UserStore-mj3fXW4D.cjs → UserStore-CTVzVGh-.cjs} +2 -2
  6. package/dist/{UserStore-mj3fXW4D.cjs.map → UserStore-CTVzVGh-.cjs.map} +1 -1
  7. package/dist/{UserStore-C4TzkGEn.js → UserStore-OZJP3K8T.js} +2 -2
  8. package/dist/{UserStore-C4TzkGEn.js.map → UserStore-OZJP3K8T.js.map} +1 -1
  9. package/dist/blocknote.cjs +1 -1
  10. package/dist/blocknote.js +6 -6
  11. package/dist/blocks-COVwe5Cf.cjs +12 -0
  12. package/dist/blocks-COVwe5Cf.cjs.map +1 -0
  13. package/dist/{blocks-Dol85hpH.js → blocks-COYcDVg7.js} +1577 -1155
  14. package/dist/blocks-COYcDVg7.js.map +1 -0
  15. package/dist/blocks.cjs +1 -1
  16. package/dist/blocks.js +2 -2
  17. package/dist/comments.cjs +1 -1
  18. package/dist/comments.cjs.map +1 -1
  19. package/dist/comments.js +69 -43
  20. package/dist/comments.js.map +1 -1
  21. package/dist/{en-uzHzj6eH.js → en-Ch-vvt5e.js} +40 -3
  22. package/dist/en-Ch-vvt5e.js.map +1 -0
  23. package/dist/en-N5lu0-j8.cjs +2 -0
  24. package/dist/en-N5lu0-j8.cjs.map +1 -0
  25. package/dist/extensions-BbM81hHa.js +3069 -0
  26. package/dist/extensions-BbM81hHa.js.map +1 -0
  27. package/dist/extensions-D_WkAfSt.cjs +58 -0
  28. package/dist/extensions-D_WkAfSt.cjs.map +1 -0
  29. package/dist/extensions.cjs +1 -1
  30. package/dist/extensions.js +4 -4
  31. package/dist/locales.cjs +1 -1
  32. package/dist/locales.cjs.map +1 -1
  33. package/dist/locales.js +859 -45
  34. package/dist/locales.js.map +1 -1
  35. package/dist/src-4OQT3z5S.cjs +23 -0
  36. package/dist/src-4OQT3z5S.cjs.map +1 -0
  37. package/dist/src-BmLsLZfE.js +3491 -0
  38. package/dist/src-BmLsLZfE.js.map +1 -0
  39. package/dist/style.css +1 -1
  40. package/dist/webpack-stats.json +1 -1
  41. package/dist/y.cjs +1 -1
  42. package/dist/y.cjs.map +1 -1
  43. package/dist/y.js +1284 -554
  44. package/dist/y.js.map +1 -1
  45. package/dist/yjs.cjs +1 -1
  46. package/dist/yjs.cjs.map +1 -1
  47. package/dist/yjs.js +189 -148
  48. package/dist/yjs.js.map +1 -1
  49. package/package.json +18 -18
  50. package/src/api/blockManipulation/commands/insertBlocks/insertBlocks.ts +45 -6
  51. package/src/api/blockManipulation/commands/insertBlocks/insertPlacement.test.ts +217 -0
  52. package/src/api/blockManipulation/commands/mergeBlocks/mergeBlocks.test.ts +113 -9
  53. package/src/api/blockManipulation/commands/mergeBlocks/mergeBlocks.ts +151 -163
  54. package/src/api/blockManipulation/commands/moveBlocks/moveBlocks.test.ts +47 -31
  55. package/src/api/blockManipulation/commands/moveBlocks/moveBlocks.ts +122 -181
  56. package/src/api/blockManipulation/commands/nestBlock/nestBlock.test.ts +256 -0
  57. package/src/api/blockManipulation/commands/nestBlock/nestBlock.ts +80 -40
  58. package/src/api/blockManipulation/commands/replaceBlocks/replaceBlocks.test.ts +71 -0
  59. package/src/api/blockManipulation/commands/replaceBlocks/replaceBlocks.ts +39 -31
  60. package/src/api/blockManipulation/commands/splitBlock/splitBlock.test.ts +221 -8
  61. package/src/api/blockManipulation/commands/splitBlock/splitBlock.ts +40 -8
  62. package/src/api/blockManipulation/commands/updateBlock/updateBlock.test.ts +272 -40
  63. package/src/api/blockManipulation/commands/updateBlock/updateBlock.ts +138 -117
  64. package/src/api/blockManipulation/getBlock/getBlock.ts +4 -11
  65. package/src/api/blockManipulation/layoutBlocks/fixLayoutBlock.ts +173 -0
  66. package/src/api/blockManipulation/layoutBlocks/layoutBlocks.browser.test.ts +293 -0
  67. package/src/api/blockManipulation/layoutBlocks/layoutBlocks.fixture.ts +145 -0
  68. package/src/api/blockManipulation/layoutBlocks/layoutBlocks.test.ts +783 -0
  69. package/src/api/blockManipulation/layoutBlocks/plainBlocks.test.ts +180 -0
  70. package/src/api/blockManipulation/layoutBlocks/titledBlocks.test.ts +365 -0
  71. package/src/api/blockManipulation/selections/selection.ts +20 -53
  72. package/src/api/blockManipulation/selections/textCursorPosition.ts +17 -72
  73. package/src/api/blockManipulation/setupTestEnv.ts +38 -6
  74. package/src/api/clipboard/fromClipboard/handleFileInsertion.ts +4 -4
  75. package/src/api/clipboard/toClipboard/copyExtension.ts +3 -3
  76. package/src/api/combineTransactionSteps.ts +22 -0
  77. package/src/api/exporters/html/externalHTMLExporter.ts +1 -1
  78. package/src/api/exporters/html/internalHTMLSerializer.ts +4 -4
  79. package/src/api/exporters/html/util/serializeBlocksExternalHTML.ts +111 -36
  80. package/src/api/exporters/html/util/serializeBlocksInternalHTML.ts +51 -21
  81. package/src/api/exporters/markdown/htmlToMarkdown.ts +12 -1
  82. package/src/api/exporters/markdown/markdownExporter.ts +1 -1
  83. package/src/api/getBlockInfoFromPos.test.ts +428 -3
  84. package/src/api/getBlockInfoFromPos.ts +531 -129
  85. package/src/api/getBlocksChangedByTransaction.test.ts +7 -7
  86. package/src/api/getBlocksChangedByTransaction.ts +3 -3
  87. package/src/api/{getChangedRange.ts → getChangedRangeWithAttrs.ts} +2 -2
  88. package/src/api/getChangedRanges.test.ts +391 -0
  89. package/src/api/getChangedRanges.ts +368 -0
  90. package/src/api/nodeConversions/blockToNode.ts +44 -16
  91. package/src/api/nodeConversions/fragmentToBlocks.ts +29 -44
  92. package/src/api/nodeConversions/nodeToBlock.ts +120 -68
  93. package/src/api/nodeUtil.ts +1 -1
  94. package/src/api/parsers/markdown/autolink.ts +23 -0
  95. package/src/api/parsers/markdown/markdownToHtml.ts +115 -11
  96. package/src/blocks/Code/block.test.ts +4 -4
  97. package/src/blocks/Code/helpers/extensions/CodeKeyboardShortcutsExtension.ts +6 -1
  98. package/src/blocks/Heading/block.ts +54 -15
  99. package/src/blocks/ListItem/BulletListItem/block.ts +6 -4
  100. package/src/blocks/ListItem/CheckListItem/block.test.ts +2 -2
  101. package/src/blocks/ListItem/CheckListItem/block.ts +6 -4
  102. package/src/blocks/ListItem/NumberedListItem/IndexingPlugin.ts +14 -17
  103. package/src/blocks/ListItem/NumberedListItem/block.ts +6 -4
  104. package/src/blocks/ListItem/ToggleListItem/block.ts +23 -12
  105. package/src/blocks/Table/block.ts +2 -10
  106. package/src/blocks/ToggleWrapper/createToggleFrame.ts +126 -0
  107. package/src/blocks/ToggleWrapper/toggleBlocks.browser.test.ts +1056 -0
  108. package/src/blocks/defaultBlockTypeItems.test.ts +70 -0
  109. package/src/blocks/defaultBlockTypeItems.ts +99 -0
  110. package/src/blocks/defaultBlocks.test.ts +67 -0
  111. package/src/blocks/defaultBlocks.ts +7 -1
  112. package/src/blocks/index.ts +2 -1
  113. package/src/comments/CommentEditorSubmitExtension.test.ts +141 -0
  114. package/src/comments/CommentEditorSubmitExtension.ts +56 -0
  115. package/src/comments/extension.ts +8 -0
  116. package/src/comments/index.ts +1 -0
  117. package/src/editor/Block.css +286 -154
  118. package/src/editor/BlockNoteEditor.node.test.ts +35 -0
  119. package/src/editor/BlockNoteEditor.test.ts +2 -2
  120. package/src/editor/BlockNoteEditor.ts +165 -50
  121. package/src/editor/BlockNoteExtension.ts +11 -6
  122. package/src/editor/blockColors.browser.test.ts +127 -0
  123. package/src/editor/editor.css +60 -0
  124. package/src/editor/managers/BlockManager.ts +4 -3
  125. package/src/editor/managers/EventManager.browser.test.ts +334 -0
  126. package/src/editor/managers/EventManager.ts +128 -31
  127. package/src/editor/managers/ExtensionManager/ExtensionManager.browser.test.ts +45 -0
  128. package/src/editor/managers/ExtensionManager/ExtensionManager.node.test.ts +209 -0
  129. package/src/editor/managers/ExtensionManager/ExtensionManager.test.ts +88 -1
  130. package/src/editor/managers/ExtensionManager/extensions.ts +10 -1
  131. package/src/editor/managers/ExtensionManager/index.ts +165 -75
  132. package/src/editor/managers/StateManager.ts +14 -4
  133. package/src/editor/managers/StyleManager.browser.test.ts +122 -0
  134. package/src/editor/managers/StyleManager.test.ts +98 -0
  135. package/src/editor/managers/StyleManager.ts +31 -15
  136. package/src/editor/managers/index.ts +1 -0
  137. package/src/editor/transformPasted.ts +14 -13
  138. package/src/exporter/Exporter.test.ts +70 -1
  139. package/src/exporter/Exporter.ts +34 -4
  140. package/src/exporter/mapping.ts +41 -10
  141. package/src/extensions/DropCursor/DropCursor.ts +119 -6
  142. package/src/extensions/DropCursor/dropIntoChildren.ts +80 -0
  143. package/src/extensions/FormattingToolbar/FormattingToolbar.ts +29 -0
  144. package/src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.test.ts +190 -0
  145. package/src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.ts +41 -4
  146. package/src/extensions/Placeholder/Placeholder.test.ts +23 -0
  147. package/src/extensions/Placeholder/Placeholder.ts +8 -7
  148. package/src/extensions/PreviousBlockType/PreviousBlockType.test.ts +36 -0
  149. package/src/extensions/PreviousBlockType/PreviousBlockType.ts +8 -4
  150. package/src/extensions/ReadOnly/ReadOnly.test.ts +181 -0
  151. package/src/extensions/ReadOnly/ReadOnly.ts +73 -0
  152. package/src/extensions/SideMenu/SideMenu.ts +401 -749
  153. package/src/extensions/SideMenu/blockDropHandling.ts +372 -0
  154. package/src/extensions/SideMenu/blockGeometry.browser.test.ts +148 -0
  155. package/src/extensions/SideMenu/blockGeometry.test.ts +46 -0
  156. package/src/extensions/SideMenu/blockGeometry.ts +53 -0
  157. package/src/extensions/SideMenu/dragging.ts +19 -32
  158. package/src/extensions/SideMenu/sideMenuHover.test.ts +36 -0
  159. package/src/extensions/SideMenu/sideMenuHover.ts +270 -0
  160. package/src/extensions/SourceBlockWithPreview/SourceBlockWithPreview.ts +5 -4
  161. package/src/extensions/SuggestionMenu/SuggestionMenu.ts +10 -1
  162. package/src/extensions/SuggestionMenu/getDefaultSlashMenuItems.ts +36 -136
  163. package/src/extensions/SyntaxHighlighting/SyntaxHighlighting.test.ts +14 -4
  164. package/src/extensions/SyntaxHighlighting/SyntaxHighlighting.ts +1 -1
  165. package/src/extensions/SyntaxHighlighting/shiki.ts +1 -1
  166. package/src/extensions/TableHandles/TableHandles.browser.test.ts +3 -1
  167. package/src/extensions/TableHandles/TableHandles.ts +4 -6
  168. package/src/extensions/Versioning/Versioning.browser.test.ts +151 -0
  169. package/src/extensions/Versioning/Versioning.node.test.ts +177 -0
  170. package/src/extensions/Versioning/Versioning.ts +145 -612
  171. package/src/extensions/Versioning/__test__/result.ts +12 -0
  172. package/src/extensions/Versioning/comparison.test.ts +40 -0
  173. package/src/extensions/Versioning/createVersioning.test.ts +867 -0
  174. package/src/extensions/Versioning/createVersioning.ts +499 -0
  175. package/src/extensions/Versioning/formatVersionDate.ts +24 -0
  176. package/src/extensions/Versioning/inMemoryVersioning.test.ts +533 -430
  177. package/src/extensions/Versioning/inMemoryVersioning.ts +246 -251
  178. package/src/extensions/Versioning/index.ts +4 -0
  179. package/src/extensions/Versioning/scrollScheduling.test.ts +51 -0
  180. package/src/extensions/Versioning/scrollToFirstChange.test.ts +320 -0
  181. package/src/extensions/Versioning/scrollToFirstChange.ts +139 -0
  182. package/src/extensions/Versioning/types.ts +219 -0
  183. package/src/extensions/Versioning/versioningState.ts +154 -0
  184. package/src/extensions/blockDOM.browser.test.ts +102 -0
  185. package/src/extensions/blockDOM.test.ts +178 -0
  186. package/src/extensions/blockDOM.ts +135 -0
  187. package/src/extensions/index.ts +2 -0
  188. package/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.test.ts +1719 -53
  189. package/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.ts +645 -531
  190. package/src/extensions/tiptap-extensions/KeyboardShortcuts/blockIdentity.browser.test.ts +152 -0
  191. package/src/extensions/tiptap-extensions/Link/helpers/autolink.ts +4 -9
  192. package/src/extensions/tiptap-extensions/UniqueID/UniqueID.test.ts +10 -24
  193. package/src/extensions/tiptap-extensions/UniqueID/UniqueID.ts +22 -19
  194. package/src/fonts/inter.browser.test.ts +57 -0
  195. package/src/fonts/inter.css +111 -0
  196. package/src/i18n/locales/ar.ts +33 -0
  197. package/src/i18n/locales/de.ts +33 -0
  198. package/src/i18n/locales/en.ts +33 -0
  199. package/src/i18n/locales/es.ts +33 -0
  200. package/src/i18n/locales/fa.ts +33 -0
  201. package/src/i18n/locales/fr.ts +33 -0
  202. package/src/i18n/locales/he.ts +33 -0
  203. package/src/i18n/locales/hr.ts +33 -0
  204. package/src/i18n/locales/is.ts +33 -0
  205. package/src/i18n/locales/it.ts +33 -0
  206. package/src/i18n/locales/ja.ts +33 -0
  207. package/src/i18n/locales/ko.ts +33 -0
  208. package/src/i18n/locales/nl.ts +33 -0
  209. package/src/i18n/locales/no.ts +33 -0
  210. package/src/i18n/locales/pl.ts +33 -0
  211. package/src/i18n/locales/pt.ts +33 -0
  212. package/src/i18n/locales/ru.ts +33 -0
  213. package/src/i18n/locales/sk.ts +33 -0
  214. package/src/i18n/locales/uk.ts +33 -0
  215. package/src/i18n/locales/uz.ts +33 -0
  216. package/src/i18n/locales/vi.ts +33 -0
  217. package/src/i18n/locales/zh-tw.ts +33 -0
  218. package/src/i18n/locales/zh.ts +33 -0
  219. package/src/index.ts +14 -3
  220. package/src/pm-nodes/BlockContainer.test.ts +101 -0
  221. package/src/pm-nodes/BlockContainer.ts +110 -1
  222. package/src/pm-nodes/BlockGroup.ts +2 -1
  223. package/src/pm-nodes/README.md +2 -0
  224. package/src/schema/blocks/children.test.ts +288 -0
  225. package/src/schema/blocks/children.ts +136 -0
  226. package/src/schema/blocks/createSpec.browser.test.ts +176 -0
  227. package/src/schema/blocks/createSpec.test.ts +231 -0
  228. package/src/schema/blocks/createSpec.ts +493 -267
  229. package/src/schema/blocks/frame.test.ts +112 -0
  230. package/src/schema/blocks/frame.ts +337 -0
  231. package/src/schema/blocks/internal.ts +50 -17
  232. package/src/schema/blocks/keyboard.ts +154 -0
  233. package/src/schema/blocks/layoutBlockAttributes.ts +29 -0
  234. package/src/schema/blocks/meta.test.ts +53 -0
  235. package/src/schema/blocks/meta.ts +35 -0
  236. package/src/schema/blocks/renderFrame.test.ts +691 -0
  237. package/src/schema/blocks/types.ts +285 -21
  238. package/src/schema/blocks/validateChildren.ts +156 -0
  239. package/src/schema/dataAttributes.test.ts +72 -0
  240. package/src/schema/dataAttributes.ts +69 -0
  241. package/src/schema/index.ts +3 -0
  242. package/src/schema/inlineContent/internal.ts +7 -12
  243. package/src/schema/markGroups.ts +34 -2
  244. package/src/schema/schema.ts +8 -1
  245. package/src/user/userColors.test.ts +108 -0
  246. package/src/user/userColors.ts +42 -13
  247. package/src/util/browser.ts +24 -0
  248. package/src/y/comments/RESTYjsThreadStore.ts +1 -1
  249. package/src/y/comments/YjsThreadStore.test.ts +1 -1
  250. package/src/y/comments/YjsThreadStore.ts +27 -27
  251. package/src/y/comments/YjsThreadStoreBase.ts +2 -2
  252. package/src/y/comments/yjsHelpers.ts +11 -11
  253. package/src/y/extensions/AttributionExtension.test.ts +271 -2
  254. package/src/y/extensions/AttributionExtension.ts +146 -123
  255. package/src/y/extensions/DiffVersioningExtension.test.ts +67 -18
  256. package/src/y/extensions/DiffVersioningExtension.ts +95 -123
  257. package/src/y/extensions/EmptyDocBinding.test.ts +282 -0
  258. package/src/y/extensions/ForkYDoc.node.test.ts +77 -0
  259. package/src/y/extensions/ForkYDoc.test.ts +93 -2
  260. package/src/y/extensions/ForkYDoc.ts +22 -13
  261. package/src/y/extensions/History.test.ts +125 -0
  262. package/src/y/extensions/RelativePositionMapping.test.ts +35 -0
  263. package/src/y/extensions/RelativePositionMapping.ts +7 -11
  264. package/src/y/extensions/Versioning.node.test.ts +126 -0
  265. package/src/y/extensions/Versioning.test.ts +110 -401
  266. package/src/y/extensions/Versioning.ts +66 -107
  267. package/src/y/extensions/YAttributionMarks.ts +111 -9
  268. package/src/y/extensions/YCursorPlugin.ts +3 -0
  269. package/src/y/extensions/YSync.node.test.ts +75 -0
  270. package/src/y/extensions/YSync.ts +76 -4
  271. package/src/y/extensions/YSyncRemount.test.ts +99 -0
  272. package/src/y/extensions/blockMatchNodes.ts +20 -29
  273. package/src/y/extensions/index.ts +10 -26
  274. package/src/y/extensions/legacyYjsDocBinding.test.ts +652 -0
  275. package/src/y/extensions/nestingChanges.test.ts +326 -0
  276. package/src/y/extensions/persistentBlockGroups.test.ts +1709 -0
  277. package/src/y/extensions/persistentBlockGroups.ts +953 -0
  278. package/src/y/extensions/snapshotCodec.test.ts +105 -0
  279. package/src/y/extensions/snapshotCodec.ts +39 -0
  280. package/src/y/extensions/snapshotPreview.test.ts +201 -0
  281. package/src/y/extensions/snapshotPreview.ts +292 -0
  282. package/src/y/extensions/tableReshape.test.ts +121 -0
  283. package/src/y/extensions/v1BindingSnapshotDiff.test.ts +121 -0
  284. package/src/y/extensions/versionDiffAttribution.test.ts +944 -0
  285. package/src/y/extensions/versionDiffPerformance.test.ts +101 -0
  286. package/src/y/index.ts +1 -0
  287. package/src/y/utils.test.ts +289 -22
  288. package/src/y/utils.ts +167 -43
  289. package/src/y/versioning/__test__/fixtures/activity-all-after.json +5 -5
  290. package/src/y/versioning/__test__/fixtures/activity-all.json +3 -3
  291. package/src/y/versioning/__test__/fixtures/activity-filtered-after.json +2 -2
  292. package/src/y/versioning/__test__/yhub.test.ts +902 -721
  293. package/src/y/versioning/index.ts +6 -1
  294. package/src/y/versioning/yhub.ts +316 -603
  295. package/src/y/versioning/yhubClient.ts +345 -0
  296. package/src/yjs/comments/RESTYjsThreadStore.test.ts +10 -0
  297. package/src/yjs/extensions/FixUpSchema.ts +11 -0
  298. package/src/yjs/extensions/ForkYDoc.browser.test.ts +84 -0
  299. package/src/yjs/extensions/ForkYDoc.node.test.ts +231 -0
  300. package/src/yjs/extensions/ForkYDoc.test.ts +68 -1
  301. package/src/yjs/extensions/ForkYDoc.ts +57 -39
  302. package/src/yjs/extensions/Versioning.test.ts +345 -530
  303. package/src/yjs/extensions/Versioning.ts +111 -68
  304. package/src/yjs/extensions/index.ts +1 -1
  305. package/src/yjs/index.ts +4 -0
  306. package/types/src/api/blockManipulation/commands/insertBlocks/insertBlocks.d.ts +2 -1
  307. package/types/src/api/blockManipulation/commands/mergeBlocks/mergeBlocks.d.ts +24 -24
  308. package/types/src/api/blockManipulation/commands/nestBlock/nestBlock.d.ts +3 -2
  309. package/types/src/api/blockManipulation/commands/replaceBlocks/replaceBlocks.d.ts +1 -1
  310. package/types/src/api/blockManipulation/commands/splitBlock/splitBlock.d.ts +2 -2
  311. package/types/src/api/blockManipulation/layoutBlocks/fixLayoutBlock.d.ts +34 -0
  312. package/types/src/api/blockManipulation/layoutBlocks/layoutBlocks.browser.test.d.ts +1 -0
  313. package/types/src/api/blockManipulation/layoutBlocks/layoutBlocks.fixture.d.ts +460 -0
  314. package/types/src/api/blockManipulation/layoutBlocks/layoutBlocks.test.d.ts +1 -0
  315. package/types/src/api/blockManipulation/layoutBlocks/plainBlocks.test.d.ts +1 -0
  316. package/types/src/api/blockManipulation/layoutBlocks/titledBlocks.test.d.ts +1 -0
  317. package/types/src/api/blockManipulation/setupTestEnv.d.ts +15 -69
  318. package/types/src/api/combineTransactionSteps.d.ts +12 -0
  319. package/types/src/api/getBlockInfoFromPos.d.ts +218 -44
  320. package/types/src/api/{getChangedRange.d.ts → getChangedRangeWithAttrs.d.ts} +1 -1
  321. package/types/src/api/getChangedRanges.d.ts +23 -0
  322. package/types/src/api/getChangedRanges.test.d.ts +1 -0
  323. package/types/src/api/nodeConversions/fragmentToBlocks.d.ts +0 -3
  324. package/types/src/api/parsers/markdown/autolink.d.ts +5 -0
  325. package/types/src/blocks/Code/helpers/extensions/CodeKeyboardShortcutsExtension.d.ts +4 -0
  326. package/types/src/blocks/ToggleWrapper/createToggleFrame.d.ts +29 -0
  327. package/types/src/blocks/ToggleWrapper/toggleBlocks.browser.test.d.ts +1 -0
  328. package/types/src/blocks/defaultBlockTypeItems.d.ts +37 -0
  329. package/types/src/blocks/defaultBlockTypeItems.test.d.ts +1 -0
  330. package/types/src/blocks/defaultBlocks.test.d.ts +1 -0
  331. package/types/src/blocks/index.d.ts +2 -1
  332. package/types/src/comments/CommentEditorSubmitExtension.d.ts +19 -0
  333. package/types/src/comments/CommentEditorSubmitExtension.test.d.ts +1 -0
  334. package/types/src/comments/extension.d.ts +7 -0
  335. package/types/src/comments/index.d.ts +1 -0
  336. package/types/src/editor/BlockNoteEditor.d.ts +88 -27
  337. package/types/src/editor/BlockNoteEditor.node.test.d.ts +1 -0
  338. package/types/src/editor/BlockNoteExtension.d.ts +3 -0
  339. package/types/src/editor/blockColors.browser.test.d.ts +1 -0
  340. package/types/src/editor/managers/BlockManager.d.ts +4 -3
  341. package/types/src/editor/managers/EventManager.browser.test.d.ts +1 -0
  342. package/types/src/editor/managers/EventManager.d.ts +55 -0
  343. package/types/src/editor/managers/ExtensionManager/ExtensionManager.browser.test.d.ts +1 -0
  344. package/types/src/editor/managers/ExtensionManager/ExtensionManager.node.test.d.ts +1 -0
  345. package/types/src/editor/managers/ExtensionManager/index.d.ts +15 -3
  346. package/types/src/editor/managers/StateManager.d.ts +1 -1
  347. package/types/src/editor/managers/StyleManager.browser.test.d.ts +1 -0
  348. package/types/src/editor/managers/StyleManager.d.ts +4 -2
  349. package/types/src/editor/managers/StyleManager.test.d.ts +1 -0
  350. package/types/src/editor/managers/index.d.ts +1 -0
  351. package/types/src/editor/transformPasted.d.ts +1 -1
  352. package/types/src/exporter/Exporter.d.ts +11 -4
  353. package/types/src/exporter/mapping.d.ts +13 -1
  354. package/types/src/extensions/DropCursor/DropCursor.d.ts +1 -1
  355. package/types/src/extensions/DropCursor/dropIntoChildren.d.ts +38 -0
  356. package/types/src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.d.ts +1 -1
  357. package/types/src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.test.d.ts +1 -0
  358. package/types/src/extensions/Placeholder/Placeholder.test.d.ts +1 -0
  359. package/types/src/extensions/ReadOnly/ReadOnly.d.ts +21 -0
  360. package/types/src/extensions/ReadOnly/ReadOnly.test.d.ts +1 -0
  361. package/types/src/extensions/SideMenu/SideMenu.d.ts +49 -88
  362. package/types/src/extensions/SideMenu/blockDropHandling.d.ts +11 -0
  363. package/types/src/extensions/SideMenu/blockGeometry.browser.test.d.ts +1 -0
  364. package/types/src/extensions/SideMenu/blockGeometry.d.ts +22 -0
  365. package/types/src/extensions/SideMenu/blockGeometry.test.d.ts +1 -0
  366. package/types/src/extensions/SideMenu/dragging.d.ts +0 -4
  367. package/types/src/extensions/SideMenu/sideMenuHover.d.ts +58 -0
  368. package/types/src/extensions/SideMenu/sideMenuHover.test.d.ts +1 -0
  369. package/types/src/extensions/SourceBlockWithPreview/SourceBlockWithPreview.d.ts +3 -0
  370. package/types/src/extensions/SourceInlineContentWithPreview/SourceInlineContentWithPreview.d.ts +1 -0
  371. package/types/src/extensions/Versioning/Versioning.browser.test.d.ts +1 -0
  372. package/types/src/extensions/Versioning/Versioning.d.ts +34 -311
  373. package/types/src/extensions/Versioning/Versioning.node.test.d.ts +1 -0
  374. package/types/src/extensions/Versioning/__test__/result.d.ts +3 -0
  375. package/types/src/extensions/Versioning/comparison.test.d.ts +1 -0
  376. package/types/src/extensions/Versioning/createVersioning.d.ts +32 -0
  377. package/types/src/extensions/Versioning/createVersioning.test.d.ts +1 -0
  378. package/types/src/extensions/Versioning/formatVersionDate.d.ts +7 -0
  379. package/types/src/extensions/Versioning/inMemoryVersioning.d.ts +64 -36
  380. package/types/src/extensions/Versioning/index.d.ts +4 -0
  381. package/types/src/extensions/Versioning/scrollScheduling.test.d.ts +1 -0
  382. package/types/src/extensions/Versioning/scrollToFirstChange.d.ts +18 -0
  383. package/types/src/extensions/Versioning/scrollToFirstChange.test.d.ts +1 -0
  384. package/types/src/extensions/Versioning/types.d.ts +239 -0
  385. package/types/src/extensions/Versioning/versioningState.d.ts +43 -0
  386. package/types/src/extensions/blockDOM.browser.test.d.ts +1 -0
  387. package/types/src/extensions/blockDOM.d.ts +37 -0
  388. package/types/src/extensions/blockDOM.test.d.ts +1 -0
  389. package/types/src/extensions/index.d.ts +2 -0
  390. package/types/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.d.ts +1 -0
  391. package/types/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.test.d.ts +3 -0
  392. package/types/src/extensions/tiptap-extensions/KeyboardShortcuts/blockIdentity.browser.test.d.ts +1 -0
  393. package/types/src/fonts/inter.browser.test.d.ts +2 -0
  394. package/types/src/i18n/locales/en.d.ts +33 -0
  395. package/types/src/i18n/locales/fa.d.ts +33 -0
  396. package/types/src/i18n/locales/sk.d.ts +33 -0
  397. package/types/src/index.d.ts +7 -3
  398. package/types/src/pm-nodes/BlockContainer.d.ts +6 -0
  399. package/types/src/pm-nodes/BlockContainer.test.d.ts +1 -0
  400. package/types/src/schema/blocks/children.d.ts +39 -0
  401. package/types/src/schema/blocks/children.test.d.ts +1 -0
  402. package/types/src/schema/blocks/createSpec.browser.test.d.ts +1 -0
  403. package/types/src/schema/blocks/createSpec.d.ts +13 -0
  404. package/types/src/schema/blocks/frame.d.ts +109 -0
  405. package/types/src/schema/blocks/frame.test.d.ts +1 -0
  406. package/types/src/schema/blocks/internal.d.ts +6 -0
  407. package/types/src/schema/blocks/keyboard.d.ts +111 -0
  408. package/types/src/schema/blocks/layoutBlockAttributes.d.ts +9 -0
  409. package/types/src/schema/blocks/meta.d.ts +14 -0
  410. package/types/src/schema/blocks/meta.test.d.ts +1 -0
  411. package/types/src/schema/blocks/renderFrame.test.d.ts +1 -0
  412. package/types/src/schema/blocks/types.d.ts +228 -15
  413. package/types/src/schema/blocks/validateChildren.d.ts +5 -0
  414. package/types/src/schema/dataAttributes.d.ts +19 -0
  415. package/types/src/schema/dataAttributes.test.d.ts +1 -0
  416. package/types/src/schema/index.d.ts +3 -0
  417. package/types/src/schema/markGroups.d.ts +8 -0
  418. package/types/src/user/userColors.d.ts +24 -3
  419. package/types/src/user/userColors.test.d.ts +1 -0
  420. package/types/src/util/browser.d.ts +2 -0
  421. package/types/src/y/comments/RESTYjsThreadStore.d.ts +1 -1
  422. package/types/src/y/comments/YjsThreadStore.d.ts +1 -1
  423. package/types/src/y/comments/YjsThreadStoreBase.d.ts +2 -2
  424. package/types/src/y/comments/yjsHelpers.d.ts +5 -5
  425. package/types/src/y/extensions/AttributionExtension.d.ts +19 -21
  426. package/types/src/y/extensions/DiffVersioningExtension.d.ts +9 -4
  427. package/types/src/y/extensions/EmptyDocBinding.test.d.ts +1 -0
  428. package/types/src/y/extensions/ForkYDoc.d.ts +3 -1
  429. package/types/src/y/extensions/ForkYDoc.node.test.d.ts +1 -0
  430. package/types/src/y/extensions/History.test.d.ts +1 -0
  431. package/types/src/y/extensions/Versioning.d.ts +4 -15
  432. package/types/src/y/extensions/Versioning.node.test.d.ts +1 -0
  433. package/types/src/y/extensions/YAttributionMarks.d.ts +13 -2
  434. package/types/src/y/extensions/YCursorPlugin.d.ts +1 -0
  435. package/types/src/y/extensions/YSync.d.ts +4 -18
  436. package/types/src/y/extensions/YSync.node.test.d.ts +1 -0
  437. package/types/src/y/extensions/YSyncRemount.test.d.ts +1 -0
  438. package/types/src/y/extensions/blockMatchNodes.d.ts +0 -22
  439. package/types/src/y/extensions/index.d.ts +27 -44
  440. package/types/src/y/extensions/legacyYjsDocBinding.test.d.ts +1 -0
  441. package/types/src/y/extensions/nestingChanges.test.d.ts +1 -0
  442. package/types/src/y/extensions/persistentBlockGroups.d.ts +189 -0
  443. package/types/src/y/extensions/persistentBlockGroups.test.d.ts +1 -0
  444. package/types/src/y/extensions/snapshotCodec.d.ts +13 -0
  445. package/types/src/y/extensions/snapshotCodec.test.d.ts +1 -0
  446. package/types/src/y/extensions/snapshotPreview.d.ts +21 -0
  447. package/types/src/y/extensions/snapshotPreview.test.d.ts +1 -0
  448. package/types/src/y/extensions/tableReshape.test.d.ts +1 -0
  449. package/types/src/y/extensions/v1BindingSnapshotDiff.test.d.ts +1 -0
  450. package/types/src/y/extensions/versionDiffAttribution.test.d.ts +1 -0
  451. package/types/src/y/extensions/versionDiffPerformance.test.d.ts +1 -0
  452. package/types/src/y/index.d.ts +1 -0
  453. package/types/src/y/utils.d.ts +39 -19
  454. package/types/src/y/versioning/index.d.ts +1 -1
  455. package/types/src/y/versioning/yhub.d.ts +69 -86
  456. package/types/src/y/versioning/yhubClient.d.ts +67 -0
  457. package/types/src/yjs/extensions/ForkYDoc.browser.test.d.ts +1 -0
  458. package/types/src/yjs/extensions/ForkYDoc.d.ts +2 -0
  459. package/types/src/yjs/extensions/ForkYDoc.node.test.d.ts +1 -0
  460. package/types/src/yjs/extensions/Versioning.d.ts +36 -22
  461. package/types/src/yjs/extensions/index.d.ts +2 -1
  462. package/types/src/yjs/index.d.ts +1 -0
  463. package/dist/BlockNoteExtension-BJCLnwrE.cjs +0 -2
  464. package/dist/BlockNoteExtension-BJCLnwrE.cjs.map +0 -1
  465. package/dist/BlockNoteExtension-CbvDA0F7.js.map +0 -1
  466. package/dist/blocks-CTB_5Vyj.cjs +0 -12
  467. package/dist/blocks-CTB_5Vyj.cjs.map +0 -1
  468. package/dist/blocks-Dol85hpH.js.map +0 -1
  469. package/dist/en-BuzSuuTq.cjs +0 -2
  470. package/dist/en-BuzSuuTq.cjs.map +0 -1
  471. package/dist/en-uzHzj6eH.js.map +0 -1
  472. package/dist/extensions-B7Rsp_Ft.cjs +0 -58
  473. package/dist/extensions-B7Rsp_Ft.cjs.map +0 -1
  474. package/dist/extensions-D6JcJCwd.js +0 -2138
  475. package/dist/extensions-D6JcJCwd.js.map +0 -1
  476. package/dist/src-Buuo5l7X.js +0 -3317
  477. package/dist/src-Buuo5l7X.js.map +0 -1
  478. package/dist/src-C54Ok9E0.cjs +0 -23
  479. package/dist/src-C54Ok9E0.cjs.map +0 -1
  480. package/src/api/blockManipulation/commands/replaceBlocks/util/fixColumnList.ts +0 -173
  481. package/src/blocks/ListItem/ListItemKeyboardShortcuts.ts +0 -63
  482. package/src/blocks/ToggleWrapper/createToggleWrapper.ts +0 -197
  483. package/src/blocks/utils/listItemEnterHandler.ts +0 -43
  484. package/src/extensions/Versioning/Versioning.test.ts +0 -435
  485. package/src/extensions/getDraggableBlockFromElement.ts +0 -19
  486. package/types/src/api/blockManipulation/commands/replaceBlocks/util/fixColumnList.d.ts +0 -32
  487. package/types/src/blocks/ListItem/ListItemKeyboardShortcuts.d.ts +0 -2
  488. package/types/src/blocks/ToggleWrapper/createToggleWrapper.d.ts +0 -15
  489. package/types/src/blocks/utils/listItemEnterHandler.d.ts +0 -2
  490. package/types/src/extensions/getDraggableBlockFromElement.d.ts +0 -5
  491. /package/types/src/{extensions/Versioning/Versioning.test.d.ts → api/blockManipulation/commands/insertBlocks/insertPlacement.test.d.ts} +0 -0
@@ -1,785 +1,966 @@
1
- import {
2
- afterEach,
3
- beforeEach,
4
- describe,
5
- expect,
6
- it,
7
- vi,
8
- } from "vite-plus/test";
9
- import { encodeAny } from "lib0/buffer";
1
+ // @vitest-environment node
2
+ import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
3
+ import { decodeAny, encodeAny } from "lib0/buffer";
10
4
  import * as Y from "@y/y";
11
-
12
5
  import {
13
- CURRENT_VERSION_ID,
14
- type VersionSnapshot,
15
- } from "../../../extensions/Versioning/index.js";
16
- import { createYHubVersioningEndpoints } from "../yhub.js";
6
+ configureYProsemirror,
7
+ docToDelta,
8
+ ySyncPluginKey,
9
+ } from "@y/prosemirror";
10
+ import {
11
+ createYHubVersionStorage,
12
+ YVersioningExtension,
13
+ type YHubVersionStorageOptions,
14
+ } from "../yhub.js";
15
+ import { YHubClient } from "../yhubClient.js";
16
+ import { createVersioning } from "../../../extensions/Versioning/createVersioning.js";
17
+ import { resultValue } from "../../../extensions/Versioning/__test__/result.js";
17
18
  import { BlockNoteEditor } from "../../../editor/BlockNoteEditor.js";
18
- import { createExtension } from "../../../editor/BlockNoteExtension.js";
19
-
20
- // ---------------------------------------------------------------------------
21
- // Fixture data — version entries now carry an `id` custom attribution (UUID).
22
- // ---------------------------------------------------------------------------
23
-
24
- const VERSION_ENTRY_1 = {
25
- from: 1782218082853,
26
- to: 1782218082853,
27
- by: "user-1",
28
- customAttributions: [
29
- { k: "type", v: "version" },
30
- { k: "id", v: "uuid-version-1" },
31
- { k: "name", v: "Test Version 1" },
32
- ],
33
- };
34
-
35
- const VERSION_ENTRY_2 = {
36
- from: 1782218211312,
37
- to: 1782218211312,
38
- by: "user-2, user-3",
39
- customAttributions: [
40
- { k: "type", v: "version" },
41
- { k: "id", v: "uuid-version-2" },
42
- { k: "name", v: "Test Version 2" },
43
- ],
44
- };
45
-
46
- // Snapshots as produced by `list()` (see `activityToSnapshot`): the activity
47
- // entry's `to` timestamp becomes both `createdAt` and `updatedAt`. The
48
- // changeset/rollback APIs are now driven by these timestamps directly, so the
49
- // endpoints no longer make an activity lookup to resolve them. The entry's
50
- // comma-separated `by` user-ids are split into the snapshot's raw `by` array.
51
- const SNAPSHOT_1: VersionSnapshot = {
52
- id: "uuid-version-1",
53
- name: "Test Version 1",
54
- createdAt: VERSION_ENTRY_1.to,
55
- updatedAt: VERSION_ENTRY_1.to,
56
- by: ["user-1"],
57
- };
58
-
59
- const SNAPSHOT_2: VersionSnapshot = {
60
- id: "uuid-version-2",
61
- name: "Test Version 2",
62
- createdAt: VERSION_ENTRY_2.to,
63
- updatedAt: VERSION_ENTRY_2.to,
64
- by: ["user-2", "user-3"],
19
+ import type { VersioningController } from "../../../extensions/Versioning/Versioning.js";
20
+ import { withCollaboration } from "../../extensions/index.js";
21
+ import {
22
+ _blocksToProsemirrorNode,
23
+ docDiffToDelta,
24
+ yNodeToTransaction,
25
+ } from "../../utils.js";
26
+
27
+ const options = { baseUrl: "https://yhub.test/api", org: "org", docId: "doc" };
28
+ const signal = new AbortController().signal;
29
+ const first = { from: 1000, to: 1000, by: ["alice"] };
30
+ const latest = { from: 2000, to: 2000, by: ["bob"] };
31
+ const version = {
32
+ type: "version:v1" as const,
33
+ t: 1000,
34
+ name: "Milestone",
35
+ custom: { restoredFrom: 42, ticket: "BN-1" },
36
+ updatedAt: 3000,
65
37
  };
38
+ const cleanup: Array<() => void> = [];
39
+ let fetchSpy = vi.spyOn(globalThis, "fetch");
40
+ beforeEach(() => {
41
+ fetchSpy = vi.spyOn(globalThis, "fetch");
42
+ });
43
+ afterEach(() => {
44
+ for (const dispose of cleanup.splice(0)) {
45
+ dispose();
46
+ }
47
+ vi.restoreAllMocks();
48
+ });
66
49
 
67
- const PATCH_RESPONSE = { success: true, message: "Document updated" };
50
+ function response(body: unknown, status = 200) {
51
+ return new Response(status === 204 ? null : new Uint8Array(encodeAny(body)), {
52
+ status,
53
+ });
54
+ }
68
55
 
69
- function makeChangeset(opts: { ydoc?: boolean; attributions?: boolean } = {}) {
56
+ function storage(activityParams?: YHubVersionStorageOptions["activityParams"]) {
70
57
  const doc = new Y.Doc();
71
- const frag = doc.get("default", "XmlFragment");
72
- frag.insert(0, ["hello"]);
58
+ const fragment = doc.get("default");
59
+ cleanup.push(() => doc.destroy());
73
60
  return {
74
- ...(opts.ydoc !== false ? { ydoc: Y.encodeStateAsUpdate(doc) } : {}),
75
- ...(opts.attributions ? { attributions: new Uint8Array([0]) } : {}),
61
+ api: createYHubVersionStorage({
62
+ ...options,
63
+ activityParams,
64
+ fragment,
65
+ beforeRestoreName: "Before restore",
66
+ }),
67
+ doc,
68
+ fragment,
76
69
  };
77
70
  }
78
71
 
79
- // ---------------------------------------------------------------------------
80
- // Helpers
81
- // ---------------------------------------------------------------------------
82
-
83
- const BASE_URL = "https://yhub.test/api";
84
- const ORG = "test-org";
85
- const DOC_ID = "test-doc";
86
-
87
- // The factory returns a callback that receives the editor instance (used to
88
- // stamp `create`d snapshots with the current cursor user's id). Author ids are
89
- // passed through raw on `VersionSnapshot.by` — resolving them to user info is
90
- // the view layer's job, not the endpoints'. These tests create a bare editor
91
- // with no collaboration extensions, so `create` gets no author id.
92
- function makeEndpoints() {
93
- const editor = BlockNoteEditor.create();
94
- return createYHubVersioningEndpoints({
95
- baseUrl: BASE_URL,
96
- org: ORG,
97
- docId: DOC_ID,
98
- activityLimit: 50,
99
- })(editor);
72
+ function request(index: number) {
73
+ const [url, init] = fetchSpy.mock.calls[index];
74
+ return {
75
+ url: new URL(url instanceof Request ? url.url : url),
76
+ method: init?.method ?? "GET",
77
+ body: init?.body instanceof Uint8Array ? decodeAny(init.body) : undefined,
78
+ signal: init?.signal,
79
+ };
100
80
  }
101
81
 
102
- // A lightweight stand-in for the real `ySync` extension. `getVersionNamesMap`
103
- // in yhub.ts reads the live collaboration doc exclusively via
104
- // `editor.getExtension("ySync")?.fragment.doc`, so a stub that just exposes the
105
- // fragment is enough to exercise the mutable `__bn_version_names` name store
106
- // without wiring up the full collaboration/prosemirror sync machinery.
107
- const ySyncStub = (fragment: Y.Type) =>
108
- createExtension({ key: "ySync", fragment } as any);
109
-
110
- // Build endpoints against an editor that has a `ySync` extension whose fragment
111
- // belongs to `doc`, so the mutable version-name store on `doc` is reachable.
112
- function makeCollabEndpoints(doc: Y.Doc) {
113
- const fragment = doc.get("default", "XmlFragment") as unknown as Y.Type;
114
- (fragment as any).insert(0, ["hello"]);
115
- const editor = BlockNoteEditor.create({
116
- extensions: [ySyncStub(fragment)],
82
+ /**
83
+ * Types `a`, `b`, `c` as separate edits at 1000, 1100 and 1200 (by the given
84
+ * authors), serves them through a mocked YHub with the given activity, and
85
+ * returns each character of the shown comparison with the authors that the
86
+ * diff credits it to (none = not changed).
87
+ */
88
+ async function compareCharacters({
89
+ authors,
90
+ activity,
91
+ target,
92
+ compareTo,
93
+ showCurrentVersion = false,
94
+ }: {
95
+ authors: [string, string, string];
96
+ activity: { first: unknown; history: unknown[] };
97
+ target: { type: "current" } | { type: "snapshot"; id: string };
98
+ compareTo: (history: { id: string }[]) => string;
99
+ showCurrentVersion?: boolean;
100
+ }) {
101
+ const { api, doc, fragment } = storage();
102
+ const editor = BlockNoteEditor.create(
103
+ withCollaboration({
104
+ extensions: [
105
+ YVersioningExtension({ storage: { ...api, showCurrentVersion } }),
106
+ ],
107
+ collaboration: { fragment, user: { name: "Alice", color: "red" } },
108
+ }),
109
+ );
110
+ const mode = editor.getExtension<VersioningController>("versioning")!;
111
+ cleanup.unshift(() => {
112
+ mode.dispose();
113
+ editor._tiptapEditor.destroy();
117
114
  });
118
- const endpoints = createYHubVersioningEndpoints({
119
- baseUrl: BASE_URL,
120
- org: ORG,
121
- docId: DOC_ID,
122
- })(editor);
123
- return { endpoints, fragment };
124
- }
125
115
 
126
- function mockFetchResponse(body: unknown, status = 200) {
127
- const encoded = encodeAny(body);
128
- return new Response(encoded as Blob | BufferSource, {
129
- status,
130
- statusText: status === 200 ? "OK" : "Error",
116
+ const edits: {
117
+ at: number;
118
+ content: Uint8Array;
119
+ attributions: Y.ContentMap;
120
+ }[] = [];
121
+ doc.on("beforeObserverCalls", (transaction) => {
122
+ const at = 1000 + edits.length * 100;
123
+ edits.push({
124
+ at,
125
+ content: Y.encodeStateAsUpdate(doc),
126
+ attributions: Y.createContentMapFromContentIds(
127
+ { inserts: transaction.insertSet, deletes: transaction.deleteSet },
128
+ [
129
+ Y.createContentAttribute("insert", authors[edits.length]),
130
+ Y.createContentAttribute("insertAt", at),
131
+ ],
132
+ [],
133
+ ),
134
+ });
135
+ });
136
+ function paragraph(text: string) {
137
+ return _blocksToProsemirrorNode(editor, [
138
+ { id: "paragraph", type: "paragraph", content: text },
139
+ ]);
140
+ }
141
+ const empty = Y.encodeStateAsUpdate(doc);
142
+ for (const text of ["a", "ab", "abc"]) {
143
+ fragment.applyDelta(
144
+ text === "a"
145
+ ? docToDelta(paragraph(text))
146
+ : docDiffToDelta(paragraph(text.slice(0, -1)), paragraph(text)),
147
+ );
148
+ }
149
+
150
+ fetchSpy.mockImplementation(async (input) => {
151
+ const url = new URL(input instanceof Request ? input.url : input);
152
+ if (url.pathname.includes("/activity/")) {
153
+ return response({
154
+ activity:
155
+ url.searchParams.get("order") === "asc"
156
+ ? [activity.first]
157
+ : activity.history,
158
+ });
159
+ }
160
+ const from = Number(url.searchParams.get("from") ?? 0);
161
+ const to = Number(url.searchParams.get("to") ?? Infinity);
162
+ if (url.searchParams.has("attributions")) {
163
+ const attributions = Y.createContentMap();
164
+ for (const edit of edits.filter(
165
+ (edit) => from <= edit.at && edit.at <= to,
166
+ )) {
167
+ Y.insertIntoIdMap(attributions.inserts, edit.attributions.inserts);
168
+ }
169
+ return response({ attributions: Y.encodeContentMap(attributions) });
170
+ }
171
+ // YHub includes edits at `to`, not just edits before it.
172
+ return response({
173
+ ydoc: edits.findLast((edit) => edit.at <= to)?.content ?? empty,
174
+ });
131
175
  });
132
- }
133
176
 
134
- function makeFragment(): Y.Type {
135
- const doc = new Y.Doc();
136
- const frag = doc.get("default", "XmlFragment");
137
- frag.insert(0, ["test content"]);
138
- return frag;
177
+ editor.replaceBlocks(editor.document, [
178
+ { id: "paragraph", type: "paragraph", content: "abc" },
179
+ ]);
180
+ editor.prosemirrorView.updateState(
181
+ editor.prosemirrorState.reconfigure({
182
+ plugins: editor._tiptapEditor.extensionManager.plugins,
183
+ }),
184
+ );
185
+ editor.exec(configureYProsemirror({ ytype: fragment }));
186
+ mode.open();
187
+ expect(await mode.list()).toEqual({ status: "done" });
188
+ const state = mode.store.state;
189
+ if (state.mode !== "versions" || state.history.status !== "success") {
190
+ throw new Error("Expected loaded version history");
191
+ }
192
+ expect(
193
+ await mode.select(target, { compareTo: compareTo(state.history.data) }),
194
+ ).toEqual({ status: "done" });
195
+
196
+ // Headless editors have no plugin view to hydrate the configured preview.
197
+ const binding = ySyncPluginKey.getState(editor.prosemirrorState)!;
198
+ editor.prosemirrorView.dispatch(
199
+ yNodeToTransaction(editor.prosemirrorState.tr, binding.ytype!, {
200
+ renderer: binding.renderer,
201
+ }),
202
+ );
203
+ const characters: { character: string; authors: string[] }[] = [];
204
+ editor.prosemirrorState.doc.descendants((node) => {
205
+ if (node.isText) {
206
+ const insertion = node.marks.find(
207
+ (mark) => mark.type.name === "y-attributed-insert",
208
+ );
209
+ for (const character of node.text!) {
210
+ characters.push({
211
+ character,
212
+ authors: insertion?.attrs.userIds ?? [],
213
+ });
214
+ }
215
+ }
216
+ });
217
+ return characters;
139
218
  }
140
219
 
141
- // ---------------------------------------------------------------------------
142
- // Tests
143
- // ---------------------------------------------------------------------------
144
-
145
- describe("createYHubVersioningEndpoints", () => {
146
- let fetchSpy: ReturnType<typeof vi.spyOn>;
147
-
148
- beforeEach(() => {
149
- fetchSpy = vi.spyOn(globalThis, "fetch");
220
+ it.each([false, true])(
221
+ "attributes every character of abc when comparing since beginning (Current: %s)",
222
+ async (showCurrentVersion) => {
223
+ const characters = await compareCharacters({
224
+ authors: ["alice", "alice", "alice"],
225
+ activity: { first, history: [{ ...first, to: 1200 }] },
226
+ target: showCurrentVersion
227
+ ? { type: "current" }
228
+ : { type: "snapshot", id: "1000-1200" },
229
+ compareTo: (history) => history.at(-1)!.id,
230
+ showCurrentVersion,
231
+ });
232
+ expect(characters).toEqual(
233
+ ["a", "b", "c"].map((character) => ({ character, authors: ["alice"] })),
234
+ );
235
+ },
236
+ );
237
+
238
+ it("shows only the selected version's edits when comparing to the previous version", async () => {
239
+ // Beginning (a), then "1000-1100" by alice (a, b), then "1200-1200" by bob (c).
240
+ const characters = await compareCharacters({
241
+ authors: ["alice", "alice", "bob"],
242
+ activity: {
243
+ first,
244
+ history: [
245
+ { from: 1200, to: 1200, by: ["bob"] },
246
+ { from: 1000, to: 1100, by: ["alice"] },
247
+ ],
248
+ },
249
+ target: { type: "snapshot", id: "1200-1200" },
250
+ compareTo: () => "1000-1100",
150
251
  });
252
+ expect(characters).toEqual([
253
+ { character: "a", authors: [] },
254
+ { character: "b", authors: [] },
255
+ { character: "c", authors: ["bob"] },
256
+ ]);
257
+ });
151
258
 
152
- afterEach(() => {
153
- vi.restoreAllMocks();
259
+ it("shows only the selected version's edits when the previous version is the first edit alone", async () => {
260
+ // "1000-1000" is both the first edit and a version of its own; the start of
261
+ // the document is a separate, empty row before it.
262
+ const characters = await compareCharacters({
263
+ authors: ["alice", "bob", "bob"],
264
+ activity: {
265
+ first,
266
+ history: [
267
+ { from: 1100, to: 1200, by: ["bob"] },
268
+ { from: 1000, to: 1000, by: ["alice"] },
269
+ ],
270
+ },
271
+ target: { type: "snapshot", id: "1100-1200" },
272
+ compareTo: () => "1000-1000",
154
273
  });
274
+ expect(characters).toEqual([
275
+ { character: "a", authors: [] },
276
+ { character: "b", authors: ["bob"] },
277
+ { character: "c", authors: ["bob"] },
278
+ ]);
279
+ });
155
280
 
156
- // -------------------------------------------------------------------------
157
- // list
158
- // -------------------------------------------------------------------------
159
- describe("list", () => {
160
- it("returns version-tagged entries using the id attribution as snapshot id", async () => {
161
- fetchSpy.mockResolvedValueOnce(
162
- mockFetchResponse({ activity: [VERSION_ENTRY_2, VERSION_ENTRY_1] }),
163
- );
164
- // Current-version probe: latest edit of any kind, then latest version
165
- // marker. Both are VERSION_ENTRY_2, so latest edit == latest marker → no
166
- // synthetic "current version" entry.
167
- fetchSpy.mockResolvedValueOnce(
168
- mockFetchResponse({ activity: [VERSION_ENTRY_2] }),
169
- );
170
- fetchSpy.mockResolvedValueOnce(
171
- mockFetchResponse({ activity: [VERSION_ENTRY_2] }),
172
- );
173
-
174
- const endpoints = makeEndpoints();
175
- const snapshots = await endpoints.list();
176
-
177
- expect(snapshots).toHaveLength(2);
178
- expect(snapshots[0].id).toBe("uuid-version-2");
179
- expect(snapshots[0].name).toBe("Test Version 2");
180
- // The comma-separated `by` user-ids are split into a raw id array —
181
- // never resolved to usernames here (that's the view layer's job).
182
- expect(snapshots[0].by).toEqual(["user-2", "user-3"]);
183
- expect(snapshots[0].secondaryLabel).toBeUndefined();
184
- expect(snapshots[1].id).toBe("uuid-version-1");
185
- expect(snapshots[1].name).toBe("Test Version 1");
186
- expect(snapshots[1].by).toEqual(["user-1"]);
187
- });
188
-
189
- it("fetches the full activity timeline (no type:version filter) with grouping defaults", async () => {
190
- // 1: full activity timeline. 2: latest edit of any kind. 3: latest
191
- // version marker (the current-version probe makes both 2 & 3).
192
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ activity: [] }));
193
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ activity: [] }));
194
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ activity: [] }));
195
-
196
- const endpoints = makeEndpoints();
197
- await endpoints.list();
198
-
199
- expect(fetchSpy).toHaveBeenCalledTimes(3);
200
- const versionUrl = new URL(fetchSpy.mock.calls[0][0] as string);
201
- expect(versionUrl.pathname).toBe(`/api/activity/v1/${ORG}/${DOC_ID}`);
202
- // The `type:version` overlay filter is dropped so history entries are
203
- // returned too.
204
- expect(versionUrl.searchParams.get("withCustomAttributions")).toBe(null);
205
- expect(versionUrl.searchParams.get("customAttributions")).toBe("true");
206
- // Grouping default is applied.
207
- expect(versionUrl.searchParams.get("groupMaxGap")).toBe("10000");
208
-
209
- // Probe A: the latest entry of *any* type (no marker filter).
210
- const latestUrl = new URL(fetchSpy.mock.calls[1][0] as string);
211
- expect(latestUrl.pathname).toBe(`/api/activity/v1/${ORG}/${DOC_ID}`);
212
- expect(latestUrl.searchParams.get("limit")).toBe("1");
213
- expect(latestUrl.searchParams.has("withCustomAttributions")).toBe(false);
214
-
215
- // Probe B: the latest *version marker*, server-filtered to `type:version`
216
- // so grouping/mergeUsers can't conflate it with a later edit.
217
- const markerUrl = new URL(fetchSpy.mock.calls[2][0] as string);
218
- expect(markerUrl.pathname).toBe(`/api/activity/v1/${ORG}/${DOC_ID}`);
219
- expect(markerUrl.searchParams.get("limit")).toBe("1");
220
- expect(markerUrl.searchParams.get("withCustomAttributions")).toBe(
221
- "type:version",
222
- );
223
- });
281
+ it("uses the latest server checkpoint as Current without a separate capture row", () => {
282
+ expect(storage().api.showCurrentVersion).toBe(false);
283
+ expect(fetchSpy).not.toHaveBeenCalled();
284
+ });
224
285
 
225
- it("forwards group + groupMaxDuration params when configured", async () => {
226
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ activity: [] }));
227
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ activity: [] }));
228
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ activity: [] }));
229
-
230
- const endpoints = createYHubVersioningEndpoints({
231
- baseUrl: BASE_URL,
232
- org: ORG,
233
- docId: DOC_ID,
234
- activityLimit: 50,
235
- group: true,
236
- groupMaxDuration: 5000,
237
- })(BlockNoteEditor.create());
238
- await endpoints.list();
239
-
240
- const versionUrl = new URL(fetchSpy.mock.calls[0][0] as string);
241
- expect(versionUrl.searchParams.get("group")).toBe("true");
242
- expect(versionUrl.searchParams.get("groupMaxDuration")).toBe("5000");
286
+ it("pins the start of the document, before the first edit, independently of sidebar filters and grouping", async () => {
287
+ const { api, doc } = storage({ from: 1500, by: "bob", group: true });
288
+ doc.get("default").push(["initial content"]);
289
+ fetchSpy
290
+ .mockResolvedValueOnce(response({ activity: [latest] }))
291
+ .mockResolvedValueOnce(response({ activity: [{ ...first, version }] }))
292
+ .mockResolvedValueOnce(response({ ydoc: Y.encodeStateAsUpdate(doc) }));
293
+ const { snapshots: versions } = resultValue(await api.list(signal));
294
+ expect(versions).toHaveLength(2);
295
+ const start = versions[1];
296
+ // The moment before the first edit: an empty document, without the first
297
+ // edit's name.
298
+ expect(start).toMatchObject({ id: "999-999", createdAt: 999, by: ["alice"] });
299
+ expect(start.name).toBeUndefined();
300
+ const content = resultValue(await api.getContent(start.id, signal));
301
+ const decoded = new Y.Doc();
302
+ try {
303
+ Y.applyUpdateV2(decoded, content);
304
+ expect(Object.fromEntries(request(1).url.searchParams)).toEqual({
305
+ from: "0",
306
+ order: "asc",
307
+ limit: "1",
308
+ group: "false",
309
+ versions: "true",
310
+ customAttributions: "true",
243
311
  });
312
+ expect(request(2).url.searchParams.get("to")).toBe("999");
313
+ } finally {
314
+ decoded.destroy();
315
+ }
316
+ });
244
317
 
245
- it("omits group params by default while keeping the groupMaxGap default", async () => {
246
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ activity: [] }));
247
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ activity: [] }));
248
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ activity: [] }));
249
-
250
- // `makeEndpoints` builds the factory with no group/groupMaxDuration opts.
251
- const endpoints = makeEndpoints();
252
- await endpoints.list();
253
-
254
- const versionUrl = new URL(fetchSpy.mock.calls[0][0] as string);
255
- expect(versionUrl.searchParams.get("group")).toBe(null);
256
- expect(versionUrl.searchParams.get("groupMaxDuration")).toBe(null);
257
- expect(versionUrl.searchParams.get("groupMaxGap")).toBe("10000");
258
- // mergeUsers is only forwarded when explicitly configured.
259
- expect(versionUrl.searchParams.get("mergeUsers")).toBe(null);
260
- });
318
+ it("lists no snapshots when there are no recorded edits", async () => {
319
+ fetchSpy.mockImplementation(async () => response({ activity: [] }));
320
+ expect(await storage().api.list(signal)).toEqual({
321
+ ok: true,
322
+ value: { snapshots: [], nextCursor: undefined },
323
+ });
324
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
325
+ });
261
326
 
262
- it("maps both named version entries and plain history entries", async () => {
263
- const namedEntry = {
264
- from: 2000,
265
- to: 2000,
266
- by: "user-1",
267
- customAttributions: [
268
- { k: "type", v: "version" },
269
- { k: "id", v: "v1" },
270
- { k: "name", v: "Named" },
327
+ it("reloads an unnamed YHub checkpoint as Current on each opening without creating a version", async () => {
328
+ const { api, doc } = storage();
329
+ const show = vi.fn();
330
+ const mode = createVersioning({
331
+ storage: api,
332
+ adapter: {
333
+ supportsComparison: false,
334
+ open() {
335
+ return {
336
+ current: { content: new Uint8Array(), capturedAt: 3000 },
337
+ show,
338
+ close() {},
339
+ };
340
+ },
341
+ },
342
+ setReadOnly() {},
343
+ });
344
+ for (let opening = 0; opening < 2; opening++) {
345
+ fetchSpy
346
+ .mockResolvedValueOnce(response({ activity: [latest, first] }))
347
+ .mockResolvedValueOnce(response({ activity: [first] }))
348
+ .mockResolvedValueOnce(response({ ydoc: Y.encodeStateAsUpdate(doc) }));
349
+ mode.open();
350
+ expect(await mode.list()).toEqual({ status: "done" });
351
+ expect(mode.store.state).toMatchObject({
352
+ showCurrentVersion: false,
353
+ displayed: { type: "snapshot", id: "2000-2000" },
354
+ history: {
355
+ data: [
356
+ { id: "2000-2000", name: undefined },
357
+ { id: "1000-1000" },
358
+ { id: "999-999" },
271
359
  ],
272
- };
273
- const historyEntry = {
274
- from: 1000,
275
- to: 1000,
276
- by: "user-2",
277
- };
278
- fetchSpy.mockResolvedValueOnce(
279
- mockFetchResponse({ activity: [namedEntry, historyEntry] }),
280
- );
281
- // Current-version probe: latest edit == latest marker == `namedEntry`, so
282
- // no synthetic current row.
283
- fetchSpy.mockResolvedValueOnce(
284
- mockFetchResponse({ activity: [namedEntry] }),
285
- );
286
- fetchSpy.mockResolvedValueOnce(
287
- mockFetchResponse({ activity: [namedEntry] }),
288
- );
289
-
290
- const endpoints = makeEndpoints();
291
- const snapshots = await endpoints.list();
292
-
293
- const named = snapshots.find((s) => s.name === "Named");
294
- expect(named).toBeDefined();
295
- expect(named!.id).toBe("v1");
296
-
297
- // `historyEntry` is at index 1 in the mocked entries array, so its
298
- // history id embeds that index: `history-<to>-<index>`.
299
- const history = snapshots.find((s) => s.id === "history-1000-1");
300
- expect(history).toBeDefined();
301
- expect(history!.name).toBeUndefined();
302
- });
303
-
304
- it("returns empty array when no versions exist", async () => {
305
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ activity: [] }));
306
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ activity: [] }));
307
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ activity: [] }));
308
-
309
- const endpoints = makeEndpoints();
310
- const snapshots = await endpoints.list();
311
-
312
- expect(snapshots).toEqual([]);
360
+ },
313
361
  });
314
-
315
- it("sorts snapshots newest-first", async () => {
316
- fetchSpy.mockResolvedValueOnce(
317
- mockFetchResponse({ activity: [VERSION_ENTRY_1, VERSION_ENTRY_2] }),
318
- );
319
- fetchSpy.mockResolvedValueOnce(
320
- mockFetchResponse({ activity: [VERSION_ENTRY_2] }),
321
- );
322
- fetchSpy.mockResolvedValueOnce(
323
- mockFetchResponse({ activity: [VERSION_ENTRY_2] }),
324
- );
325
-
326
- const endpoints = makeEndpoints();
327
- const snapshots = await endpoints.list();
328
-
329
- expect(snapshots[0].createdAt).toBeGreaterThan(snapshots[1].createdAt);
330
- });
331
-
332
- it("silently skips entries without an id attribution", async () => {
333
- const noIdEntry = {
334
- from: 1782218082853,
335
- to: 1782218082853,
336
- by: "Bad Entry",
337
- customAttributions: [{ k: "type", v: "version" }],
338
- };
339
- fetchSpy.mockResolvedValueOnce(
340
- mockFetchResponse({ activity: [VERSION_ENTRY_1, noIdEntry] }),
341
- );
342
- fetchSpy.mockResolvedValueOnce(
343
- mockFetchResponse({ activity: [VERSION_ENTRY_1] }),
344
- );
345
- fetchSpy.mockResolvedValueOnce(
346
- mockFetchResponse({ activity: [VERSION_ENTRY_1] }),
347
- );
348
-
349
- const endpoints = makeEndpoints();
350
- const snapshots = await endpoints.list();
351
-
352
- expect(snapshots).toHaveLength(1);
353
- expect(snapshots[0].id).toBe("uuid-version-1");
362
+ expect(show.mock.lastCall?.[0].target).toEqual({
363
+ type: "snapshot",
364
+ id: "2000-2000",
354
365
  });
366
+ mode.close();
367
+ }
368
+ expect(fetchSpy).toHaveBeenCalledTimes(6);
369
+ for (let index = 0; index < 6; index++) {
370
+ expect(request(index).method).toBe("GET");
371
+ }
372
+ });
355
373
 
356
- it("prefers the mutable __bn_version_names name over the attribution name", async () => {
357
- const doc = new Y.Doc();
358
- // The `ySync` extension's fragment belongs to `doc`, so the mutable
359
- // name store on `doc` is what `getVersionNamesMap` reads.
360
- const { endpoints } = makeCollabEndpoints(doc);
361
-
362
- // Rename version "v1" in the mutable store on the live doc.
363
- doc.get("__bn_version_names").setAttr("v1", "Renamed");
364
-
365
- const versionEntry = {
366
- from: 1782218082853,
367
- to: 1782218082853,
368
- by: "user-1",
369
- customAttributions: [
370
- { k: "type", v: "version" },
371
- { k: "id", v: "v1" },
372
- { k: "name", v: "Original" },
374
+ it("lists server checkpoints with their attached versions and empty versions", async () => {
375
+ fetchSpy
376
+ .mockResolvedValueOnce(
377
+ response({
378
+ activity: [
379
+ latest,
380
+ {
381
+ ...first,
382
+ by: ["alice", "bob"],
383
+ version,
384
+ customAttributions: [{ k: "source", v: "import" }],
385
+ },
386
+ {
387
+ from: 500,
388
+ to: 500,
389
+ by: [],
390
+ version: { ...version, t: 500, name: "Empty" },
391
+ isEmpty: true,
392
+ },
373
393
  ],
374
- };
375
- // 1: activity fetch. 2 & 3: current-version probe (latest edit, latest
376
- // marker) — same entry both times, so no newer edit and no current row.
377
- fetchSpy.mockResolvedValueOnce(
378
- mockFetchResponse({ activity: [versionEntry] }),
379
- );
380
- fetchSpy.mockResolvedValueOnce(
381
- mockFetchResponse({ activity: [versionEntry] }),
382
- );
383
- fetchSpy.mockResolvedValueOnce(
384
- mockFetchResponse({ activity: [versionEntry] }),
385
- );
386
-
387
- const snapshots = await endpoints.list();
388
-
389
- expect(snapshots).toHaveLength(1);
390
- expect(snapshots[0].id).toBe("v1");
391
- expect(snapshots[0].name).toBe("Renamed");
392
- });
393
-
394
- it("falls back to the attribution name when the store has no entry", async () => {
395
- fetchSpy.mockResolvedValueOnce(
396
- mockFetchResponse({ activity: [VERSION_ENTRY_1] }),
397
- );
398
- fetchSpy.mockResolvedValueOnce(
399
- mockFetchResponse({ activity: [VERSION_ENTRY_1] }),
400
- );
401
- fetchSpy.mockResolvedValueOnce(
402
- mockFetchResponse({ activity: [VERSION_ENTRY_1] }),
403
- );
404
-
405
- const endpoints = makeEndpoints();
406
- const snapshots = await endpoints.list();
407
-
408
- expect(snapshots).toHaveLength(1);
409
- expect(snapshots[0].name).toBe("Test Version 1");
410
- });
411
-
412
- it("prepends a 'current version' entry when there are edits beyond the latest version", async () => {
413
- // A more recent edit than VERSION_ENTRY_2, by a different author.
414
- const latestEdit = {
415
- from: 1782218300000,
416
- to: 1782218300000,
417
- by: "user-4",
418
- };
419
- // 1: activity list. 2: latest edit of any kind (the newer edit). 3: latest
420
- // version marker (VERSION_ENTRY_2). Since latestEdit.to > VERSION_ENTRY_2.to
421
- // a synthetic current-version row is prepended.
422
- fetchSpy.mockResolvedValueOnce(
423
- mockFetchResponse({ activity: [VERSION_ENTRY_2, VERSION_ENTRY_1] }),
424
- );
425
- fetchSpy.mockResolvedValueOnce(
426
- mockFetchResponse({ activity: [latestEdit] }),
427
- );
428
- fetchSpy.mockResolvedValueOnce(
429
- mockFetchResponse({ activity: [VERSION_ENTRY_2] }),
430
- );
431
-
432
- const endpoints = makeEndpoints();
433
- const snapshots = await endpoints.list();
434
-
435
- expect(snapshots).toHaveLength(3);
436
- expect(snapshots[0].id).toBe(CURRENT_VERSION_ID);
437
- expect(snapshots[0].createdAt).toBe(latestEdit.to);
438
- expect(snapshots[0].by).toEqual(["user-4"]);
439
- expect(snapshots[0].secondaryLabel).toBeUndefined();
440
- // The real version markers follow, newest-first.
441
- expect(snapshots[1].id).toBe("uuid-version-2");
442
- expect(snapshots[2].id).toBe("uuid-version-1");
443
- });
394
+ }),
395
+ )
396
+ .mockResolvedValueOnce(response({ activity: [] }));
397
+ expect(resultValue(await storage().api.list(signal)).snapshots).toMatchObject(
398
+ [
399
+ { id: "2000-2000", by: ["bob"] },
400
+ {
401
+ id: "1000-1000",
402
+ by: ["alice", "bob"],
403
+ name: "Milestone",
404
+ metadata: version.custom,
405
+ restoredFrom: { id: "42-42", createdAt: 42 },
406
+ customAttributions: { source: "import" },
407
+ },
408
+ { id: "500-500", by: [], name: "Empty" },
409
+ ],
410
+ );
411
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
412
+ expect(request(0).url.searchParams.get("versions")).toBe("true");
413
+ expect(request(0).signal).toBeInstanceOf(AbortSignal);
414
+ });
444
415
 
445
- it("prepends 'current version' even when the newest activity entry is a history edit (regression: grouping absorbing the marker)", async () => {
446
- // This is the exact regression the self-contained current-version probe
447
- // fixes: `list()` maps the whole timeline, so its newest snapshot is a
448
- // plain edit — deriving the latest-version time from that list would make
449
- // the guard compare a value against itself and never surface a current
450
- // row. Because the marker is fetched independently (probe 3), the edit is
451
- // correctly recognised as newer than the latest *version marker*.
452
- const historyEdit = {
453
- from: 1782218300000,
454
- to: 1782218300000,
455
- by: "user-9",
456
- };
457
- // 1: activity list — newest entry is the history edit, not a marker.
458
- fetchSpy.mockResolvedValueOnce(
459
- mockFetchResponse({
460
- activity: [historyEdit, VERSION_ENTRY_2, VERSION_ENTRY_1],
416
+ it.each([false, 0, "", ["app"], {}, null].map((custom) => ({ custom })))(
417
+ "preserves each activity entry and its custom metadata $custom",
418
+ async ({ custom }) => {
419
+ fetchSpy
420
+ .mockResolvedValueOnce(
421
+ response({
422
+ activity: [
423
+ { ...first, by: "bob", version: { ...version, custom } },
424
+ {
425
+ ...first,
426
+ by: "alice",
427
+ customAttributions: [{ k: "source", v: "edit" }],
428
+ },
429
+ ],
461
430
  }),
462
- );
463
- // 2: latest edit of any kind → the history edit.
464
- fetchSpy.mockResolvedValueOnce(
465
- mockFetchResponse({ activity: [historyEdit] }),
466
- );
467
- // 3: latest version marker → VERSION_ENTRY_2 (older than the edit).
468
- fetchSpy.mockResolvedValueOnce(
469
- mockFetchResponse({ activity: [VERSION_ENTRY_2] }),
470
- );
471
-
472
- const endpoints = makeEndpoints();
473
- const snapshots = await endpoints.list();
474
-
475
- expect(snapshots[0].id).toBe(CURRENT_VERSION_ID);
476
- expect(snapshots[0].createdAt).toBe(historyEdit.to);
477
- expect(snapshots[0].by).toEqual(["user-9"]);
478
- });
479
-
480
- it("forwards the mergeUsers param when configured", async () => {
481
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ activity: [] }));
482
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ activity: [] }));
483
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ activity: [] }));
484
-
485
- const endpoints = createYHubVersioningEndpoints({
486
- baseUrl: BASE_URL,
487
- org: ORG,
488
- docId: DOC_ID,
489
- mergeUsers: true,
490
- })(BlockNoteEditor.create());
491
- await endpoints.list();
492
-
493
- const versionUrl = new URL(fetchSpy.mock.calls[0][0] as string);
494
- expect(versionUrl.searchParams.get("mergeUsers")).toBe("true");
495
- });
431
+ )
432
+ .mockResolvedValueOnce(response({ activity: [first] }));
433
+ const { snapshots: rows } = resultValue(
434
+ await storage({ groupByUser: true }).api.list(signal),
435
+ );
436
+ expect(rows).toHaveLength(3);
437
+ expect(rows[2].id).toBe("999-999");
438
+ expect(rows[0].by).toEqual(["bob"]);
439
+ expect(rows[0].metadata).toEqual(custom);
440
+ expect(rows[1].by).toEqual(["alice"]);
441
+ expect(rows[1].metadata).toBeUndefined();
442
+ expect(rows[1].customAttributions).toEqual({ source: "edit" });
443
+ expect(request(0).url.searchParams.get("groupByUser")).toBe("true");
444
+ },
445
+ );
446
+
447
+ it("preserves caller activity filters without merging returned entries", async () => {
448
+ fetchSpy
449
+ .mockResolvedValueOnce(
450
+ response({
451
+ activity: [
452
+ { ...first, customAttributions: [{ k: "source", v: "import" }] },
453
+ {
454
+ ...first,
455
+ by: ["bob"],
456
+ version,
457
+ customAttributions: [{ k: "tag", v: "release" }],
458
+ },
459
+ ],
460
+ }),
461
+ )
462
+ .mockResolvedValueOnce(response({ activity: [first] }));
463
+ const activityParams = {
464
+ groupExclude: "alice,bob",
465
+ order: "desc",
466
+ limit: 10,
467
+ from: 500,
468
+ by: "alice,bob",
469
+ customAttributions: true,
470
+ };
471
+ expect(
472
+ resultValue(await storage(activityParams).api.list(signal)).snapshots,
473
+ ).toMatchObject([
474
+ {
475
+ id: "1000-1000",
476
+ by: ["alice"],
477
+ customAttributions: { source: "import" },
478
+ },
479
+ {
480
+ id: "1000-1000",
481
+ by: ["bob"],
482
+ name: "Milestone",
483
+ metadata: version.custom,
484
+ restoredFrom: { id: "42-42", createdAt: 42 },
485
+ customAttributions: { tag: "release" },
486
+ },
487
+ { id: "999-999", by: ["alice"] },
488
+ ]);
489
+ for (const [key, value] of Object.entries(activityParams)) {
490
+ expect(request(0).url.searchParams.get(key)).toBe(
491
+ String(key === "limit" ? Number(value) + 1 : value),
492
+ );
493
+ }
494
+ expect(activityParams).toEqual({
495
+ groupExclude: "alice,bob",
496
+ order: "desc",
497
+ limit: 10,
498
+ from: 500,
499
+ by: "alice,bob",
500
+ customAttributions: true,
496
501
  });
502
+ });
497
503
 
498
- // -------------------------------------------------------------------------
499
- // create
500
- // -------------------------------------------------------------------------
501
- describe("create", () => {
502
- it("PATCHes with type:version, id, and name attributions and returns optimistic snapshot", async () => {
503
- fetchSpy.mockResolvedValueOnce(mockFetchResponse(PATCH_RESPONSE));
504
-
505
- const endpoints = makeEndpoints();
506
- const snapshot = await endpoints.create!(makeFragment(), {
507
- name: "My Version",
508
- });
509
-
510
- // Only one fetch call (PATCH) — no activity fetch
511
- expect(fetchSpy).toHaveBeenCalledOnce();
512
- const [patchUrl, patchInit] = fetchSpy.mock.calls[0];
513
- expect(patchUrl).toBe(`${BASE_URL}/ydoc/v1/${ORG}/${DOC_ID}`);
514
- expect(patchInit.method).toBe("PATCH");
515
- expect(patchInit.body).toBeInstanceOf(Uint8Array);
516
-
517
- // Optimistic snapshot has a UUID id and the provided name. With no
518
- // yCursor extension there's no current user to attribute it to.
519
- expect(snapshot.id).toMatch(/^[0-9a-f-]+$/);
520
- expect(snapshot.name).toBe("My Version");
521
- expect(snapshot.createdAt).toBeGreaterThan(0);
522
- expect(snapshot.by).toBeUndefined();
523
- });
524
-
525
- it("stamps the optimistic snapshot with the cursor user's id", async () => {
526
- fetchSpy.mockResolvedValueOnce(mockFetchResponse(PATCH_RESPONSE));
527
-
528
- // Stub the editor so the yCursor extension reports a current user.
529
- const editor = {
530
- getExtension: (key: string) =>
531
- key === "yCursor"
532
- ? {
533
- getUser: () => ({ id: "user-1", name: "Alice", color: "#f00" }),
534
- }
535
- : undefined,
536
- } as unknown as BlockNoteEditor<any, any, any>;
537
- const endpoints = createYHubVersioningEndpoints({
538
- baseUrl: BASE_URL,
539
- org: ORG,
540
- docId: DOC_ID,
541
- })(editor);
542
-
543
- const snapshot = await endpoints.create!(makeFragment(), {
544
- name: "My Version",
545
- });
546
-
547
- expect(snapshot.by).toBe("user-1");
548
- // The PATCH is attributed to the same user via the body, not query params.
549
- const patchUrl = new URL(fetchSpy.mock.calls[0][0] as string);
550
- expect(patchUrl.searchParams.has("userid")).toBe(false);
504
+ it("pages through bounded activity windows with stable timestamp identifiers", async () => {
505
+ const activity = [
506
+ { from: 90, to: 100, by: ["alice"] },
507
+ { from: 70, to: 80, by: ["bob"], version: { ...version, t: 80 } },
508
+ { from: 50, to: 60, by: ["alice"] },
509
+ ];
510
+ fetchSpy.mockImplementation(async (url) => {
511
+ const params = new URL(url instanceof Request ? url.url : url).searchParams;
512
+ if (params.get("order") === "asc") {
513
+ return response({ activity: [activity.at(-1)] });
514
+ }
515
+ const to = Number(params.get("to") ?? Infinity);
516
+ return response({
517
+ activity: activity
518
+ .filter((entry) => entry.to <= to)
519
+ .slice(0, Number(params.get("limit"))),
551
520
  });
521
+ });
522
+ const { api } = storage({ limit: 1 });
523
+ const snapshots = [];
524
+ const cursors = new Set<string>();
525
+ let cursor: string | undefined;
526
+ do {
527
+ const page = resultValue(await api.list(signal, cursor));
528
+ snapshots.push(...page.snapshots);
529
+ cursor = page.nextCursor;
530
+ if (cursor !== undefined) {
531
+ expect(cursors.has(cursor)).toBe(false);
532
+ cursors.add(cursor);
533
+ }
534
+ } while (cursor !== undefined);
535
+ expect(
536
+ snapshots.map(({ id, createdAt, name }) => ({ id, createdAt, name })),
537
+ ).toEqual([
538
+ { id: "90-100", createdAt: 100, name: undefined },
539
+ // The first page also pins the start, the moment before the first edit.
540
+ { id: "49-49", createdAt: 49, name: undefined },
541
+ { id: "70-80", createdAt: 80, name: "Milestone" },
542
+ { id: "50-60", createdAt: 60, name: undefined },
543
+ ]);
544
+ });
552
545
 
553
- it("creates a version without a name", async () => {
554
- fetchSpy.mockResolvedValueOnce(mockFetchResponse(PATCH_RESPONSE));
555
-
556
- const endpoints = makeEndpoints();
557
- const snapshot = await endpoints.create!(makeFragment());
546
+ it("keeps grouping fixed while traversing a cursor and uses changed options on refresh", async () => {
547
+ const activityParams = { limit: 1, groupMaxGap: 10, groupByUser: false };
548
+ fetchSpy.mockImplementation(async (url) => {
549
+ const params = new URL(url instanceof Request ? url.url : url).searchParams;
550
+ if (params.get("order") === "asc") {
551
+ return response({ activity: [first] });
552
+ }
553
+ return response({ activity: params.has("to") ? [first] : [latest, first] });
554
+ });
555
+ const { api } = storage(activityParams);
556
+ const page = resultValue(await api.list(signal));
557
+ activityParams.groupMaxGap = 20;
558
+ activityParams.groupByUser = true;
559
+ expect(
560
+ resultValue(await api.list(signal, page.nextCursor)).snapshots[0].id,
561
+ ).toBe("1000-1000");
562
+ await api.list(signal);
563
+ expect(request(2).url.searchParams.get("groupMaxGap")).toBe("10");
564
+ expect(request(2).url.searchParams.get("groupByUser")).toBe("false");
565
+ expect(request(3).url.searchParams.get("groupMaxGap")).toBe("20");
566
+ expect(request(3).url.searchParams.get("groupByUser")).toBe("true");
567
+ });
558
568
 
559
- expect(snapshot.name).toBeUndefined();
560
- expect(snapshot.id).toMatch(/^[0-9a-f-]+$/);
561
- });
569
+ it.each([{ activity: [] }, { activity: [latest] }])(
570
+ "reports exhaustion without an unnecessary empty-page request for %j",
571
+ async ({ activity }) => {
572
+ fetchSpy
573
+ .mockResolvedValueOnce(response({ activity }))
574
+ .mockResolvedValueOnce(response({ activity }));
575
+ const page = resultValue(await storage({ limit: 1 }).api.list(signal));
576
+ expect(page.nextCursor).toBeUndefined();
577
+ // With an edit, the start of the document is pinned after it.
578
+ expect(page.snapshots.map((snapshot) => snapshot.id)).toEqual(
579
+ activity.length ? ["2000-2000", "1999-1999"] : [],
580
+ );
581
+ },
582
+ );
583
+
584
+ it.each([0, -1, 1.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1])(
585
+ "rejects invalid activity page size %s",
586
+ async (limit) => {
587
+ await expect(storage({ limit }).api.list(signal)).rejects.toThrow(
588
+ "positive integer",
589
+ );
590
+ },
591
+ );
592
+
593
+ it("names the latest checkpoint only when its content matches frozen current", async () => {
594
+ const { api, doc } = storage();
595
+ doc.get("default").push(["shown"]);
596
+ fetchSpy
597
+ .mockResolvedValueOnce(response({ activity: [latest] }))
598
+ .mockResolvedValueOnce(response({ ydoc: Y.encodeStateAsUpdate(doc) }))
599
+ .mockResolvedValueOnce(response({ versions: [] }))
600
+ .mockResolvedValueOnce(
601
+ response({ ...version, t: latest.to, name: "Current milestone" }),
602
+ );
603
+ expect(
604
+ await api.create!(Y.encodeStateAsUpdateV2(doc), "Current milestone"),
605
+ ).toMatchObject({
606
+ ok: true,
607
+ value: { id: "2000-2000", createdAt: 2000, name: "Current milestone" },
608
+ });
609
+ expect(request(0).url.searchParams.get("limit")).toBe("1");
610
+ expect(request(3).method).toBe("POST");
611
+ expect(request(3).body).toEqual({
612
+ type: "version:v1",
613
+ t: 2000,
614
+ name: "Current milestone",
615
+ });
616
+ });
562
617
 
563
- it("writes the version name into the __bn_version_names Y.Map on create", async () => {
564
- const doc = new Y.Doc();
565
- const { endpoints, fragment } = makeCollabEndpoints(doc);
618
+ it("renames an already named latest checkpoint while preserving metadata", async () => {
619
+ const { api, doc } = storage();
620
+ doc.get("default").push(["shown"]);
621
+ const current = { ...version, t: latest.to };
622
+ fetchSpy
623
+ .mockResolvedValueOnce(response({ activity: [latest] }))
624
+ .mockResolvedValueOnce(response({ ydoc: Y.encodeStateAsUpdate(doc) }))
625
+ .mockResolvedValueOnce(response({ versions: [current] }))
626
+ .mockResolvedValueOnce(response({ ...current, name: "Renamed current" }));
627
+ expect(
628
+ await api.create!(Y.encodeStateAsUpdateV2(doc), "Renamed current"),
629
+ ).toMatchObject({
630
+ ok: true,
631
+ value: {
632
+ id: "2000-2000",
633
+ name: "Renamed current",
634
+ metadata: version.custom,
635
+ },
636
+ });
637
+ expect(request(3).method).toBe("PATCH");
638
+ expect(request(3).body.custom).toEqual(version.custom);
639
+ });
566
640
 
567
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ success: true }));
641
+ it("does not name a checkpoint when no edits have been recorded", async () => {
642
+ fetchSpy.mockResolvedValueOnce(response({ activity: [] }));
643
+ expect(
644
+ await storage().api.create?.(new Uint8Array(), "Current milestone"),
645
+ ).toEqual({ ok: false, error: { type: "conflict" } });
646
+ expect(fetchSpy).toHaveBeenCalledOnce();
647
+ });
568
648
 
569
- const snapshot = await endpoints.create!(fragment as any, {
570
- name: "My Version",
571
- });
649
+ it("names a recorded checkpoint through POST", async () => {
650
+ fetchSpy.mockResolvedValueOnce(response({ versions: [] }));
651
+ fetchSpy.mockResolvedValueOnce(response({ ...version, name: "Saved" }));
652
+ await storage().api.rename!("900-1000", "Saved");
653
+ expect(request(1)).toMatchObject({
654
+ method: "POST",
655
+ body: { type: "version:v1", t: 1000, name: "Saved" },
656
+ });
657
+ });
572
658
 
573
- const names = doc.get("__bn_version_names");
574
- expect(names.getAttr(snapshot.id as string)).toBe("My Version");
575
- });
659
+ it("renames through conditional PATCH without losing custom data", async () => {
660
+ fetchSpy.mockResolvedValueOnce(response({ versions: [version] }));
661
+ fetchSpy.mockResolvedValueOnce(response({ ...version, name: "New" }));
662
+ await storage().api.rename!("900-1000", "New");
663
+ expect(request(1)).toMatchObject({
664
+ method: "PATCH",
665
+ body: {
666
+ updatedAt: 3000,
667
+ name: "New",
668
+ custom: version.custom,
669
+ },
670
+ });
671
+ });
576
672
 
577
- it("throws when the fragment is not attached to a doc", async () => {
578
- const endpoints = makeEndpoints();
579
- const detached = { doc: null } as unknown as Y.Type;
580
- await expect(
581
- endpoints.create!(detached, { name: "fail" }),
582
- ).rejects.toThrow("not attached to a Y.Doc");
583
- });
673
+ it("removes a name without removing app metadata", async () => {
674
+ fetchSpy.mockResolvedValueOnce(response({ versions: [version] }));
675
+ fetchSpy.mockResolvedValueOnce(response({ ...version, name: "" }));
676
+ await storage().api.remove!("900-1000");
677
+ expect(request(1).body).toMatchObject({ name: "", custom: version.custom });
678
+ });
584
679
 
585
- it("getContent works on the returned snapshot without an extra lookup", async () => {
586
- fetchSpy.mockResolvedValueOnce(mockFetchResponse(PATCH_RESPONSE));
587
- const cs = makeChangeset();
588
- fetchSpy.mockResolvedValueOnce(mockFetchResponse(cs));
680
+ it("conditionally deletes a version without custom metadata", async () => {
681
+ fetchSpy.mockResolvedValueOnce(
682
+ response({ versions: [{ ...version, custom: null }] }),
683
+ );
684
+ fetchSpy.mockResolvedValueOnce(response(null, 204));
685
+ await storage().api.remove!("900-1000");
686
+ expect(request(1).method).toBe("DELETE");
687
+ expect(request(1).url.searchParams.get("updatedAt")).toBe("3000");
688
+ });
589
689
 
590
- const endpoints = makeEndpoints();
591
- const snapshot = await endpoints.create!(makeFragment(), {
592
- name: "new",
593
- });
690
+ it("leaves unnamed automatic activity alone", async () => {
691
+ fetchSpy.mockResolvedValueOnce(response({ versions: [] }));
692
+ await storage().api.remove!("900-1000");
693
+ expect(fetchSpy).toHaveBeenCalledOnce();
694
+ });
594
695
 
595
- const content = await endpoints.getContent(snapshot);
596
- expect(content).toBeInstanceOf(Uint8Array);
597
- // PATCH + changeset — the timestamp comes from the snapshot itself, so
598
- // there's no activity lookup.
599
- expect(fetchSpy).toHaveBeenCalledTimes(2);
600
- const url = new URL(fetchSpy.mock.calls[1][0] as string);
601
- expect(url.searchParams.get("to")).toBe(String(snapshot.createdAt));
602
- });
696
+ it("propagates concurrent version conflicts", async () => {
697
+ fetchSpy.mockResolvedValueOnce(response({ versions: [version] }));
698
+ fetchSpy.mockResolvedValueOnce(response({ error: "conflict" }, 409));
699
+ expect(await storage().api.rename!("900-1000", "New")).toEqual({
700
+ ok: false,
701
+ error: { type: "conflict" },
603
702
  });
703
+ });
604
704
 
605
- // -------------------------------------------------------------------------
606
- // getContent
607
- // -------------------------------------------------------------------------
608
- describe("getContent", () => {
609
- it("fetches the changeset by to=<snapshot.createdAt> with no activity lookup", async () => {
610
- // changeset fetch
611
- const cs = makeChangeset();
612
- fetchSpy.mockResolvedValueOnce(mockFetchResponse(cs));
613
-
614
- const endpoints = makeEndpoints();
615
- const content = await endpoints.getContent(SNAPSHOT_1);
616
-
617
- expect(content).toBeInstanceOf(Uint8Array);
618
- expect(content.byteLength).toBeGreaterThan(0);
619
-
620
- // The snapshot carries its own timestamp, so only the changeset is fetched.
621
- expect(fetchSpy).toHaveBeenCalledOnce();
622
-
623
- // changeset reconstructed by timestamp, NOT by custom attribution
624
- const url = new URL(fetchSpy.mock.calls[0][0] as string);
625
- expect(url.pathname).toBe(`/api/changeset/v1/${ORG}/${DOC_ID}`);
626
- expect(url.searchParams.get("ydoc")).toBe("true");
627
- expect(url.searchParams.get("to")).toBe(String(SNAPSHOT_1.createdAt));
628
- expect(url.searchParams.has("from")).toBe(false);
629
- expect(url.searchParams.has("withCustomAttributions")).toBe(false);
630
- });
631
-
632
- it("throws when changeset has no ydoc", async () => {
633
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({}));
634
-
635
- const endpoints = makeEndpoints();
636
- await expect(endpoints.getContent(SNAPSHOT_1)).rejects.toThrow(
637
- "no document state",
638
- );
639
- });
640
- });
705
+ it("loads V2 content at the end of its window", async () => {
706
+ const { api, doc } = storage();
707
+ doc.get("default").push(["hello"]);
708
+ fetchSpy.mockResolvedValueOnce(
709
+ response({ ydoc: Y.encodeStateAsUpdate(doc) }),
710
+ );
711
+ const content = resultValue(await api.getContent("900-1000", signal));
712
+ const restored = new Y.Doc();
713
+ try {
714
+ Y.applyUpdateV2(restored, content);
715
+ expect(restored.get("default").toArray()).toEqual(["hello"]);
716
+ } finally {
717
+ restored.destroy();
718
+ }
719
+ expect(request(0).url.searchParams.get("to")).toBe("1000");
720
+ expect(request(0).signal).toBeInstanceOf(AbortSignal);
721
+ });
641
722
 
642
- // -------------------------------------------------------------------------
643
- // getAttributions
644
- // -------------------------------------------------------------------------
645
- describe("getAttributions", () => {
646
- it("fetches attributions between two versions", async () => {
647
- const endpoints = makeEndpoints();
648
-
649
- // changeset fetch (timestamps come straight from the snapshots)
650
- const cs = makeChangeset({ attributions: true });
651
- fetchSpy.mockResolvedValueOnce(mockFetchResponse(cs));
652
-
653
- try {
654
- await endpoints.getAttributions!(SNAPSHOT_2, SNAPSHOT_1);
655
- } catch {
656
- // Expected — mock attributions aren't valid Y.ContentMap
723
+ it.each([
724
+ { type: "current", capturedAt: 500 },
725
+ { type: "current", capturedAt: 2500 },
726
+ { type: "snapshot", capturedAt: 2500 },
727
+ ] as const)(
728
+ "uses the server attribution cutoff for $type with client capture time $capturedAt",
729
+ async ({ type, capturedAt }) => {
730
+ fetchSpy.mockResolvedValueOnce(
731
+ response({ attributions: Y.encodeContentMap(Y.createContentMap()) }),
732
+ );
733
+ await storage().api.getAttributions!(
734
+ type === "current" ? { type } : { type, id: "1900-2000" },
735
+ "900-1000",
736
+ capturedAt,
737
+ signal,
738
+ );
739
+ // The baseline already holds its edits up to 1000.
740
+ expect(request(0).url.searchParams.get("from")).toBe("1001");
741
+ expect(request(0).url.searchParams.get("to")).toBe(
742
+ type === "current" ? null : "2000",
743
+ );
744
+ expect(request(0).signal).toBeInstanceOf(AbortSignal);
745
+ },
746
+ );
747
+
748
+ it.each([false, true])(
749
+ "preserves the live head before restore, existing named checkpoint: %s",
750
+ async (named) => {
751
+ const { api, doc, fragment } = storage();
752
+ fragment.push(["hello"]);
753
+ fetchSpy.mockImplementation(async (input, init) => {
754
+ const path = new URL(input instanceof Request ? input.url : input)
755
+ .pathname;
756
+ if (path.includes("/activity/")) {
757
+ return response({ activity: [latest] });
657
758
  }
658
-
659
- // Only the changeset is fetched — no activity lookups.
660
- expect(fetchSpy).toHaveBeenCalledOnce();
661
- const url = new URL(fetchSpy.mock.calls[0][0] as string);
662
- expect(url.searchParams.get("from")).toBe(String(SNAPSHOT_1.createdAt));
663
- expect(url.searchParams.get("to")).toBe(String(SNAPSHOT_2.createdAt));
664
- expect(url.searchParams.get("attributions")).toBe("true");
759
+ if (path.includes("/ydoc/")) {
760
+ return response({ doc: Y.encodeStateAsUpdate(doc) });
761
+ }
762
+ if (path.includes("/version/") && init?.method !== "POST") {
763
+ return response({ versions: named ? [{ ...version, t: 2000 }] : [] });
764
+ }
765
+ if (path.includes("/version/")) {
766
+ return response({ ...version, t: 2000 });
767
+ }
768
+ return response({ success: true });
665
769
  });
666
-
667
- it("uses from=0 when compareTo is omitted", async () => {
668
- const endpoints = makeEndpoints();
669
-
670
- // changeset fetch
671
- const cs = makeChangeset({ attributions: true });
672
- fetchSpy.mockResolvedValueOnce(mockFetchResponse(cs));
673
-
674
- try {
675
- await endpoints.getAttributions!(SNAPSHOT_1);
676
- } catch {
677
- // Expected
770
+ await api.restore!("900-1000");
771
+ const calls = fetchSpy.mock.calls.map((_, index) => request(index));
772
+ const pins = calls.filter(
773
+ (call) =>
774
+ call.method === "POST" && call.url.pathname.includes("/version/"),
775
+ );
776
+ expect(pins).toHaveLength(named ? 0 : 1);
777
+ if (!named) {
778
+ expect(pins[0].body).toMatchObject({ t: 2000, name: "Before restore" });
779
+ }
780
+ const rollback = calls.find((call) =>
781
+ call.url.pathname.includes("/rollback/"),
782
+ );
783
+ expect(rollback?.body.from).toBe(1001);
784
+ expect(Y.decodeContentIds(rollback?.body.contentIds).inserts).toBeDefined();
785
+ },
786
+ );
787
+
788
+ it.each(["alice", "bob"])(
789
+ "authenticates every restore request as %s without using the rollback author filter",
790
+ async (userid) => {
791
+ const doc = new Y.Doc();
792
+ cleanup.push(() => doc.destroy());
793
+ const fragment = doc.get("default");
794
+ fragment.push(["hello"]);
795
+ const api = createYHubVersionStorage({
796
+ ...options,
797
+ queryParams: { userid },
798
+ fragment,
799
+ beforeRestoreName: "Before restore",
800
+ });
801
+ fetchSpy.mockImplementation(async (input, init) => {
802
+ const path = new URL(input instanceof Request ? input.url : input)
803
+ .pathname;
804
+ if (path.includes("/activity/")) {
805
+ return response({ activity: [latest] });
678
806
  }
679
-
680
- const url = new URL(fetchSpy.mock.calls[0][0] as string);
681
- expect(url.searchParams.get("from")).toBe("0");
807
+ if (path.includes("/ydoc/")) {
808
+ return response({ doc: Y.encodeStateAsUpdate(doc) });
809
+ }
810
+ if (path.includes("/version/")) {
811
+ return init?.method === "POST"
812
+ ? response({ ...version, t: latest.to })
813
+ : response({ versions: [] });
814
+ }
815
+ return response({ success: true });
682
816
  });
683
-
684
- it("throws when changeset has no attributions", async () => {
685
- const endpoints = makeEndpoints();
686
-
687
- // changeset without attributions
688
- fetchSpy.mockResolvedValueOnce(
689
- mockFetchResponse({ ydoc: new Uint8Array() }),
690
- );
691
-
692
- await expect(endpoints.getAttributions!(SNAPSHOT_1)).rejects.toThrow(
693
- "no attributions",
694
- );
817
+ expect(await api.restore("900-1000")).toEqual({
818
+ ok: true,
819
+ value: undefined,
695
820
  });
821
+ const calls = fetchSpy.mock.calls.map((_, index) => request(index));
822
+ expect(calls).toHaveLength(6);
823
+ for (const call of calls) {
824
+ expect(call.url.searchParams.get("userid")).toBe(userid);
825
+ }
826
+ const rollback = calls.find((call) =>
827
+ call.url.pathname.includes("/rollback/"),
828
+ );
829
+ expect(Object.keys(rollback?.body).sort()).toEqual(["contentIds", "from"]);
830
+ expect(calls[0].url.searchParams.get("limit")).toBe("1");
831
+ expect(calls[1].url.searchParams.get("gc")).toBe("false");
832
+ },
833
+ );
834
+
835
+ it.each([false, 0, "", [], {}, null].map((custom) => ({ custom })))(
836
+ "the transport can still save app metadata $custom directly",
837
+ async ({ custom }) => {
838
+ fetchSpy.mockResolvedValueOnce(response({ ...version, custom }));
839
+ await new YHubClient(options).createVersion(1000, "Milestone", custom);
840
+ expect(request(0).body.custom).toEqual(custom);
841
+ },
842
+ );
843
+
844
+ it("refuses to name newer server content that was not shown in frozen current", async () => {
845
+ const { api, doc, fragment } = storage();
846
+ fragment.push(["shown"]);
847
+ const frozen = Y.encodeStateAsUpdateV2(doc);
848
+ fragment.push(["unseen"]);
849
+ fetchSpy
850
+ .mockResolvedValueOnce(response({ activity: [latest] }))
851
+ .mockResolvedValueOnce(response({ ydoc: Y.encodeStateAsUpdate(doc) }));
852
+ expect(await api.create!(frozen, "Milestone")).toEqual({
853
+ ok: false,
854
+ error: { type: "conflict" },
696
855
  });
856
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
857
+ expect(fetchSpy.mock.calls.every(([, init]) => !init?.method)).toBe(true);
858
+ });
697
859
 
698
- // -------------------------------------------------------------------------
699
- // restore
700
- // -------------------------------------------------------------------------
701
- describe("restore", () => {
702
- it("fetches content and issues rollback (no backup)", async () => {
703
- const endpoints = makeEndpoints();
704
- const cs = makeChangeset();
705
-
706
- // 1: GET /changeset (getContentAt via to=<snapshot.createdAt>)
707
- fetchSpy.mockResolvedValueOnce(mockFetchResponse(cs));
708
- // 2: POST /rollback
709
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ success: true }));
710
-
711
- const content = await endpoints.restore!(makeFragment(), SNAPSHOT_1);
712
-
713
- // No backup PATCH and no activity lookup — just changeset + rollback.
714
- expect(fetchSpy).toHaveBeenCalledTimes(2);
715
-
716
- // 1st call: GET changeset by timestamp
717
- const csUrl = new URL(fetchSpy.mock.calls[0][0] as string);
718
- expect(csUrl.pathname).toBe(`/api/changeset/v1/${ORG}/${DOC_ID}`);
719
- expect(csUrl.searchParams.get("to")).toBe(String(SNAPSHOT_1.createdAt));
720
-
721
- // 2nd call: POST rollback
722
- const [rollbackUrl, rollbackInit] = fetchSpy.mock.calls[1];
723
- expect(rollbackUrl).toBe(`${BASE_URL}/rollback/v1/${ORG}/${DOC_ID}`);
724
- expect(rollbackInit.method).toBe("POST");
725
-
726
- expect(content).toBeInstanceOf(Uint8Array);
727
- });
860
+ it("waits for the post-rollback document and applies it to the original live document", async () => {
861
+ const { api, doc, fragment } = storage();
862
+ fragment.push(["before"]);
863
+ const server = new Y.Doc();
864
+ Y.applyUpdate(server, Y.encodeStateAsUpdate(doc));
865
+ server.get("default").delete(0, 1);
866
+ server.get("default").push(["restored"]);
867
+ let finish!: (response: Response) => void;
868
+ const postRollback = new Promise<Response>((resolve) => {
869
+ finish = resolve;
728
870
  });
871
+ fetchSpy
872
+ .mockResolvedValueOnce(response({ activity: [latest] }))
873
+ .mockResolvedValueOnce(response({ doc: Y.encodeStateAsUpdate(doc) }))
874
+ .mockResolvedValueOnce(response({ versions: [{ ...version, t: 2000 }] }))
875
+ .mockResolvedValueOnce(response({ success: true }))
876
+ .mockReturnValueOnce(postRollback);
877
+ let completed = false;
878
+ const restore = api.restore!("900-1000").then((result) => {
879
+ completed = true;
880
+ return result;
881
+ });
882
+ await vi.waitFor(() => expect(fetchSpy).toHaveBeenCalledTimes(5));
883
+ expect(completed).toBe(false);
884
+ expect(fragment.toArray()).toEqual(["before"]);
885
+ finish(response({ doc: Y.encodeStateAsUpdate(server) }));
886
+ expect(await restore).toEqual({ ok: true, value: undefined });
887
+ expect(fragment.toArray()).toEqual(["restored"]);
888
+ server.destroy();
889
+ });
729
890
 
730
- // -------------------------------------------------------------------------
731
- // rename
732
- // -------------------------------------------------------------------------
733
- describe("rename", () => {
734
- it("provides a rename endpoint", () => {
735
- const endpoints = makeEndpoints();
736
- expect(typeof endpoints.rename).toBe("function");
737
- });
738
-
739
- it("rename sets the name in the Y.Map", async () => {
740
- const doc = new Y.Doc();
741
- const { endpoints, fragment } = makeCollabEndpoints(doc);
742
-
743
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ success: true }));
744
- const snapshot = await endpoints.create!(fragment as any, {
745
- name: "Old",
746
- });
747
-
748
- await endpoints.rename!(snapshot, "New");
749
-
750
- const names = doc.get("__bn_version_names");
751
- expect(names.getAttr(snapshot.id as string)).toBe("New");
752
- });
753
-
754
- it("rename with no name clears the entry", async () => {
755
- const doc = new Y.Doc();
756
- const { endpoints, fragment } = makeCollabEndpoints(doc);
757
-
758
- fetchSpy.mockResolvedValueOnce(mockFetchResponse({ success: true }));
759
- const snapshot = await endpoints.create!(fragment as any, {
760
- name: "Old",
761
- });
762
-
763
- await endpoints.rename!(snapshot, undefined);
764
-
765
- const names = doc.get("__bn_version_names");
766
- expect(names.hasAttr(snapshot.id as string)).toBe(false);
891
+ it.each([
892
+ { status: 403, error: { type: "forbidden" } },
893
+ { status: 404, error: { type: "not-found" } },
894
+ { status: 409, error: { type: "conflict" } },
895
+ { status: 500, error: { type: "server", status: 500 } },
896
+ ])(
897
+ "returns a typed expected error for HTTP $status without exposing its body",
898
+ async ({ status, error }) => {
899
+ fetchSpy.mockResolvedValueOnce(
900
+ response({ error: "private server details" }, status),
901
+ );
902
+ expect(await new YHubClient(options).getActivity()).toEqual({
903
+ ok: false,
904
+ error,
767
905
  });
906
+ },
907
+ );
908
+
909
+ it("classifies transport failures but lets unexpected bugs throw", async () => {
910
+ const client = new YHubClient(options);
911
+ fetchSpy.mockRejectedValueOnce(new TypeError("fetch failed"));
912
+ expect(await client.getActivity()).toEqual({
913
+ ok: false,
914
+ error: { type: "network" },
768
915
  });
916
+ const bug = new Error("programmer error");
917
+ fetchSpy.mockRejectedValueOnce(bug);
918
+ await expect(client.getActivity()).rejects.toBe(bug);
919
+ fetchSpy.mockResolvedValueOnce(response(null));
920
+ await expect(client.getActivity()).rejects.toThrow();
921
+ });
769
922
 
770
- // -------------------------------------------------------------------------
771
- // error handling
772
- // -------------------------------------------------------------------------
773
- describe("error handling", () => {
774
- it("throws on non-OK HTTP responses", async () => {
775
- fetchSpy.mockResolvedValueOnce(
776
- new Response("Not Found", { status: 404, statusText: "Not Found" }),
777
- );
778
-
779
- const endpoints = makeEndpoints();
780
- await expect(endpoints.list()).rejects.toThrow(
781
- "YHub request failed: 404",
782
- );
923
+ it.each(["read", "mutation"] as const)(
924
+ "bounds a hung $type request and reports whether its outcome is known",
925
+ async (type) => {
926
+ fetchSpy.mockImplementationOnce(
927
+ (_input, init) =>
928
+ new Promise((_, reject) => {
929
+ init?.signal?.addEventListener(
930
+ "abort",
931
+ () => reject(init.signal?.reason),
932
+ { once: true },
933
+ );
934
+ }),
935
+ );
936
+ const client = new YHubClient({ ...options, timeoutMs: 10 });
937
+ const result = await (type === "read"
938
+ ? client.getActivity()
939
+ : client.createVersion(1000, "Named"));
940
+ expect(result).toEqual({
941
+ ok: false,
942
+ error: {
943
+ type: "timeout",
944
+ outcome: type === "read" ? "unchanged" : "unknown",
945
+ },
783
946
  });
784
- });
947
+ expect(fetchSpy).toHaveBeenCalledOnce();
948
+ },
949
+ );
950
+
951
+ it("preserves caller cancellation rather than showing it as a network failure", async () => {
952
+ const abort = new AbortController();
953
+ fetchSpy.mockImplementationOnce(
954
+ (_input, init) =>
955
+ new Promise((_, reject) => {
956
+ init?.signal?.addEventListener(
957
+ "abort",
958
+ () => reject(init.signal?.reason),
959
+ { once: true },
960
+ );
961
+ }),
962
+ );
963
+ const pending = new YHubClient(options).getActivity(undefined, abort.signal);
964
+ abort.abort();
965
+ await expect(pending).rejects.toBe(abort.signal.reason);
785
966
  });