@blocknote/core 0.53.0 → 0.54.1

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 (219) hide show
  1. package/dist/BlockNoteExtension-BJCLnwrE.cjs +2 -0
  2. package/dist/BlockNoteExtension-BJCLnwrE.cjs.map +1 -0
  3. package/dist/BlockNoteExtension-CbvDA0F7.js +80 -0
  4. package/dist/BlockNoteExtension-CbvDA0F7.js.map +1 -0
  5. package/dist/{UserStore-QbbPFj0z.js → UserStore-C4TzkGEn.js} +3 -3
  6. package/dist/{UserStore-DCG6lsla.cjs.map → UserStore-C4TzkGEn.js.map} +1 -1
  7. package/dist/{UserStore-DCG6lsla.cjs → UserStore-mj3fXW4D.cjs} +2 -2
  8. package/dist/UserStore-mj3fXW4D.cjs.map +1 -0
  9. package/dist/blocknote.cjs +1 -1
  10. package/dist/blocknote.js +6 -6
  11. package/dist/blocks-CTB_5Vyj.cjs +12 -0
  12. package/dist/blocks-CTB_5Vyj.cjs.map +1 -0
  13. package/dist/{blocks-BEJW9OM_.js → blocks-Dol85hpH.js} +680 -670
  14. package/dist/blocks-Dol85hpH.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 +7 -7
  20. package/dist/comments.js.map +1 -1
  21. package/dist/en-BuzSuuTq.cjs +2 -0
  22. package/dist/en-BuzSuuTq.cjs.map +1 -0
  23. package/dist/{en-CGKXfWma.js → en-uzHzj6eH.js} +10 -1
  24. package/dist/en-uzHzj6eH.js.map +1 -0
  25. package/dist/extensions-B7Rsp_Ft.cjs +58 -0
  26. package/dist/extensions-B7Rsp_Ft.cjs.map +1 -0
  27. package/dist/{extensions-BR5hkAio.js → extensions-D6JcJCwd.js} +735 -457
  28. package/dist/extensions-D6JcJCwd.js.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 +199 -1
  34. package/dist/locales.js.map +1 -1
  35. package/dist/{src-BUXut68d.js → src-Buuo5l7X.js} +924 -851
  36. package/dist/src-Buuo5l7X.js.map +1 -0
  37. package/dist/src-C54Ok9E0.cjs +23 -0
  38. package/dist/src-C54Ok9E0.cjs.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 +245 -242
  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 +79 -67
  48. package/dist/yjs.js.map +1 -1
  49. package/package.json +17 -18
  50. package/src/api/blockManipulation/commands/updateBlock/__snapshots__/updateBlock.test.ts.snap +2505 -763
  51. package/src/api/blockManipulation/commands/updateBlock/updateBlock.test.ts +42 -0
  52. package/src/api/blockManipulation/commands/updateBlock/updateBlock.ts +16 -4
  53. package/src/api/exporters/markdown/htmlToMarkdown.ts +45 -10
  54. package/src/api/getBlocksChangedByTransaction.test.ts +211 -0
  55. package/src/api/getBlocksChangedByTransaction.ts +48 -12
  56. package/src/api/getChangedRange.ts +54 -0
  57. package/src/api/nodeConversions/blockToNode.ts +5 -1
  58. package/src/api/nodeConversions/nodeToBlock.ts +3 -0
  59. package/src/api/pmUtil.ts +16 -8
  60. package/src/blocks/Code/CodeBlockOptions.ts +83 -0
  61. package/src/blocks/Code/block.test.ts +1 -1
  62. package/src/blocks/Code/block.ts +29 -281
  63. package/src/blocks/Code/helpers/extensions/CodeKeyboardShortcutsExtension.ts +120 -0
  64. package/src/blocks/Code/helpers/parse/parsePreCode.ts +45 -0
  65. package/src/blocks/Code/helpers/render/createCodeBlock.ts +98 -0
  66. package/src/blocks/Code/helpers/toExternalHTML/createPreCode.ts +14 -0
  67. package/src/blocks/index.ts +3 -1
  68. package/src/comments/extension.ts +2 -4
  69. package/src/editor/Block.css +273 -2
  70. package/src/editor/BlockNoteEditor.ts +25 -4
  71. package/src/editor/BlockNoteExtension.ts +1 -1
  72. package/src/editor/managers/ExtensionManager/extensions.ts +6 -0
  73. package/src/editor/performance.test.ts +45 -0
  74. package/src/exporter/ExportImage.ts +50 -0
  75. package/src/exporter/Exporter.test.ts +186 -0
  76. package/src/exporter/Exporter.ts +66 -14
  77. package/src/exporter/index.ts +1 -0
  78. package/src/exporter/mapping.ts +4 -1
  79. package/src/extensions/FormattingToolbar/FormattingToolbar.ts +10 -8
  80. package/src/extensions/InlineContentBoundaryEdit/InlineContentBoundaryEdit.ts +109 -0
  81. package/src/extensions/PreviousBlockType/PreviousBlockType.test.ts +21 -0
  82. package/src/extensions/PreviousBlockType/PreviousBlockType.ts +5 -3
  83. package/src/extensions/SourceBlockWithPreview/SourceBlockWithPreview.ts +192 -0
  84. package/src/extensions/SourceInlineContentWithPreview/SourceInlineContentWithPreview.ts +142 -0
  85. package/src/extensions/SyntaxHighlighting/SyntaxHighlighting.test.ts +120 -0
  86. package/src/extensions/SyntaxHighlighting/SyntaxHighlighting.ts +89 -0
  87. package/src/extensions/SyntaxHighlighting/inlineHighlight.test.ts +135 -0
  88. package/src/extensions/SyntaxHighlighting/shiki.ts +116 -0
  89. package/src/extensions/TableHandles/TableHandles.browser.test.ts +305 -0
  90. package/src/extensions/TableHandles/TableHandles.ts +82 -41
  91. package/src/extensions/Versioning/inMemoryVersioning.ts +13 -3
  92. package/src/extensions/index.ts +4 -0
  93. package/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.test.ts +51 -2
  94. package/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.ts +22 -2
  95. package/src/fonts/inter.css +9 -9
  96. package/src/i18n/locales/ar.ts +9 -0
  97. package/src/i18n/locales/de.ts +9 -0
  98. package/src/i18n/locales/en.ts +9 -0
  99. package/src/i18n/locales/es.ts +9 -0
  100. package/src/i18n/locales/fa.ts +9 -0
  101. package/src/i18n/locales/fr.ts +9 -0
  102. package/src/i18n/locales/he.ts +9 -0
  103. package/src/i18n/locales/hr.ts +9 -0
  104. package/src/i18n/locales/is.ts +9 -0
  105. package/src/i18n/locales/it.ts +9 -0
  106. package/src/i18n/locales/ja.ts +9 -0
  107. package/src/i18n/locales/ko.ts +9 -0
  108. package/src/i18n/locales/nl.ts +9 -0
  109. package/src/i18n/locales/no.ts +9 -0
  110. package/src/i18n/locales/pl.ts +9 -0
  111. package/src/i18n/locales/pt.ts +9 -0
  112. package/src/i18n/locales/ru.ts +9 -0
  113. package/src/i18n/locales/sk.ts +9 -0
  114. package/src/i18n/locales/uk.ts +9 -0
  115. package/src/i18n/locales/uz.ts +9 -0
  116. package/src/i18n/locales/vi.ts +9 -0
  117. package/src/i18n/locales/zh-tw.ts +9 -0
  118. package/src/i18n/locales/zh.ts +9 -0
  119. package/src/index.ts +5 -1
  120. package/src/schema/blocks/createSpec.ts +5 -7
  121. package/src/schema/blocks/types.ts +53 -3
  122. package/src/schema/contentTypePropagation.test.ts +1 -1
  123. package/src/schema/inlineContent/createSpec.test.ts +161 -0
  124. package/src/schema/inlineContent/createSpec.ts +175 -17
  125. package/src/schema/inlineContent/internal.ts +21 -2
  126. package/src/schema/inlineContent/types.ts +35 -5
  127. package/src/schema/nodeViewMutations.test.ts +81 -56
  128. package/src/schema/nodeViewMutations.ts +30 -27
  129. package/src/schema/schema.test.ts +110 -0
  130. package/src/schema/schema.ts +13 -4
  131. package/src/user/UserStore.ts +1 -1
  132. package/src/util/Store.test.ts +132 -0
  133. package/src/util/Store.ts +135 -0
  134. package/src/y/extensions/AttributionExtension.test.ts +18 -9
  135. package/src/y/extensions/Versioning.test.ts +20 -7
  136. package/src/y/versioning/__test__/yhub.test.ts +92 -59
  137. package/src/y/versioning/yhub.ts +35 -29
  138. package/src/yjs/comments/RESTYjsThreadStore.test.ts +85 -0
  139. package/src/yjs/comments/RESTYjsThreadStore.ts +7 -1
  140. package/src/yjs/extensions/ForkYDoc.test.ts +37 -0
  141. package/src/yjs/extensions/ForkYDoc.ts +26 -1
  142. package/src/yjs/extensions/RelativePositionMapping.ts +8 -2
  143. package/src/yjs/extensions/Versioning.test.ts +17 -5
  144. package/types/src/api/getChangedRange.d.ts +14 -0
  145. package/types/src/api/pmUtil.d.ts +7 -7
  146. package/types/src/blocks/Code/CodeBlockOptions.d.ts +61 -0
  147. package/types/src/blocks/Code/block.d.ts +3 -53
  148. package/types/src/blocks/Code/helpers/extensions/CodeKeyboardShortcutsExtension.d.ts +35 -0
  149. package/types/src/blocks/Code/helpers/parse/parsePreCode.d.ts +8 -0
  150. package/types/src/blocks/Code/helpers/render/createCodeBlock.d.ts +18 -0
  151. package/types/src/blocks/Code/helpers/toExternalHTML/createPreCode.d.ts +5 -0
  152. package/types/src/blocks/index.d.ts +3 -1
  153. package/types/src/comments/extension.d.ts +1 -15
  154. package/types/src/editor/BlockNoteEditor.d.ts +3 -3
  155. package/types/src/editor/BlockNoteExtension.d.ts +1 -1
  156. package/types/src/exporter/ExportImage.d.ts +36 -0
  157. package/types/src/exporter/Exporter.d.ts +30 -0
  158. package/types/src/exporter/Exporter.test.d.ts +1 -0
  159. package/types/src/exporter/index.d.ts +1 -0
  160. package/types/src/exporter/mapping.d.ts +1 -1
  161. package/types/src/extensions/FilePanel/FilePanel.d.ts +1 -1
  162. package/types/src/extensions/FormattingToolbar/FormattingToolbar.d.ts +1 -1
  163. package/types/src/extensions/InlineContentBoundaryEdit/InlineContentBoundaryEdit.d.ts +5 -0
  164. package/types/src/extensions/ShowSelection/ShowSelection.d.ts +1 -5
  165. package/types/src/extensions/SideMenu/SideMenu.d.ts +1 -1
  166. package/types/src/extensions/SourceBlockWithPreview/SourceBlockWithPreview.d.ts +45 -0
  167. package/types/src/extensions/SourceInlineContentWithPreview/SourceInlineContentWithPreview.d.ts +49 -0
  168. package/types/src/extensions/SuggestionMenu/SuggestionMenu.d.ts +1 -11
  169. package/types/src/extensions/SyntaxHighlighting/SyntaxHighlighting.d.ts +44 -0
  170. package/types/src/extensions/SyntaxHighlighting/SyntaxHighlighting.test.d.ts +1 -0
  171. package/types/src/extensions/SyntaxHighlighting/inlineHighlight.test.d.ts +1 -0
  172. package/types/src/extensions/SyntaxHighlighting/shiki.d.ts +13 -0
  173. package/types/src/extensions/TableHandles/TableHandles.browser.test.d.ts +1 -0
  174. package/types/src/extensions/TableHandles/TableHandles.d.ts +4 -1
  175. package/types/src/extensions/Versioning/Versioning.d.ts +1 -35
  176. package/types/src/extensions/index.d.ts +4 -0
  177. package/types/src/i18n/locales/en.d.ts +9 -0
  178. package/types/src/i18n/locales/fa.d.ts +9 -0
  179. package/types/src/i18n/locales/sk.d.ts +9 -0
  180. package/types/src/index.d.ts +2 -1
  181. package/types/src/schema/blocks/types.d.ts +36 -3
  182. package/types/src/schema/inlineContent/createSpec.d.ts +35 -3
  183. package/types/src/schema/inlineContent/createSpec.test.d.ts +1 -0
  184. package/types/src/schema/inlineContent/internal.d.ts +3 -2
  185. package/types/src/schema/inlineContent/types.d.ts +22 -3
  186. package/types/src/schema/nodeViewMutations.d.ts +2 -2
  187. package/types/src/schema/schema.test.d.ts +1 -0
  188. package/types/src/user/UserStore.d.ts +1 -1
  189. package/types/src/util/Store.d.ts +45 -0
  190. package/types/src/util/Store.test.d.ts +1 -0
  191. package/types/src/y/extensions/AttributionExtension.d.ts +1 -1
  192. package/types/src/y/extensions/DiffVersioningExtension.d.ts +1 -1
  193. package/types/src/y/extensions/ForkYDoc.d.ts +1 -5
  194. package/types/src/y/extensions/index.d.ts +2 -10
  195. package/types/src/y/versioning/yhub.d.ts +3 -2
  196. package/types/src/yjs/comments/RESTYjsThreadStore.test.d.ts +1 -0
  197. package/types/src/yjs/extensions/ForkYDoc.d.ts +1 -5
  198. package/types/src/yjs/extensions/index.d.ts +1 -5
  199. package/dist/BlockNoteExtension-B_IEJHS8.js +0 -38
  200. package/dist/BlockNoteExtension-B_IEJHS8.js.map +0 -1
  201. package/dist/BlockNoteExtension-M0znTzxP.cjs +0 -2
  202. package/dist/BlockNoteExtension-M0znTzxP.cjs.map +0 -1
  203. package/dist/UserStore-QbbPFj0z.js.map +0 -1
  204. package/dist/blocks-BEJW9OM_.js.map +0 -1
  205. package/dist/blocks-BPmJglFo.cjs +0 -12
  206. package/dist/blocks-BPmJglFo.cjs.map +0 -1
  207. package/dist/en-C5Z4Ag9_.cjs +0 -2
  208. package/dist/en-C5Z4Ag9_.cjs.map +0 -1
  209. package/dist/en-CGKXfWma.js.map +0 -1
  210. package/dist/extensions-AitWbYdJ.cjs +0 -52
  211. package/dist/extensions-AitWbYdJ.cjs.map +0 -1
  212. package/dist/extensions-BR5hkAio.js.map +0 -1
  213. package/dist/src-BHPuOo7W.cjs +0 -21
  214. package/dist/src-BHPuOo7W.cjs.map +0 -1
  215. package/dist/src-BUXut68d.js.map +0 -1
  216. package/src/blocks/Code/shiki.ts +0 -73
  217. package/src/blocks/File/helpers/uploadToTmpFilesDotOrg_DEV_ONLY.ts +0 -20
  218. package/types/src/blocks/Code/shiki.d.ts +0 -4
  219. package/types/src/blocks/File/helpers/uploadToTmpFilesDotOrg_DEV_ONLY.d.ts +0 -6
package/dist/yjs.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"yjs.js","names":[],"sources":["../src/yjs/utils.ts","../src/yjs/extensions/FixUpSchema.ts","../src/yjs/extensions/YCursorPlugin.ts","../src/yjs/extensions/YSync.ts","../src/yjs/extensions/YUndo.ts","../src/yjs/extensions/ForkYDoc.ts","../src/yjs/extensions/RelativePositionMapping.ts","../src/yjs/extensions/schemaMigration/migrationRules/moveColorAttributes.ts","../src/yjs/extensions/schemaMigration/migrationRules/index.ts","../src/yjs/extensions/schemaMigration/SchemaMigration.ts","../src/yjs/extensions/Versioning.ts","../src/yjs/extensions/index.ts","../src/yjs/comments/yjsHelpers.ts","../src/yjs/comments/YjsThreadStoreBase.ts","../src/yjs/comments/RESTYjsThreadStore.ts","../src/yjs/comments/YjsThreadStore.ts"],"sourcesContent":["import {\n prosemirrorToYDoc,\n prosemirrorToYXmlFragment,\n yXmlFragmentToProseMirrorRootNode,\n} from \"y-prosemirror\";\nimport * as Y from \"yjs\";\n\nimport {\n type Block,\n type BlockNoteEditor,\n type BlockSchema,\n type InlineContentSchema,\n type PartialBlock,\n type StyleSchema,\n blockToNode,\n docToBlocks,\n} from \"../index.js\";\n\n/**\n * Find a Y.AbstractType in another Y.Doc that corresponds to the same\n * logical type in the original doc.\n */\nexport function findTypeInOtherYdoc<T extends Y.AbstractType<any>>(\n ytype: T,\n otherYdoc: Y.Doc,\n): T {\n const ydoc = ytype.doc;\n if (!ydoc) {\n throw new Error(\"type does not have a ydoc\");\n }\n if (ytype._item === null) {\n const rootKey = Array.from(ydoc.share.keys()).find(\n (key) => ydoc.share.get(key) === ytype,\n );\n if (rootKey == null) {\n throw new Error(\"type does not exist in other ydoc\");\n }\n return otherYdoc.get(rootKey, ytype.constructor as new () => T) as T;\n } else {\n const ytypeItem = ytype._item;\n const otherStructs = otherYdoc.store.clients.get(ytypeItem.id.client) ?? [];\n const itemIndex = Y.findIndexSS(otherStructs, ytypeItem.id.clock);\n const otherItem = otherStructs[itemIndex] as Y.Item | undefined;\n if (!otherItem) {\n throw new Error(\"type does not exist in other ydoc\");\n }\n const otherContent = otherItem.content as Y.ContentType | undefined;\n if (!otherContent) {\n throw new Error(\"type does not exist in other ydoc\");\n }\n return otherContent.type as T;\n }\n}\n\n/**\n * Turn Prosemirror JSON to BlockNote style JSON\n * @param editor BlockNote editor\n * @param json Prosemirror JSON\n * @returns BlockNote style JSON\n */\nexport function _prosemirrorJSONToBlocks<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(editor: BlockNoteEditor<BSchema, ISchema, SSchema>, json: any) {\n // note: theoretically this should also be possible without creating prosemirror nodes,\n // but this is definitely the easiest way\n const doc = editor.pmSchema.nodeFromJSON(json);\n return docToBlocks<BSchema, ISchema, SSchema>(doc);\n}\n\n/**\n * Turn BlockNote JSON to Prosemirror node / state\n * @param editor BlockNote editor\n * @param blocks BlockNote blocks\n * @returns Prosemirror root node\n */\nexport function _blocksToProsemirrorNode<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n blocks: PartialBlock<BSchema, ISchema, SSchema>[],\n) {\n const pmNodes = blocks.map((b) => blockToNode(b, editor.pmSchema));\n\n const doc = editor.pmSchema.topNodeType.create(\n null,\n editor.pmSchema.nodes[\"blockGroup\"].create(null, pmNodes),\n );\n return doc;\n}\n\n/** YJS / BLOCKNOTE conversions */\n\n/**\n * Turn a Y.XmlFragment collaborative doc into a BlockNote document (BlockNote style JSON of all blocks)\n * @param editor BlockNote editor\n * @param xmlFragment Y.XmlFragment\n * @returns BlockNote document (BlockNote style JSON of all blocks)\n */\nexport function yXmlFragmentToBlocks<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n xmlFragment: Y.XmlFragment,\n) {\n const pmNode = yXmlFragmentToProseMirrorRootNode(\n xmlFragment,\n editor.pmSchema,\n );\n return docToBlocks<BSchema, ISchema, SSchema>(pmNode);\n}\n\n/**\n * Convert blocks to a Y.XmlFragment\n *\n * This can be used when importing existing content to Y.Doc for the first time,\n * note that this should not be used to rehydrate a Y.Doc from a database once\n * collaboration has begun as all history will be lost\n *\n * @param editor BlockNote editor\n * @param blocks the blocks to convert\n * @param xmlFragment XML fragment name\n * @returns Y.XmlFragment\n */\nexport function blocksToYXmlFragment<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n blocks: Block<BSchema, ISchema, SSchema>[],\n xmlFragment?: Y.XmlFragment,\n) {\n return prosemirrorToYXmlFragment(\n _blocksToProsemirrorNode(editor, blocks),\n xmlFragment,\n );\n}\n\n/**\n * Turn a Y.Doc collaborative doc into a BlockNote document (BlockNote style JSON of all blocks)\n * @param editor BlockNote editor\n * @param ydoc Y.Doc\n * @param xmlFragment XML fragment name\n * @returns BlockNote document (BlockNote style JSON of all blocks)\n */\nexport function yDocToBlocks<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n ydoc: Y.Doc,\n xmlFragment = \"prosemirror\",\n) {\n return yXmlFragmentToBlocks(editor, ydoc.getXmlFragment(xmlFragment));\n}\n\n/**\n * This can be used when importing existing content to Y.Doc for the first time,\n * note that this should not be used to rehydrate a Y.Doc from a database once\n * collaboration has begun as all history will be lost\n *\n * @param editor BlockNote editor\n * @param blocks the blocks to convert\n * @param xmlFragment XML fragment name\n */\nexport function blocksToYDoc<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n blocks: PartialBlock<BSchema, ISchema, SSchema>[],\n xmlFragment = \"prosemirror\",\n) {\n return prosemirrorToYDoc(\n _blocksToProsemirrorNode(editor, blocks),\n xmlFragment,\n );\n}\n","import { Attrs, Fragment, Mark, Node, NodeType } from \"prosemirror-model\";\n\nimport { isPlainContentNodeType } from \"../../api/pmUtil.js\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\n// Collaboration-only patches to the live ProseMirror schema. Both are applied\n// once on `create`, before y-prosemirror binds and reconstructs the document.\nexport const FixUpSchemaExtension = createExtension(({ editor }) => {\n editor.on(\"create\", () => {\n const schema = editor.pmSchema;\n\n // 1. Preserve the initial block id.\n // When y-prosemirror creates an empty document, the `blockContainer` node is created with an `id` of `null`.\n // This causes the unique id extension to generate a new id for the initial block, which is not what we want\n // Since it will be randomly generated & cause there to be more updates to the ydoc\n // This is a hack to make it so that anytime `schema.doc.createAndFill` is called, the initial block id is already set to \"initialBlockId\"\n let cache: Node | undefined = undefined;\n // eslint-disable-next-line @typescript-eslint/unbound-method -- intentionally saving reference for monkey-patching\n const oldCreateAndFill = schema.nodes.doc.createAndFill;\n schema.nodes.doc.createAndFill = ((...args: any) => {\n if (cache) {\n return cache;\n }\n const ret = oldCreateAndFill.apply(schema.nodes.doc, args)!;\n\n // create a copy that we can mutate (otherwise, assigning attrs is not safe and corrupts the pm state)\n const jsonNode = JSON.parse(JSON.stringify(ret.toJSON()));\n jsonNode.content[0].content[0].attrs.id = \"initialBlockId\";\n\n cache = Node.fromJSON(schema, jsonNode);\n return cache;\n }) as unknown as typeof schema.nodes.doc.createAndFill;\n\n // 2. Drop marks a plain block no longer allows, instead of deleting the block.\n // When a block's content type changes across BlockNote versions — e.g. a\n // `codeBlock` that was `\"inline\"` (formatting marks like bold allowed) and is\n // now `\"plain\"` (only the `\"annotation\"` mark group: comments + suggestions) —\n // old Yjs documents carry text with marks the new node type disallows.\n //\n // y-prosemirror rebuilds each block by calling `schema.node(nodeName, attrs,\n // children)`, where `children` are text nodes that may still carry those\n // disallowed marks. `createChecked` then throws, and y-prosemirror's error\n // handler DELETES the whole block from the Yjs doc — a deletion that propagates\n // to every peer (data loss).\n //\n // Rather than mutating the Yjs doc to strip those marks, we leave them in place\n // (marks are just format attributes; they don't affect position counting, so\n // editing text is unaffected) and simply never materialize the disallowed ones\n // into ProseMirror. We do that by wrapping `schema.node` to filter each text\n // child's marks through the parent node type's `allowedMarks` before the node\n // is built. The wrapper is scoped to plain-content blocks (the only place this\n // migration applies); all other node types pass through untouched.\n //\n // NOTE: this covers marks that EXIST in the schema but aren't allowed on the\n // node. A mark whose type is entirely absent from the schema still hits\n // y-prosemirror's earlier `schema.mark` throw (and delete) path — that's a\n // different migration scenario and is out of scope here.\n // eslint-disable-next-line @typescript-eslint/unbound-method -- intentionally saving reference for monkey-patching\n const originalNode = schema.node;\n schema.node = function (\n this: typeof schema,\n type: string | NodeType,\n attrs?: Attrs | null,\n content?: Fragment | Node | readonly Node[],\n marks?: readonly Mark[],\n ) {\n const nodeType = typeof type === \"string\" ? this.nodes[type] : type;\n // y-prosemirror always passes `content` as a plain array of nodes; only\n // touch text children that carry marks.\n if (\n nodeType &&\n isPlainContentNodeType(this, nodeType) &&\n Array.isArray(content)\n ) {\n content = (content as readonly Node[]).map((child) =>\n child?.isText && child.marks.length\n ? child.mark(nodeType.allowedMarks(child.marks))\n : child,\n );\n }\n return originalNode.call(this, type, attrs, content, marks);\n } as typeof schema.node;\n });\n\n return {\n key: \"fixUpSchema\",\n } as const;\n});\n","import { defaultSelectionBuilder, yCursorPlugin } from \"y-prosemirror\";\nimport {\n createExtension,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport type { CollaborationOptions } from \"./index.js\";\n\nexport type CollaborationUser = {\n id?: string;\n name: string;\n color: string;\n [key: string]: unknown;\n};\n\n/**\n * Determine whether the foreground color should be white or black based on a provided background color\n * Inspired by: https://stackoverflow.com/a/3943023\n */\nfunction isDarkColor(bgColor: string): boolean {\n const color = bgColor.charAt(0) === \"#\" ? bgColor.substring(1, 7) : bgColor;\n const r = parseInt(color.substring(0, 2), 16); // hexToR\n const g = parseInt(color.substring(2, 4), 16); // hexToG\n const b = parseInt(color.substring(4, 6), 16); // hexToB\n const uicolors = [r / 255, g / 255, b / 255];\n const c = uicolors.map((col) => {\n if (col <= 0.03928) {\n return col / 12.92;\n }\n return Math.pow((col + 0.055) / 1.055, 2.4);\n });\n const L = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];\n return L <= 0.179;\n}\n\nfunction defaultCursorRender(user: CollaborationUser) {\n const cursorElement = document.createElement(\"span\");\n\n cursorElement.classList.add(\"bn-collaboration-cursor__base\");\n\n const caretElement = document.createElement(\"span\");\n caretElement.setAttribute(\"contentedEditable\", \"false\");\n caretElement.classList.add(\"bn-collaboration-cursor__caret\");\n caretElement.setAttribute(\n \"style\",\n `background-color: ${user.color}; color: ${\n isDarkColor(user.color) ? \"white\" : \"black\"\n }`,\n );\n\n const labelElement = document.createElement(\"span\");\n\n labelElement.classList.add(\"bn-collaboration-cursor__label\");\n labelElement.setAttribute(\n \"style\",\n `background-color: ${user.color}; color: ${\n isDarkColor(user.color) ? \"white\" : \"black\"\n }`,\n );\n labelElement.insertBefore(document.createTextNode(user.name), null);\n\n caretElement.insertBefore(labelElement, null);\n\n cursorElement.insertBefore(document.createTextNode(\"\\u2060\"), null); // Non-breaking space\n cursorElement.insertBefore(caretElement, null);\n cursorElement.insertBefore(document.createTextNode(\"\\u2060\"), null); // Non-breaking space\n\n return cursorElement;\n}\n\nexport const YCursorExtension = createExtension(\n ({ options }: ExtensionOptions<CollaborationOptions>) => {\n const recentlyUpdatedCursors = new Map();\n const awareness =\n options.provider &&\n \"awareness\" in options.provider &&\n typeof options.provider.awareness === \"object\"\n ? options.provider.awareness\n : undefined;\n if (awareness) {\n if (\n \"setLocalStateField\" in awareness &&\n typeof awareness.setLocalStateField === \"function\"\n ) {\n awareness.setLocalStateField(\"user\", options.user);\n }\n }\n\n const handleAwarenessChange = ({\n updated,\n }: {\n added: Array<number>;\n updated: Array<number>;\n removed: Array<number>;\n }) => {\n for (const clientID of updated) {\n const cursor = recentlyUpdatedCursors.get(clientID);\n\n if (cursor) {\n setTimeout(() => {\n cursor.element.setAttribute(\"data-active\", \"\");\n }, 10);\n\n if (cursor.hideTimeout) {\n clearTimeout(cursor.hideTimeout);\n }\n\n recentlyUpdatedCursors.set(clientID, {\n element: cursor.element,\n hideTimeout: setTimeout(() => {\n cursor.element.removeAttribute(\"data-active\");\n }, 2000),\n });\n }\n }\n };\n\n return {\n key: \"yCursor\",\n mount() {\n if (\n awareness &&\n options.showCursorLabels !== \"always\" &&\n \"on\" in awareness &&\n typeof awareness.on === \"function\"\n ) {\n awareness.on(\"change\", handleAwarenessChange);\n\n return () => {\n if (\"off\" in awareness && typeof awareness.off === \"function\") {\n awareness.off(\"change\", handleAwarenessChange);\n }\n };\n }\n\n return undefined;\n },\n prosemirrorPlugins: [\n awareness\n ? yCursorPlugin(awareness, {\n selectionBuilder: defaultSelectionBuilder,\n cursorBuilder(user: CollaborationUser, clientID: number) {\n let cursorData = recentlyUpdatedCursors.get(clientID);\n\n if (!cursorData) {\n const cursorElement = (\n options.renderCursor ?? defaultCursorRender\n )(user);\n\n if (options.showCursorLabels !== \"always\") {\n cursorElement.addEventListener(\"mouseenter\", () => {\n const cursor = recentlyUpdatedCursors.get(clientID)!;\n cursor.element.setAttribute(\"data-active\", \"\");\n\n if (cursor.hideTimeout) {\n clearTimeout(cursor.hideTimeout);\n recentlyUpdatedCursors.set(clientID, {\n element: cursor.element,\n hideTimeout: undefined,\n });\n }\n });\n\n cursorElement.addEventListener(\"mouseleave\", () => {\n const cursor = recentlyUpdatedCursors.get(clientID)!;\n\n recentlyUpdatedCursors.set(clientID, {\n element: cursor.element,\n hideTimeout: setTimeout(() => {\n cursor.element.removeAttribute(\"data-active\");\n }, 2000),\n });\n });\n }\n\n cursorData = {\n element: cursorElement,\n hideTimeout: undefined,\n };\n\n recentlyUpdatedCursors.set(clientID, cursorData);\n }\n\n return cursorData.element;\n },\n })\n : undefined,\n ].filter(Boolean),\n dependsOn: [\"ySync\"],\n updateUser(user: { name: string; color: string; [key: string]: string }) {\n awareness?.setLocalStateField(\"user\", user);\n },\n getUser(): CollaborationUser | undefined {\n const state = awareness?.getLocalState();\n if (!state) {\n return undefined;\n }\n return state[\"user\"];\n },\n } as const;\n },\n);\n","import { ySyncPlugin } from \"y-prosemirror\";\nimport {\n ExtensionOptions,\n createExtension,\n} from \"../../editor/BlockNoteExtension.js\";\nimport type { CollaborationOptions } from \"./index.js\";\n\nexport const YSyncExtension = createExtension(\n ({ options }: ExtensionOptions<Pick<CollaborationOptions, \"fragment\">>) => {\n return {\n key: \"ySync\",\n prosemirrorPlugins: [ySyncPlugin(options.fragment)],\n runsBefore: [\"default\"],\n } as const;\n },\n);\n","import { redoCommand, undoCommand, yUndoPlugin } from \"y-prosemirror\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\nexport const YUndoExtension = createExtension(() => {\n return {\n key: \"yUndo\",\n prosemirrorPlugins: [yUndoPlugin()],\n dependsOn: [\"yCursor\", \"ySync\"],\n undoCommand: undoCommand,\n redoCommand: redoCommand,\n } as const;\n});\n","import { yUndoPluginKey } from \"y-prosemirror\";\nimport * as Y from \"yjs\";\nimport {\n createExtension,\n createStore,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport type { CollaborationOptions } from \"./index.js\";\nimport { YCursorExtension } from \"./YCursorPlugin.js\";\nimport { YSyncExtension } from \"./YSync.js\";\nimport { YUndoExtension } from \"./YUndo.js\";\nimport { findTypeInOtherYdoc } from \"../utils.js\";\n\nexport const ForkYDocExtension = createExtension(\n ({ editor, options }: ExtensionOptions<CollaborationOptions>) => {\n let forkedState:\n | {\n originalFragment: Y.XmlFragment;\n undoStack: Y.UndoManager[\"undoStack\"];\n forkedFragment: Y.XmlFragment;\n }\n | undefined = undefined;\n\n const store = createStore({ isForked: false });\n\n return {\n key: \"yForkDoc\",\n store,\n /**\n * Fork the Y.js document from syncing to the remote,\n * allowing modifications to the document without affecting the remote.\n * These changes can later be rolled back or applied to the remote.\n */\n fork({\n /**\n * The initial update to apply to the forked document.\n * If not provided, the current document state is used.\n */\n initialUpdate,\n }: {\n initialUpdate?: Uint8Array;\n } = {}) {\n if (forkedState) {\n return;\n }\n\n const originalFragment = options.fragment;\n\n if (!originalFragment) {\n throw new Error(\"No fragment to fork from\");\n }\n\n const doc = new Y.Doc();\n // Copy the original document (or apply the provided update) to a new Yjs document\n Y.applyUpdate(\n doc,\n initialUpdate ?? Y.encodeStateAsUpdate(originalFragment.doc!),\n );\n\n // Find the forked fragment in the new Yjs document\n const forkedFragment = findTypeInOtherYdoc(originalFragment, doc);\n\n forkedState = {\n undoStack: yUndoPluginKey.getState(editor.prosemirrorState)!\n .undoManager.undoStack,\n originalFragment,\n forkedFragment,\n };\n\n const newOptions = {\n ...options,\n fragment: forkedFragment,\n };\n\n // Atomically swap the yjs plugins to avoid re-entrant dispatch issues\n // where y-prosemirror's view hooks can dispatch a transaction between\n // separate unregister/register calls, re-introducing stale plugins.\n editor.replaceExtension(\n [\"ySync\", \"yCursor\", \"yUndo\"],\n [\n YSyncExtension(newOptions),\n // No need to register the cursor plugin again, it's a local fork\n YUndoExtension(),\n ],\n );\n\n // Tell the store that the editor is now forked\n store.setState({ isForked: true });\n },\n\n /**\n * Resume syncing the Y.js document to the remote\n * If `keepChanges` is true, any changes that have been made to the forked document will be applied to the original document.\n * Otherwise, the original document will be restored and the changes will be discarded.\n */\n merge({ keepChanges }: { keepChanges: boolean }) {\n if (!forkedState) {\n return;\n }\n\n const { originalFragment, forkedFragment, undoStack } = forkedState;\n\n // Atomically swap the forked plugins back to the original ones\n editor.replaceExtension(\n [\"ySync\", \"yCursor\", \"yUndo\"],\n [\n YSyncExtension(options),\n YCursorExtension(options),\n YUndoExtension(),\n ],\n );\n\n // Reset the undo stack to the original undo stack\n yUndoPluginKey.getState(\n editor.prosemirrorState,\n )!.undoManager.undoStack = undoStack;\n\n if (keepChanges) {\n // Apply any changes that have been made to the fork, onto the original doc\n const update = Y.encodeStateAsUpdate(\n forkedFragment.doc!,\n Y.encodeStateVector(originalFragment.doc!),\n );\n // Applying this change will add to the undo stack, allowing it to be undone normally\n Y.applyUpdate(originalFragment.doc!, update, editor);\n }\n // Reset the forked state\n forkedState = undefined;\n // Tell the store that the editor is no longer forked\n store.setState({ isForked: false });\n },\n } as const;\n },\n);\n","import {\n absolutePositionToRelativePosition,\n relativePositionToAbsolutePosition,\n ySyncPluginKey,\n} from \"y-prosemirror\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\nimport type { PositionMappingExtension } from \"../../extensions/index.js\";\n\nexport const RelativePositionMappingExtension = createExtension(\n ({ editor }) => {\n return {\n key: \"yPositionMapping\",\n mapPosition: (position: number, side: \"left\" | \"right\" = \"left\") => {\n const ySyncPluginState = ySyncPluginKey.getState(\n editor.prosemirrorState,\n );\n if (!ySyncPluginState) {\n throw new Error(\"YSync plugin state not found\");\n }\n\n // 0 is a special case & always should map to itself\n if (position === 0) {\n return () => 0;\n }\n\n // If the document is empty, it has not been synced yet\n if (ySyncPluginState.binding.type.length === 0) {\n // so, we just fallback to the prosemirror position mapping extension\n // If a remote transaction or sync happens in this case. The position map will be invalidated,\n // and the positions will be moved to the end of the document\n // This is acceptable, because the document had not been synced so there are no positions to map properly into\n const fallback =\n editor.getExtension<typeof PositionMappingExtension>(\n \"positionMapping\",\n );\n if (!fallback) {\n throw new Error(\n \"positionMapping extension is not available; cannot map position before sync\",\n );\n }\n return fallback.mapPosition(position, side);\n }\n\n const relativePosition = absolutePositionToRelativePosition(\n position + (side === \"right\" ? 1 : -1),\n ySyncPluginState.binding.type,\n ySyncPluginState.binding.mapping,\n );\n\n return () => {\n const curYSyncPluginState = ySyncPluginKey.getState(\n editor.prosemirrorState,\n ) as typeof ySyncPluginState;\n const pos = relativePositionToAbsolutePosition(\n curYSyncPluginState.doc,\n curYSyncPluginState.binding.type,\n relativePosition,\n curYSyncPluginState.binding.mapping,\n );\n\n // This can happen if the element is garbage collected\n if (pos === null) {\n throw new Error(\"Position not found, cannot track positions\");\n }\n\n return pos + (side === \"right\" ? -1 : 1);\n };\n },\n } as const;\n },\n);\n","import * as Y from \"yjs\";\n\nimport { MigrationRule } from \"./migrationRule.js\";\nimport { defaultProps } from \"../../../../blocks/defaultProps.js\";\n\n// Helper function to recursively traverse a `Y.XMLElement` and its descendant\n// elements.\nconst traverseElement = (\n rootElement: Y.XmlElement,\n cb: (element: Y.XmlElement) => void,\n) => {\n cb(rootElement);\n rootElement.forEach((element) => {\n if (element instanceof Y.XmlElement) {\n traverseElement(element, cb);\n }\n });\n};\n\n// Moves `textColor` and `backgroundColor` attributes from `blockContainer`\n// nodes to their child `blockContent` nodes. This is due to a schema change\n// introduced in PR #TODO.\nexport const moveColorAttributes: MigrationRule = (fragment, tr) => {\n // Stores necessary info for all `blockContainer` nodes which still have\n // `textColor` or `backgroundColor` attributes that need to be moved.\n const targetBlockContainers: Map<\n string,\n {\n textColor: string | undefined;\n backgroundColor: string | undefined;\n }\n > = new Map();\n // Finds all elements which still have `textColor` or `backgroundColor`\n // attributes in the current Yjs fragment.\n fragment.forEach((element) => {\n if (element instanceof Y.XmlElement) {\n traverseElement(element, (element) => {\n if (\n element.nodeName === \"blockContainer\" &&\n element.hasAttribute(\"id\")\n ) {\n const textColor = element.getAttribute(\"textColor\");\n const backgroundColor = element.getAttribute(\"backgroundColor\");\n\n const colors = {\n textColor:\n textColor === defaultProps.textColor.default\n ? undefined\n : textColor,\n backgroundColor:\n backgroundColor === defaultProps.backgroundColor.default\n ? undefined\n : backgroundColor,\n };\n\n if (colors.textColor || colors.backgroundColor) {\n targetBlockContainers.set(element.getAttribute(\"id\")!, colors);\n }\n }\n });\n }\n });\n\n if (targetBlockContainers.size === 0) {\n return false;\n }\n\n // Appends transactions to add the `textColor` and `backgroundColor`\n // attributes found on each `blockContainer` node to move them to the child\n // `blockContent` node.\n tr.doc.descendants((node, pos) => {\n if (\n node.type.name === \"blockContainer\" &&\n targetBlockContainers.has(node.attrs.id)\n ) {\n const el = tr.doc.nodeAt(pos + 1);\n if (!el) {\n throw new Error(\"No element found\");\n }\n\n tr.setNodeMarkup(pos + 1, undefined, {\n // preserve existing attributes\n ...el.attrs,\n // add the textColor and backgroundColor attributes\n ...targetBlockContainers.get(node.attrs.id),\n });\n }\n });\n\n return true;\n};\n","import { MigrationRule } from \"./migrationRule.js\";\nimport { moveColorAttributes } from \"./moveColorAttributes.js\";\n\nexport default [moveColorAttributes] as MigrationRule[];\n","import { Plugin, PluginKey } from \"@tiptap/pm/state\";\nimport * as Y from \"yjs\";\n\nimport {\n createExtension,\n ExtensionOptions,\n} from \"../../../editor/BlockNoteExtension.js\";\nimport migrationRules from \"./migrationRules/index.js\";\n\n// This plugin allows us to update collaboration YDocs whenever BlockNote's\n// underlying ProseMirror schema changes. The plugin reads the current Yjs\n// fragment and dispatches additional transactions to the ProseMirror state, in\n// case things are found in the fragment that don't adhere to the editor schema\n// and need to be fixed. These fixes are defined as `MigrationRule`s within the\n// `migrationRules` directory.\nexport const SchemaMigration = createExtension(\n ({ options }: ExtensionOptions<{ fragment: Y.XmlFragment }>) => {\n let migrationDone = false;\n const pluginKey = new PluginKey(\"schemaMigration\");\n\n return {\n key: \"schemaMigration\",\n prosemirrorPlugins: [\n new Plugin({\n key: pluginKey,\n appendTransaction: (transactions, _oldState, newState) => {\n if (migrationDone) {\n return undefined;\n }\n\n if (\n // If any of the transactions are not due to a yjs sync, we don't need to run the migration\n !transactions.some((tr) => tr.getMeta(\"y-sync$\")) ||\n // If none of the transactions result in a document change, we don't need to run the migration\n transactions.every((tr) => !tr.docChanged) ||\n // If the fragment is still empty, we can't run the migration (since it has not yet been applied to the Y.Doc)\n !options.fragment.firstChild\n ) {\n return undefined;\n }\n\n const tr = newState.tr;\n for (const migrationRule of migrationRules) {\n migrationRule(options.fragment, tr);\n }\n\n migrationDone = true;\n\n if (!tr.docChanged) {\n return undefined;\n }\n\n return tr;\n },\n }),\n ],\n } as const;\n },\n);\n","import * as Y from \"yjs\";\n\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport type { PreviewController } from \"../../extensions/Versioning/index.js\";\nimport type { CollaborationOptions } from \"./index.js\";\nimport { ForkYDocExtension } from \"./ForkYDoc.js\";\n\n/**\n * Creates a Yjs v13 adapter that provides the {@link PreviewController}\n * and `getCurrentDocument` callback required by the base\n * {@link VersioningExtension}.\n *\n * Delegates to the {@link ForkYDocExtension} for entering/exiting preview:\n * - **enterPreview**: calls `fork({ initialUpdate: snapshotContent })` to\n * switch the editor to a temporary doc built from the snapshot.\n * - **exitPreview**: calls `merge({ keepChanges: false })` to discard the\n * preview and restore the live document.\n * - **applyRestore**: calls `merge({ keepChanges: true })` to apply the\n * snapshot content back to the live document.\n */\nexport function createYjsVersioningAdapter(\n /** The BlockNote editor instance (must have ForkYDocExtension). */\n editor: BlockNoteEditor<any, any, any>,\n /** The full collaboration options (used for `fragment` access). */\n options: CollaborationOptions,\n): {\n preview: PreviewController<Uint8Array>;\n getCurrentDocument: () => Y.XmlFragment;\n serializeCurrentContent: () => Uint8Array;\n} {\n const { fragment } = options;\n\n function getForkYDoc() {\n const ext = editor.getExtension(ForkYDocExtension);\n if (!ext) {\n throw new Error(\n \"ForkYDocExtension is required for the Yjs versioning adapter. \" +\n \"Make sure it is registered before the VersioningExtension.\",\n );\n }\n return ext;\n }\n\n return {\n getCurrentDocument: () => fragment,\n serializeCurrentContent: () => Y.encodeStateAsUpdateV2(fragment.doc!),\n preview: {\n // Yjs v13 can only fork the document to a single snapshot; it has no way\n // to diff two versions, so comparison is unsupported.\n supportsComparison: false,\n enterPreview(\n snapshotContent: Uint8Array,\n _compareToContent?: Uint8Array,\n ) {\n const forkYDoc = getForkYDoc();\n\n // If already in a preview (forked state), exit first.\n if (forkYDoc.store.state.isForked) {\n forkYDoc.merge({ keepChanges: false });\n }\n\n forkYDoc.fork({ initialUpdate: snapshotContent });\n },\n\n exitPreview() {\n const forkYDoc = getForkYDoc();\n if (forkYDoc.store.state.isForked) {\n forkYDoc.merge({ keepChanges: false });\n }\n },\n\n applyRestore(_snapshotContent: Uint8Array) {\n // Restoring to an older Yjs state cannot be done by merging a fork\n // because the original doc already contains all CRDT state vectors\n // from the snapshot. Restore must be handled at the endpoint/server\n // level (e.g., the server creates a new Y.Doc and syncs it).\n throw new Error(\n \"Restore is not yet implemented for Yjs v13 versioning adapter.\",\n );\n },\n },\n };\n}\n","import type { Awareness } from \"y-protocols/awareness\";\nimport type * as Y from \"yjs\";\nimport type { BlockNoteEditorOptions } from \"../../editor/BlockNoteEditor\";\nimport {\n createExtension,\n type ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport { FixUpSchemaExtension } from \"./FixUpSchema.js\";\nimport { ForkYDocExtension } from \"./ForkYDoc.js\";\nimport { RelativePositionMappingExtension } from \"./RelativePositionMapping.js\";\nimport { SchemaMigration } from \"./schemaMigration/SchemaMigration.js\";\nimport { CollaborationUser, YCursorExtension } from \"./YCursorPlugin.js\";\nimport { YSyncExtension } from \"./YSync.js\";\nimport { YUndoExtension } from \"./YUndo.js\";\n\nexport type CollaborationOptions = {\n /**\n * The Yjs XML fragment that's used for collaboration.\n */\n fragment: Y.XmlFragment;\n /**\n * The user info for the current user that's shown to other collaborators.\n */\n user: CollaborationUser;\n /**\n * A Yjs provider (used for awareness / cursor information)\n */\n provider?: { awareness?: Awareness };\n /**\n * Optional function to customize how cursors of users are rendered\n */\n renderCursor?: (user: CollaborationUser) => HTMLElement;\n /**\n * Optional flag to set when the user label should be shown with the default\n * collaboration cursor. Setting to \"always\" will always show the label,\n * while \"activity\" will only show the label when the user moves the cursor\n * or types. Defaults to \"activity\".\n */\n showCursorLabels?: \"always\" | \"activity\";\n};\n\nexport const CollaborationExtension = createExtension(\n ({ options }: ExtensionOptions<CollaborationOptions>) => {\n return {\n key: \"collaboration\",\n blockNoteExtensions: [\n FixUpSchemaExtension(),\n ForkYDocExtension(options),\n RelativePositionMappingExtension(),\n SchemaMigration(options),\n YCursorExtension(options),\n YSyncExtension(options),\n YUndoExtension(),\n ],\n } as const;\n },\n);\n\nexport function withCollaboration<\n Options extends Partial<BlockNoteEditorOptions<any, any, any>>,\n>(\n options: Options & {\n /**\n * Options for configuring the collaboration functionality.\n */\n collaboration: CollaborationOptions;\n },\n): Options {\n return {\n ...options,\n extensions: [\n ...(options.extensions ?? []),\n CollaborationExtension(options.collaboration),\n ],\n // We disable the default prosemirror history plugin, since it's not compatible with yjs\n disableExtensions: [\"history\", ...(options.disableExtensions ?? [])],\n // We don't want the default initial content, since it will generate a random id for the initial block on each client,\n // leading to conflicts when syncing happens afterwards.\n initialContent: [{ type: \"paragraph\", id: \"initialBlockId\" }],\n };\n}\n\nexport * from \"./ForkYDoc.js\";\nexport * from \"./RelativePositionMapping.js\";\nexport * from \"./schemaMigration/SchemaMigration.js\";\nexport * from \"./Versioning.js\";\nexport * from \"./YCursorPlugin.js\";\nexport * from \"./YSync.js\";\nexport * from \"./YUndo.js\";\n","import * as Y from \"yjs\";\nimport type {\n CommentData,\n CommentReactionData,\n ThreadData,\n} from \"../../comments/types.js\";\n\nexport function commentToYMap(comment: CommentData) {\n const yMap = new Y.Map<any>();\n yMap.set(\"id\", comment.id);\n yMap.set(\"userId\", comment.userId);\n yMap.set(\"createdAt\", comment.createdAt.getTime());\n yMap.set(\"updatedAt\", comment.updatedAt.getTime());\n if (comment.deletedAt) {\n yMap.set(\"deletedAt\", comment.deletedAt.getTime());\n yMap.set(\"body\", undefined);\n } else {\n yMap.set(\"body\", comment.body);\n }\n if (comment.reactions.length > 0) {\n throw new Error(\"Reactions should be empty in commentToYMap\");\n }\n\n /**\n * Reactions are stored in a map keyed by {userId-emoji},\n * this makes it easy to add / remove reactions and in a way that works local-first.\n * The cost is that \"reading\" the reactions is a bit more complex (see yMapToReactions).\n */\n yMap.set(\"reactionsByUser\", new Y.Map());\n yMap.set(\"metadata\", comment.metadata);\n\n return yMap;\n}\n\nexport function threadToYMap(thread: ThreadData) {\n const yMap = new Y.Map();\n yMap.set(\"id\", thread.id);\n yMap.set(\"createdAt\", thread.createdAt.getTime());\n yMap.set(\"updatedAt\", thread.updatedAt.getTime());\n const commentsArray = new Y.Array<Y.Map<any>>();\n\n commentsArray.push(thread.comments.map((comment) => commentToYMap(comment)));\n\n yMap.set(\"comments\", commentsArray);\n yMap.set(\"resolved\", thread.resolved);\n yMap.set(\"resolvedUpdatedAt\", thread.resolvedUpdatedAt?.getTime());\n yMap.set(\"resolvedBy\", thread.resolvedBy);\n yMap.set(\"metadata\", thread.metadata);\n return yMap;\n}\n\ntype SingleUserCommentReactionData = {\n emoji: string;\n createdAt: Date;\n userId: string;\n};\n\nexport function yMapToReaction(\n yMap: Y.Map<any>,\n): SingleUserCommentReactionData {\n return {\n emoji: yMap.get(\"emoji\"),\n createdAt: new Date(yMap.get(\"createdAt\")),\n userId: yMap.get(\"userId\"),\n };\n}\n\nfunction yMapToReactions(yMap: Y.Map<any>): CommentReactionData[] {\n const flatReactions = [...yMap.values()].map((reaction: Y.Map<any>) =>\n yMapToReaction(reaction),\n );\n // combine reactions by the same emoji\n return flatReactions.reduce(\n (acc: CommentReactionData[], reaction: SingleUserCommentReactionData) => {\n const existingReaction = acc.find((r) => r.emoji === reaction.emoji);\n if (existingReaction) {\n existingReaction.userIds.push(reaction.userId);\n existingReaction.createdAt = new Date(\n Math.min(\n existingReaction.createdAt.getTime(),\n reaction.createdAt.getTime(),\n ),\n );\n } else {\n acc.push({\n emoji: reaction.emoji,\n createdAt: reaction.createdAt,\n userIds: [reaction.userId],\n });\n }\n return acc;\n },\n [] as CommentReactionData[],\n );\n}\n\nexport function yMapToComment(yMap: Y.Map<any>): CommentData {\n return {\n type: \"comment\",\n id: yMap.get(\"id\"),\n userId: yMap.get(\"userId\"),\n createdAt: new Date(yMap.get(\"createdAt\")),\n updatedAt: new Date(yMap.get(\"updatedAt\")),\n deletedAt: yMap.get(\"deletedAt\")\n ? new Date(yMap.get(\"deletedAt\"))\n : undefined,\n reactions: yMapToReactions(yMap.get(\"reactionsByUser\")),\n metadata: yMap.get(\"metadata\"),\n body: yMap.get(\"body\"),\n };\n}\n\nexport function yMapToThread(yMap: Y.Map<any>): ThreadData {\n return {\n type: \"thread\",\n id: yMap.get(\"id\"),\n createdAt: new Date(yMap.get(\"createdAt\")),\n updatedAt: new Date(yMap.get(\"updatedAt\")),\n comments: ((yMap.get(\"comments\") as Y.Array<Y.Map<any>>) || []).map(\n (comment) => yMapToComment(comment),\n ),\n resolved: yMap.get(\"resolved\"),\n resolvedUpdatedAt: new Date(yMap.get(\"resolvedUpdatedAt\")),\n resolvedBy: yMap.get(\"resolvedBy\"),\n metadata: yMap.get(\"metadata\"),\n };\n}\n","import * as Y from \"yjs\";\nimport type { ThreadData } from \"../../comments/types.js\";\nimport { ThreadStore } from \"../../comments/threadstore/ThreadStore.js\";\nimport type { ThreadStoreAuth } from \"../../comments/threadstore/ThreadStoreAuth.js\";\nimport { yMapToThread } from \"./yjsHelpers.js\";\n\n/**\n * This is an abstract class that only implements the READ methods required by the ThreadStore interface.\n * The data is read from a Yjs Map.\n */\nexport abstract class YjsThreadStoreBase extends ThreadStore {\n constructor(\n protected readonly threadsYMap: Y.Map<any>,\n auth: ThreadStoreAuth,\n ) {\n super(auth);\n }\n\n // TODO: async / reactive interface?\n public getThread(threadId: string) {\n const yThread = this.threadsYMap.get(threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n const thread = yMapToThread(yThread);\n return thread;\n }\n\n public getThreads(): Map<string, ThreadData> {\n const threadMap = new Map<string, ThreadData>();\n this.threadsYMap.forEach((yThread, id) => {\n if (yThread instanceof Y.Map) {\n threadMap.set(id, yMapToThread(yThread));\n }\n });\n return threadMap;\n }\n\n public subscribe(cb: (threads: Map<string, ThreadData>) => void) {\n const observer = () => {\n cb(this.getThreads());\n };\n\n this.threadsYMap.observeDeep(observer);\n\n return () => {\n this.threadsYMap.unobserveDeep(observer);\n };\n }\n}\n","import * as Y from \"yjs\";\nimport {\n absolutePositionToRelativePosition,\n ySyncPluginKey,\n} from \"y-prosemirror\";\nimport type { CommentBody } from \"../../comments/types.js\";\nimport type { ThreadStoreAuth } from \"../../comments/threadstore/ThreadStoreAuth.js\";\nimport { YjsThreadStoreBase } from \"./YjsThreadStoreBase.js\";\nimport { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\n\n/**\n * This is a REST-based implementation of the YjsThreadStoreBase.\n * It Reads data directly from the underlying document (same as YjsThreadStore),\n * but for Writes, it sends data to a REST API that should:\n * - check the user has the correct permissions to make the desired changes\n * - apply the updates to the underlying Yjs document\n *\n * (see https://github.com/TypeCellOS/BlockNote-demo-nextjs-hocuspocus)\n *\n * The reason we still use the Yjs document as underlying storage is that it makes it easy to\n * sync updates in real-time to other collaborators.\n * (but technically, you could also implement a different storage altogether\n * and not store the thread related data in the Yjs document)\n */\nexport class RESTYjsThreadStore extends YjsThreadStoreBase {\n constructor(\n private readonly BASE_URL: string,\n private readonly headers: Record<string, string>,\n threadsYMap: Y.Map<any>,\n auth: ThreadStoreAuth,\n ) {\n super(threadsYMap, auth);\n }\n\n private doRequest = async (path: string, method: string, body?: any) => {\n const response = await fetch(`${this.BASE_URL}${path}`, {\n method,\n body: JSON.stringify(body),\n headers: {\n \"Content-Type\": \"application/json\",\n ...this.headers,\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to ${method} ${path}: ${response.statusText}`);\n }\n\n return response.json();\n };\n\n public addThreadToDocument = async (options: {\n threadId: string;\n selection: {\n head: number;\n anchor: number;\n };\n editor: BlockNoteEditor<any, any, any>;\n }) => {\n const { threadId, selection } = options;\n\n const binding = ySyncPluginKey.getState(options.editor.prosemirrorState);\n const yjsSelection = binding\n ? {\n head: absolutePositionToRelativePosition(\n selection.head,\n binding.type,\n binding.mapping,\n ),\n anchor: absolutePositionToRelativePosition(\n selection.anchor,\n binding.type,\n binding.mapping,\n ),\n }\n : undefined;\n\n return this.doRequest(`/${threadId}/addToDocument`, \"POST\", {\n selection: {\n prosemirror: selection,\n yjs: yjsSelection,\n },\n });\n };\n\n public createThread = async (options: {\n initialComment: {\n body: CommentBody;\n metadata?: any;\n };\n metadata?: any;\n }) => {\n return this.doRequest(\"\", \"POST\", options);\n };\n\n public addComment = (options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n }) => {\n const { threadId, ...rest } = options;\n return this.doRequest(`/${threadId}/comments`, \"POST\", rest);\n };\n\n public updateComment = (options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n commentId: string;\n }) => {\n const { threadId, commentId, ...rest } = options;\n return this.doRequest(`/${threadId}/comments/${commentId}`, \"PUT\", rest);\n };\n\n public deleteComment = (options: {\n threadId: string;\n commentId: string;\n softDelete?: boolean;\n }) => {\n const { threadId, commentId, ...rest } = options;\n return this.doRequest(\n `/${threadId}/comments/${commentId}?soft=${!!rest.softDelete}`,\n \"DELETE\",\n );\n };\n\n public deleteThread = (options: { threadId: string }) => {\n return this.doRequest(`/${options.threadId}`, \"DELETE\");\n };\n\n public resolveThread = (options: { threadId: string }) => {\n return this.doRequest(`/${options.threadId}/resolve`, \"POST\");\n };\n\n public unresolveThread = (options: { threadId: string }) => {\n return this.doRequest(`/${options.threadId}/unresolve`, \"POST\");\n };\n\n public addReaction = (options: {\n threadId: string;\n commentId: string;\n emoji: string;\n }) => {\n const { threadId, commentId, ...rest } = options;\n return this.doRequest(\n `/${threadId}/comments/${commentId}/reactions`,\n \"POST\",\n rest,\n );\n };\n\n public deleteReaction = (options: {\n threadId: string;\n commentId: string;\n emoji: string;\n }) => {\n return this.doRequest(\n `/${options.threadId}/comments/${options.commentId}/reactions/${options.emoji}`,\n \"DELETE\",\n );\n };\n}\n","import * as Y from \"yjs\";\nimport { uuidv4 } from \"lib0/random\";\nimport type {\n CommentBody,\n CommentData,\n ThreadData,\n} from \"../../comments/types.js\";\nimport type { ThreadStoreAuth } from \"../../comments/threadstore/ThreadStoreAuth.js\";\nimport { YjsThreadStoreBase } from \"./YjsThreadStoreBase.js\";\nimport {\n commentToYMap,\n threadToYMap,\n yMapToComment,\n yMapToThread,\n} from \"./yjsHelpers.js\";\n\n/**\n * This is a Yjs-based implementation of the ThreadStore interface.\n *\n * It reads and writes thread / comments information directly to the underlying Yjs Document.\n *\n * @important While this is the easiest to add to your app, there are two challenges:\n * - The user needs to be able to write to the Yjs document to store the information.\n * So a user without write access to the Yjs document cannot leave any comments.\n * - Even with write access, the operations are not secure. Unless your Yjs server\n * guards against malicious operations, it's technically possible for one user to make changes to another user's comments, etc.\n * (even though these options are not visible in the UI, a malicious user can make unauthorized changes to the underlying Yjs document)\n */\nexport class YjsThreadStore extends YjsThreadStoreBase {\n constructor(\n private readonly userId: string,\n threadsYMap: Y.Map<any>,\n auth: ThreadStoreAuth,\n ) {\n super(threadsYMap, auth);\n }\n\n private transact = <T, R>(\n fn: (options: T) => R,\n ): ((options: T) => Promise<R>) => {\n return async (options: T) => {\n return this.threadsYMap.doc!.transact(() => {\n return fn(options);\n });\n };\n };\n\n public createThread = this.transact(\n (options: {\n initialComment: {\n body: CommentBody;\n metadata?: any;\n };\n metadata?: any;\n }) => {\n if (!this.auth.canCreateThread()) {\n throw new Error(\"Not authorized\");\n }\n\n const date = new Date();\n\n const comment: CommentData = {\n type: \"comment\",\n id: uuidv4(),\n userId: this.userId,\n createdAt: date,\n updatedAt: date,\n reactions: [],\n metadata: options.initialComment.metadata,\n body: options.initialComment.body,\n };\n\n const thread: ThreadData = {\n type: \"thread\",\n id: uuidv4(),\n createdAt: date,\n updatedAt: date,\n comments: [comment],\n resolved: false,\n metadata: options.metadata,\n };\n\n this.threadsYMap.set(thread.id, threadToYMap(thread));\n\n return thread;\n },\n );\n\n // YjsThreadStore does not support addThreadToDocument\n public addThreadToDocument = undefined;\n\n public addComment = this.transact(\n (options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canAddComment(yMapToThread(yThread))) {\n throw new Error(\"Not authorized\");\n }\n\n const date = new Date();\n const comment: CommentData = {\n type: \"comment\",\n id: uuidv4(),\n userId: this.userId,\n createdAt: date,\n updatedAt: date,\n deletedAt: undefined,\n reactions: [],\n metadata: options.comment.metadata,\n body: options.comment.body,\n };\n\n (yThread.get(\"comments\") as Y.Array<Y.Map<any>>).push([\n commentToYMap(comment),\n ]);\n\n yThread.set(\"updatedAt\", new Date().getTime());\n return comment;\n },\n );\n\n public updateComment = this.transact(\n (options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n commentId: string;\n }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const yCommentIndex = yArrayFindIndex(\n yThread.get(\"comments\"),\n (comment) => comment.get(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = yThread.get(\"comments\").get(yCommentIndex);\n\n if (!this.auth.canUpdateComment(yMapToComment(yComment))) {\n throw new Error(\"Not authorized\");\n }\n\n yComment.set(\"body\", options.comment.body);\n yComment.set(\"updatedAt\", new Date().getTime());\n yComment.set(\"metadata\", options.comment.metadata);\n },\n );\n\n public deleteComment = this.transact(\n (options: {\n threadId: string;\n commentId: string;\n softDelete?: boolean;\n }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const yCommentIndex = yArrayFindIndex(\n yThread.get(\"comments\"),\n (comment) => comment.get(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = yThread.get(\"comments\").get(yCommentIndex);\n\n if (!this.auth.canDeleteComment(yMapToComment(yComment))) {\n throw new Error(\"Not authorized\");\n }\n\n if (yComment.get(\"deletedAt\")) {\n throw new Error(\"Comment already deleted\");\n }\n\n if (options.softDelete) {\n yComment.set(\"deletedAt\", new Date().getTime());\n yComment.set(\"body\", undefined);\n } else {\n yThread.get(\"comments\").delete(yCommentIndex);\n }\n\n if (\n (yThread.get(\"comments\") as Y.Array<any>)\n .toArray()\n .every((comment) => comment.get(\"deletedAt\"))\n ) {\n // all comments deleted\n if (options.softDelete) {\n yThread.set(\"deletedAt\", new Date().getTime());\n } else {\n this.threadsYMap.delete(options.threadId);\n }\n }\n\n yThread.set(\"updatedAt\", new Date().getTime());\n },\n );\n\n public deleteThread = this.transact((options: { threadId: string }) => {\n if (\n !this.auth.canDeleteThread(\n yMapToThread(this.threadsYMap.get(options.threadId)),\n )\n ) {\n throw new Error(\"Not authorized\");\n }\n\n this.threadsYMap.delete(options.threadId);\n });\n\n public resolveThread = this.transact((options: { threadId: string }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canResolveThread(yMapToThread(yThread))) {\n throw new Error(\"Not authorized\");\n }\n\n yThread.set(\"resolved\", true);\n yThread.set(\"resolvedUpdatedAt\", new Date().getTime());\n yThread.set(\"resolvedBy\", this.userId);\n });\n\n public unresolveThread = this.transact((options: { threadId: string }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canUnresolveThread(yMapToThread(yThread))) {\n throw new Error(\"Not authorized\");\n }\n\n yThread.set(\"resolved\", false);\n yThread.set(\"resolvedUpdatedAt\", new Date().getTime());\n });\n\n public addReaction = this.transact(\n (options: { threadId: string; commentId: string; emoji: string }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const yCommentIndex = yArrayFindIndex(\n yThread.get(\"comments\"),\n (comment) => comment.get(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = yThread.get(\"comments\").get(yCommentIndex);\n\n if (!this.auth.canAddReaction(yMapToComment(yComment), options.emoji)) {\n throw new Error(\"Not authorized\");\n }\n\n const date = new Date();\n\n const key = `${this.userId}-${options.emoji}`;\n\n const reactionsByUser = yComment.get(\"reactionsByUser\");\n\n if (reactionsByUser.has(key)) {\n // already exists\n return;\n } else {\n const reaction = new Y.Map();\n reaction.set(\"emoji\", options.emoji);\n reaction.set(\"createdAt\", date.getTime());\n reaction.set(\"userId\", this.userId);\n reactionsByUser.set(key, reaction);\n }\n },\n );\n\n public deleteReaction = this.transact(\n (options: { threadId: string; commentId: string; emoji: string }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const yCommentIndex = yArrayFindIndex(\n yThread.get(\"comments\"),\n (comment) => comment.get(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = yThread.get(\"comments\").get(yCommentIndex);\n\n if (\n !this.auth.canDeleteReaction(yMapToComment(yComment), options.emoji)\n ) {\n throw new Error(\"Not authorized\");\n }\n\n const key = `${this.userId}-${options.emoji}`;\n\n const reactionsByUser = yComment.get(\"reactionsByUser\");\n\n reactionsByUser.delete(key);\n },\n );\n}\n\nfunction yArrayFindIndex(\n yArray: Y.Array<any>,\n predicate: (item: any) => boolean,\n) {\n for (let i = 0; i < yArray.length; i++) {\n if (predicate(yArray.get(i))) {\n return i;\n }\n }\n return -1;\n}\n"],"mappings":";;;;;;;;;AAsBA,SAAgB,EACd,GACA,GACG;CACH,IAAM,IAAO,EAAM;CACnB,IAAI,CAAC,GACH,MAAU,MAAM,2BAA2B;CAE7C,IAAI,EAAM,UAAU,MAAM;EACxB,IAAM,IAAU,MAAM,KAAK,EAAK,MAAM,KAAK,CAAC,EAAE,MAC3C,MAAQ,EAAK,MAAM,IAAI,CAAG,MAAM,CACnC;EACA,IAAI,KAAW,MACb,MAAU,MAAM,mCAAmC;EAErD,OAAO,EAAU,IAAI,GAAS,EAAM,WAA0B;CAChE,OAAO;EACL,IAAM,IAAY,EAAM,OAClB,IAAe,EAAU,MAAM,QAAQ,IAAI,EAAU,GAAG,MAAM,KAAK,CAAC,GAEpE,IAAY,EADA,EAAE,YAAY,GAAc,EAAU,GAAG,KAC5B;EAC/B,IAAI,CAAC,GACH,MAAU,MAAM,mCAAmC;EAErD,IAAM,IAAe,EAAU;EAC/B,IAAI,CAAC,GACH,MAAU,MAAM,mCAAmC;EAErD,OAAO,EAAa;CACtB;AACF;AAQA,SAAgB,EAId,GAAoD,GAAW;CAI/D,OAAO,EADK,EAAO,SAAS,aAAa,CACK,CAAG;AACnD;AAQA,SAAgB,EAKd,GACA,GACA;CACA,IAAM,IAAU,EAAO,KAAK,MAAM,EAAY,GAAG,E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Q,GAAG,EAAQ,KAAK,GAEnE,MAAU,MAAM,gBAAgB;EAGlC,IAAM,IAAM,GAAG,KAAK,OAAO,GAAG,EAAQ;EAItC,EAFiC,IAAI,iBAErC,EAAgB,OAAO,CAAG;CAC5B,CACF;AACF;AAEA,SAAS,EACP,GACA,GACA;CACA,KAAK,IAAI,IAAI,GAAG,IAAI,EAAO,QAAQ,KACjC,IAAI,EAAU,EAAO,IAAI,CAAC,CAAC,GACzB,OAAO;CAGX,OAAO;AACT"}
1
+ {"version":3,"file":"yjs.js","names":[],"sources":["../src/yjs/utils.ts","../src/yjs/extensions/FixUpSchema.ts","../src/yjs/extensions/YCursorPlugin.ts","../src/yjs/extensions/YSync.ts","../src/yjs/extensions/YUndo.ts","../src/yjs/extensions/ForkYDoc.ts","../src/yjs/extensions/RelativePositionMapping.ts","../src/yjs/extensions/schemaMigration/migrationRules/moveColorAttributes.ts","../src/yjs/extensions/schemaMigration/migrationRules/index.ts","../src/yjs/extensions/schemaMigration/SchemaMigration.ts","../src/yjs/extensions/Versioning.ts","../src/yjs/extensions/index.ts","../src/yjs/comments/yjsHelpers.ts","../src/yjs/comments/YjsThreadStoreBase.ts","../src/yjs/comments/RESTYjsThreadStore.ts","../src/yjs/comments/YjsThreadStore.ts"],"sourcesContent":["import {\n prosemirrorToYDoc,\n prosemirrorToYXmlFragment,\n yXmlFragmentToProseMirrorRootNode,\n} from \"y-prosemirror\";\nimport * as Y from \"yjs\";\n\nimport {\n type Block,\n type BlockNoteEditor,\n type BlockSchema,\n type InlineContentSchema,\n type PartialBlock,\n type StyleSchema,\n blockToNode,\n docToBlocks,\n} from \"../index.js\";\n\n/**\n * Find a Y.AbstractType in another Y.Doc that corresponds to the same\n * logical type in the original doc.\n */\nexport function findTypeInOtherYdoc<T extends Y.AbstractType<any>>(\n ytype: T,\n otherYdoc: Y.Doc,\n): T {\n const ydoc = ytype.doc;\n if (!ydoc) {\n throw new Error(\"type does not have a ydoc\");\n }\n if (ytype._item === null) {\n const rootKey = Array.from(ydoc.share.keys()).find(\n (key) => ydoc.share.get(key) === ytype,\n );\n if (rootKey == null) {\n throw new Error(\"type does not exist in other ydoc\");\n }\n return otherYdoc.get(rootKey, ytype.constructor as new () => T) as T;\n } else {\n const ytypeItem = ytype._item;\n const otherStructs = otherYdoc.store.clients.get(ytypeItem.id.client) ?? [];\n const itemIndex = Y.findIndexSS(otherStructs, ytypeItem.id.clock);\n const otherItem = otherStructs[itemIndex] as Y.Item | undefined;\n if (!otherItem) {\n throw new Error(\"type does not exist in other ydoc\");\n }\n const otherContent = otherItem.content as Y.ContentType | undefined;\n if (!otherContent) {\n throw new Error(\"type does not exist in other ydoc\");\n }\n return otherContent.type as T;\n }\n}\n\n/**\n * Turn Prosemirror JSON to BlockNote style JSON\n * @param editor BlockNote editor\n * @param json Prosemirror JSON\n * @returns BlockNote style JSON\n */\nexport function _prosemirrorJSONToBlocks<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(editor: BlockNoteEditor<BSchema, ISchema, SSchema>, json: any) {\n // note: theoretically this should also be possible without creating prosemirror nodes,\n // but this is definitely the easiest way\n const doc = editor.pmSchema.nodeFromJSON(json);\n return docToBlocks<BSchema, ISchema, SSchema>(doc);\n}\n\n/**\n * Turn BlockNote JSON to Prosemirror node / state\n * @param editor BlockNote editor\n * @param blocks BlockNote blocks\n * @returns Prosemirror root node\n */\nexport function _blocksToProsemirrorNode<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n blocks: PartialBlock<BSchema, ISchema, SSchema>[],\n) {\n const pmNodes = blocks.map((b) => blockToNode(b, editor.pmSchema));\n\n const doc = editor.pmSchema.topNodeType.create(\n null,\n editor.pmSchema.nodes[\"blockGroup\"].create(null, pmNodes),\n );\n return doc;\n}\n\n/** YJS / BLOCKNOTE conversions */\n\n/**\n * Turn a Y.XmlFragment collaborative doc into a BlockNote document (BlockNote style JSON of all blocks)\n * @param editor BlockNote editor\n * @param xmlFragment Y.XmlFragment\n * @returns BlockNote document (BlockNote style JSON of all blocks)\n */\nexport function yXmlFragmentToBlocks<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n xmlFragment: Y.XmlFragment,\n) {\n const pmNode = yXmlFragmentToProseMirrorRootNode(\n xmlFragment,\n editor.pmSchema,\n );\n return docToBlocks<BSchema, ISchema, SSchema>(pmNode);\n}\n\n/**\n * Convert blocks to a Y.XmlFragment\n *\n * This can be used when importing existing content to Y.Doc for the first time,\n * note that this should not be used to rehydrate a Y.Doc from a database once\n * collaboration has begun as all history will be lost\n *\n * @param editor BlockNote editor\n * @param blocks the blocks to convert\n * @param xmlFragment XML fragment name\n * @returns Y.XmlFragment\n */\nexport function blocksToYXmlFragment<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n blocks: Block<BSchema, ISchema, SSchema>[],\n xmlFragment?: Y.XmlFragment,\n) {\n return prosemirrorToYXmlFragment(\n _blocksToProsemirrorNode(editor, blocks),\n xmlFragment,\n );\n}\n\n/**\n * Turn a Y.Doc collaborative doc into a BlockNote document (BlockNote style JSON of all blocks)\n * @param editor BlockNote editor\n * @param ydoc Y.Doc\n * @param xmlFragment XML fragment name\n * @returns BlockNote document (BlockNote style JSON of all blocks)\n */\nexport function yDocToBlocks<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n ydoc: Y.Doc,\n xmlFragment = \"prosemirror\",\n) {\n return yXmlFragmentToBlocks(editor, ydoc.getXmlFragment(xmlFragment));\n}\n\n/**\n * This can be used when importing existing content to Y.Doc for the first time,\n * note that this should not be used to rehydrate a Y.Doc from a database once\n * collaboration has begun as all history will be lost\n *\n * @param editor BlockNote editor\n * @param blocks the blocks to convert\n * @param xmlFragment XML fragment name\n */\nexport function blocksToYDoc<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n blocks: PartialBlock<BSchema, ISchema, SSchema>[],\n xmlFragment = \"prosemirror\",\n) {\n return prosemirrorToYDoc(\n _blocksToProsemirrorNode(editor, blocks),\n xmlFragment,\n );\n}\n","import { Attrs, Fragment, Mark, Node, NodeType } from \"prosemirror-model\";\n\nimport { isPlainContentNodeType } from \"../../api/pmUtil.js\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\n// Collaboration-only patches to the live ProseMirror schema. Both are applied\n// once on `create`, before y-prosemirror binds and reconstructs the document.\nexport const FixUpSchemaExtension = createExtension(({ editor }) => {\n editor.on(\"create\", () => {\n const schema = editor.pmSchema;\n\n // 1. Preserve the initial block id.\n // When y-prosemirror creates an empty document, the `blockContainer` node is created with an `id` of `null`.\n // This causes the unique id extension to generate a new id for the initial block, which is not what we want\n // Since it will be randomly generated & cause there to be more updates to the ydoc\n // This is a hack to make it so that anytime `schema.doc.createAndFill` is called, the initial block id is already set to \"initialBlockId\"\n let cache: Node | undefined = undefined;\n // eslint-disable-next-line @typescript-eslint/unbound-method -- intentionally saving reference for monkey-patching\n const oldCreateAndFill = schema.nodes.doc.createAndFill;\n schema.nodes.doc.createAndFill = ((...args: any) => {\n if (cache) {\n return cache;\n }\n const ret = oldCreateAndFill.apply(schema.nodes.doc, args)!;\n\n // create a copy that we can mutate (otherwise, assigning attrs is not safe and corrupts the pm state)\n const jsonNode = JSON.parse(JSON.stringify(ret.toJSON()));\n jsonNode.content[0].content[0].attrs.id = \"initialBlockId\";\n\n cache = Node.fromJSON(schema, jsonNode);\n return cache;\n }) as unknown as typeof schema.nodes.doc.createAndFill;\n\n // 2. Drop marks a plain block no longer allows, instead of deleting the block.\n // When a block's content type changes across BlockNote versions — e.g. a\n // `codeBlock` that was `\"inline\"` (formatting marks like bold allowed) and is\n // now `\"plain\"` (only the `\"annotation\"` mark group: comments + suggestions) —\n // old Yjs documents carry text with marks the new node type disallows.\n //\n // y-prosemirror rebuilds each block by calling `schema.node(nodeName, attrs,\n // children)`, where `children` are text nodes that may still carry those\n // disallowed marks. `createChecked` then throws, and y-prosemirror's error\n // handler DELETES the whole block from the Yjs doc — a deletion that propagates\n // to every peer (data loss).\n //\n // Rather than mutating the Yjs doc to strip those marks, we leave them in place\n // (marks are just format attributes; they don't affect position counting, so\n // editing text is unaffected) and simply never materialize the disallowed ones\n // into ProseMirror. We do that by wrapping `schema.node` to filter each text\n // child's marks through the parent node type's `allowedMarks` before the node\n // is built. The wrapper is scoped to plain-content blocks (the only place this\n // migration applies); all other node types pass through untouched.\n //\n // NOTE: this covers marks that EXIST in the schema but aren't allowed on the\n // node. A mark whose type is entirely absent from the schema still hits\n // y-prosemirror's earlier `schema.mark` throw (and delete) path — that's a\n // different migration scenario and is out of scope here.\n // eslint-disable-next-line @typescript-eslint/unbound-method -- intentionally saving reference for monkey-patching\n const originalNode = schema.node;\n schema.node = function (\n this: typeof schema,\n type: string | NodeType,\n attrs?: Attrs | null,\n content?: Fragment | Node | readonly Node[],\n marks?: readonly Mark[],\n ) {\n const nodeType = typeof type === \"string\" ? this.nodes[type] : type;\n // y-prosemirror always passes `content` as a plain array of nodes; only\n // touch text children that carry marks.\n if (\n nodeType &&\n isPlainContentNodeType(this, nodeType) &&\n Array.isArray(content)\n ) {\n content = (content as readonly Node[]).map((child) =>\n child?.isText && child.marks.length\n ? child.mark(nodeType.allowedMarks(child.marks))\n : child,\n );\n }\n return originalNode.call(this, type, attrs, content, marks);\n } as typeof schema.node;\n });\n\n return {\n key: \"fixUpSchema\",\n } as const;\n});\n","import { defaultSelectionBuilder, yCursorPlugin } from \"y-prosemirror\";\nimport {\n createExtension,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport type { CollaborationOptions } from \"./index.js\";\n\nexport type CollaborationUser = {\n id?: string;\n name: string;\n color: string;\n [key: string]: unknown;\n};\n\n/**\n * Determine whether the foreground color should be white or black based on a provided background color\n * Inspired by: https://stackoverflow.com/a/3943023\n */\nfunction isDarkColor(bgColor: string): boolean {\n const color = bgColor.charAt(0) === \"#\" ? bgColor.substring(1, 7) : bgColor;\n const r = parseInt(color.substring(0, 2), 16); // hexToR\n const g = parseInt(color.substring(2, 4), 16); // hexToG\n const b = parseInt(color.substring(4, 6), 16); // hexToB\n const uicolors = [r / 255, g / 255, b / 255];\n const c = uicolors.map((col) => {\n if (col <= 0.03928) {\n return col / 12.92;\n }\n return Math.pow((col + 0.055) / 1.055, 2.4);\n });\n const L = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];\n return L <= 0.179;\n}\n\nfunction defaultCursorRender(user: CollaborationUser) {\n const cursorElement = document.createElement(\"span\");\n\n cursorElement.classList.add(\"bn-collaboration-cursor__base\");\n\n const caretElement = document.createElement(\"span\");\n caretElement.setAttribute(\"contentedEditable\", \"false\");\n caretElement.classList.add(\"bn-collaboration-cursor__caret\");\n caretElement.setAttribute(\n \"style\",\n `background-color: ${user.color}; color: ${\n isDarkColor(user.color) ? \"white\" : \"black\"\n }`,\n );\n\n const labelElement = document.createElement(\"span\");\n\n labelElement.classList.add(\"bn-collaboration-cursor__label\");\n labelElement.setAttribute(\n \"style\",\n `background-color: ${user.color}; color: ${\n isDarkColor(user.color) ? \"white\" : \"black\"\n }`,\n );\n labelElement.insertBefore(document.createTextNode(user.name), null);\n\n caretElement.insertBefore(labelElement, null);\n\n cursorElement.insertBefore(document.createTextNode(\"\\u2060\"), null); // Non-breaking space\n cursorElement.insertBefore(caretElement, null);\n cursorElement.insertBefore(document.createTextNode(\"\\u2060\"), null); // Non-breaking space\n\n return cursorElement;\n}\n\nexport const YCursorExtension = createExtension(\n ({ options }: ExtensionOptions<CollaborationOptions>) => {\n const recentlyUpdatedCursors = new Map();\n const awareness =\n options.provider &&\n \"awareness\" in options.provider &&\n typeof options.provider.awareness === \"object\"\n ? options.provider.awareness\n : undefined;\n if (awareness) {\n if (\n \"setLocalStateField\" in awareness &&\n typeof awareness.setLocalStateField === \"function\"\n ) {\n awareness.setLocalStateField(\"user\", options.user);\n }\n }\n\n const handleAwarenessChange = ({\n updated,\n }: {\n added: Array<number>;\n updated: Array<number>;\n removed: Array<number>;\n }) => {\n for (const clientID of updated) {\n const cursor = recentlyUpdatedCursors.get(clientID);\n\n if (cursor) {\n setTimeout(() => {\n cursor.element.setAttribute(\"data-active\", \"\");\n }, 10);\n\n if (cursor.hideTimeout) {\n clearTimeout(cursor.hideTimeout);\n }\n\n recentlyUpdatedCursors.set(clientID, {\n element: cursor.element,\n hideTimeout: setTimeout(() => {\n cursor.element.removeAttribute(\"data-active\");\n }, 2000),\n });\n }\n }\n };\n\n return {\n key: \"yCursor\",\n mount() {\n if (\n awareness &&\n options.showCursorLabels !== \"always\" &&\n \"on\" in awareness &&\n typeof awareness.on === \"function\"\n ) {\n awareness.on(\"change\", handleAwarenessChange);\n\n return () => {\n if (\"off\" in awareness && typeof awareness.off === \"function\") {\n awareness.off(\"change\", handleAwarenessChange);\n }\n };\n }\n\n return undefined;\n },\n prosemirrorPlugins: [\n awareness\n ? yCursorPlugin(awareness, {\n selectionBuilder: defaultSelectionBuilder,\n cursorBuilder(user: CollaborationUser, clientID: number) {\n let cursorData = recentlyUpdatedCursors.get(clientID);\n\n if (!cursorData) {\n const cursorElement = (\n options.renderCursor ?? defaultCursorRender\n )(user);\n\n if (options.showCursorLabels !== \"always\") {\n cursorElement.addEventListener(\"mouseenter\", () => {\n const cursor = recentlyUpdatedCursors.get(clientID)!;\n cursor.element.setAttribute(\"data-active\", \"\");\n\n if (cursor.hideTimeout) {\n clearTimeout(cursor.hideTimeout);\n recentlyUpdatedCursors.set(clientID, {\n element: cursor.element,\n hideTimeout: undefined,\n });\n }\n });\n\n cursorElement.addEventListener(\"mouseleave\", () => {\n const cursor = recentlyUpdatedCursors.get(clientID)!;\n\n recentlyUpdatedCursors.set(clientID, {\n element: cursor.element,\n hideTimeout: setTimeout(() => {\n cursor.element.removeAttribute(\"data-active\");\n }, 2000),\n });\n });\n }\n\n cursorData = {\n element: cursorElement,\n hideTimeout: undefined,\n };\n\n recentlyUpdatedCursors.set(clientID, cursorData);\n }\n\n return cursorData.element;\n },\n })\n : undefined,\n ].filter(Boolean),\n dependsOn: [\"ySync\"],\n updateUser(user: { name: string; color: string; [key: string]: string }) {\n awareness?.setLocalStateField(\"user\", user);\n },\n getUser(): CollaborationUser | undefined {\n const state = awareness?.getLocalState();\n if (!state) {\n return undefined;\n }\n return state[\"user\"];\n },\n } as const;\n },\n);\n","import { ySyncPlugin } from \"y-prosemirror\";\nimport {\n ExtensionOptions,\n createExtension,\n} from \"../../editor/BlockNoteExtension.js\";\nimport type { CollaborationOptions } from \"./index.js\";\n\nexport const YSyncExtension = createExtension(\n ({ options }: ExtensionOptions<Pick<CollaborationOptions, \"fragment\">>) => {\n return {\n key: \"ySync\",\n prosemirrorPlugins: [ySyncPlugin(options.fragment)],\n runsBefore: [\"default\"],\n } as const;\n },\n);\n","import { redoCommand, undoCommand, yUndoPlugin } from \"y-prosemirror\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\nexport const YUndoExtension = createExtension(() => {\n return {\n key: \"yUndo\",\n prosemirrorPlugins: [yUndoPlugin()],\n dependsOn: [\"yCursor\", \"ySync\"],\n undoCommand: undoCommand,\n redoCommand: redoCommand,\n } as const;\n});\n","import { ySyncPluginKey, yUndoPluginKey } from \"y-prosemirror\";\nimport * as Y from \"yjs\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport {\n createExtension,\n createStore,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport type { CollaborationOptions } from \"./index.js\";\nimport { YCursorExtension } from \"./YCursorPlugin.js\";\nimport { YSyncExtension } from \"./YSync.js\";\nimport { YUndoExtension } from \"./YUndo.js\";\nimport { findTypeInOtherYdoc } from \"../utils.js\";\n\n/**\n * Point the `ySync` plugin state at `fragment`.\n *\n * Swapping the `ySync` plugin reconfigures the ProseMirror state, and\n * ProseMirror carries over the state of plugins that share a key instead of\n * re-initializing them. So the new plugin's `binding` (which is set from its\n * view, via a transaction) ends up on the new fragment, while `type` and `doc`\n * still point at the fragment the editor was bound to before. Anything reading\n * those (e.g. `RelativePositionMappingExtension`) would then mix up the two\n * Y.Docs, so we set them explicitly here.\n */\nfunction bindYSyncPluginStateTo(\n editor: BlockNoteEditor<any, any, any>,\n fragment: Y.XmlFragment,\n) {\n editor.transact((tr) =>\n tr.setMeta(ySyncPluginKey, { type: fragment, doc: fragment.doc }),\n );\n}\n\nexport const ForkYDocExtension = createExtension(\n ({ editor, options }: ExtensionOptions<CollaborationOptions>) => {\n let forkedState:\n | {\n originalFragment: Y.XmlFragment;\n undoStack: Y.UndoManager[\"undoStack\"];\n forkedFragment: Y.XmlFragment;\n }\n | undefined = undefined;\n\n const store = createStore({ isForked: false });\n\n return {\n key: \"yForkDoc\",\n store,\n /**\n * Fork the Y.js document from syncing to the remote,\n * allowing modifications to the document without affecting the remote.\n * These changes can later be rolled back or applied to the remote.\n */\n fork({\n /**\n * The initial update to apply to the forked document.\n * If not provided, the current document state is used.\n */\n initialUpdate,\n }: {\n initialUpdate?: Uint8Array;\n } = {}) {\n if (forkedState) {\n return;\n }\n\n const originalFragment = options.fragment;\n\n if (!originalFragment) {\n throw new Error(\"No fragment to fork from\");\n }\n\n const doc = new Y.Doc();\n // Copy the original document (or apply the provided update) to a new Yjs document\n Y.applyUpdate(\n doc,\n initialUpdate ?? Y.encodeStateAsUpdate(originalFragment.doc!),\n );\n\n // Find the forked fragment in the new Yjs document\n const forkedFragment = findTypeInOtherYdoc(originalFragment, doc);\n\n forkedState = {\n undoStack: yUndoPluginKey.getState(editor.prosemirrorState)!\n .undoManager.undoStack,\n originalFragment,\n forkedFragment,\n };\n\n const newOptions = {\n ...options,\n fragment: forkedFragment,\n };\n\n // Atomically swap the yjs plugins to avoid re-entrant dispatch issues\n // where y-prosemirror's view hooks can dispatch a transaction between\n // separate unregister/register calls, re-introducing stale plugins.\n editor.replaceExtension(\n [\"ySync\", \"yCursor\", \"yUndo\"],\n [\n YSyncExtension(newOptions),\n // No need to register the cursor plugin again, it's a local fork\n YUndoExtension(),\n ],\n );\n\n bindYSyncPluginStateTo(editor, forkedFragment);\n\n // Tell the store that the editor is now forked\n store.setState({ isForked: true });\n },\n\n /**\n * Resume syncing the Y.js document to the remote\n * If `keepChanges` is true, any changes that have been made to the forked document will be applied to the original document.\n * Otherwise, the original document will be restored and the changes will be discarded.\n */\n merge({ keepChanges }: { keepChanges: boolean }) {\n if (!forkedState) {\n return;\n }\n\n const { originalFragment, forkedFragment, undoStack } = forkedState;\n\n // Atomically swap the forked plugins back to the original ones\n editor.replaceExtension(\n [\"ySync\", \"yCursor\", \"yUndo\"],\n [\n YSyncExtension(options),\n YCursorExtension(options),\n YUndoExtension(),\n ],\n );\n\n bindYSyncPluginStateTo(editor, originalFragment);\n\n // Reset the undo stack to the original undo stack\n yUndoPluginKey.getState(\n editor.prosemirrorState,\n )!.undoManager.undoStack = undoStack;\n\n if (keepChanges) {\n // Apply any changes that have been made to the fork, onto the original doc\n const update = Y.encodeStateAsUpdate(\n forkedFragment.doc!,\n Y.encodeStateVector(originalFragment.doc!),\n );\n // Applying this change will add to the undo stack, allowing it to be undone normally\n Y.applyUpdate(originalFragment.doc!, update, editor);\n }\n // Reset the forked state\n forkedState = undefined;\n // Tell the store that the editor is no longer forked\n store.setState({ isForked: false });\n },\n } as const;\n },\n);\n","import {\n absolutePositionToRelativePosition,\n relativePositionToAbsolutePosition,\n ySyncPluginKey,\n} from \"y-prosemirror\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\nimport type { PositionMappingExtension } from \"../../extensions/index.js\";\n\nexport const RelativePositionMappingExtension = createExtension(\n ({ editor }) => {\n return {\n key: \"yPositionMapping\",\n mapPosition: (position: number, side: \"left\" | \"right\" = \"left\") => {\n const ySyncPluginState = ySyncPluginKey.getState(\n editor.prosemirrorState,\n );\n if (!ySyncPluginState) {\n throw new Error(\"YSync plugin state not found\");\n }\n\n // 0 is a special case & always should map to itself\n if (position === 0) {\n return () => 0;\n }\n\n // If the document is empty, it has not been synced yet\n if (ySyncPluginState.binding.type.length === 0) {\n // so, we just fallback to the prosemirror position mapping extension\n // If a remote transaction or sync happens in this case. The position map will be invalidated,\n // and the positions will be moved to the end of the document\n // This is acceptable, because the document had not been synced so there are no positions to map properly into\n const fallback =\n editor.getExtension<typeof PositionMappingExtension>(\n \"positionMapping\",\n );\n if (!fallback) {\n throw new Error(\n \"positionMapping extension is not available; cannot map position before sync\",\n );\n }\n return fallback.mapPosition(position, side);\n }\n\n const relativePosition = absolutePositionToRelativePosition(\n position + (side === \"right\" ? 1 : -1),\n ySyncPluginState.binding.type,\n ySyncPluginState.binding.mapping,\n );\n\n return () => {\n const curYSyncPluginState = ySyncPluginKey.getState(\n editor.prosemirrorState,\n ) as typeof ySyncPluginState;\n // Resolve against the doc that owns the currently bound type, and not\n // against `curYSyncPluginState.doc`. Those can point at different\n // Y.Docs (e.g. right after forking the doc, see `ForkYDocExtension`),\n // in which case the resolved type wouldn't be part of the bound\n // fragment and the position would be reported as \"not found\".\n const boundType = curYSyncPluginState.binding.type;\n const pos = relativePositionToAbsolutePosition(\n boundType.doc,\n boundType,\n relativePosition,\n curYSyncPluginState.binding.mapping,\n );\n\n // This can happen if the element is garbage collected\n if (pos === null) {\n throw new Error(\"Position not found, cannot track positions\");\n }\n\n return pos + (side === \"right\" ? -1 : 1);\n };\n },\n } as const;\n },\n);\n","import * as Y from \"yjs\";\n\nimport { MigrationRule } from \"./migrationRule.js\";\nimport { defaultProps } from \"../../../../blocks/defaultProps.js\";\n\n// Helper function to recursively traverse a `Y.XMLElement` and its descendant\n// elements.\nconst traverseElement = (\n rootElement: Y.XmlElement,\n cb: (element: Y.XmlElement) => void,\n) => {\n cb(rootElement);\n rootElement.forEach((element) => {\n if (element instanceof Y.XmlElement) {\n traverseElement(element, cb);\n }\n });\n};\n\n// Moves `textColor` and `backgroundColor` attributes from `blockContainer`\n// nodes to their child `blockContent` nodes. This is due to a schema change\n// introduced in PR #TODO.\nexport const moveColorAttributes: MigrationRule = (fragment, tr) => {\n // Stores necessary info for all `blockContainer` nodes which still have\n // `textColor` or `backgroundColor` attributes that need to be moved.\n const targetBlockContainers: Map<\n string,\n {\n textColor: string | undefined;\n backgroundColor: string | undefined;\n }\n > = new Map();\n // Finds all elements which still have `textColor` or `backgroundColor`\n // attributes in the current Yjs fragment.\n fragment.forEach((element) => {\n if (element instanceof Y.XmlElement) {\n traverseElement(element, (element) => {\n if (\n element.nodeName === \"blockContainer\" &&\n element.hasAttribute(\"id\")\n ) {\n const textColor = element.getAttribute(\"textColor\");\n const backgroundColor = element.getAttribute(\"backgroundColor\");\n\n const colors = {\n textColor:\n textColor === defaultProps.textColor.default\n ? undefined\n : textColor,\n backgroundColor:\n backgroundColor === defaultProps.backgroundColor.default\n ? undefined\n : backgroundColor,\n };\n\n if (colors.textColor || colors.backgroundColor) {\n targetBlockContainers.set(element.getAttribute(\"id\")!, colors);\n }\n }\n });\n }\n });\n\n if (targetBlockContainers.size === 0) {\n return false;\n }\n\n // Appends transactions to add the `textColor` and `backgroundColor`\n // attributes found on each `blockContainer` node to move them to the child\n // `blockContent` node.\n tr.doc.descendants((node, pos) => {\n if (\n node.type.name === \"blockContainer\" &&\n targetBlockContainers.has(node.attrs.id)\n ) {\n const el = tr.doc.nodeAt(pos + 1);\n if (!el) {\n throw new Error(\"No element found\");\n }\n\n tr.setNodeMarkup(pos + 1, undefined, {\n // preserve existing attributes\n ...el.attrs,\n // add the textColor and backgroundColor attributes\n ...targetBlockContainers.get(node.attrs.id),\n });\n }\n });\n\n return true;\n};\n","import { MigrationRule } from \"./migrationRule.js\";\nimport { moveColorAttributes } from \"./moveColorAttributes.js\";\n\nexport default [moveColorAttributes] as MigrationRule[];\n","import { Plugin, PluginKey } from \"@tiptap/pm/state\";\nimport * as Y from \"yjs\";\n\nimport {\n createExtension,\n ExtensionOptions,\n} from \"../../../editor/BlockNoteExtension.js\";\nimport migrationRules from \"./migrationRules/index.js\";\n\n// This plugin allows us to update collaboration YDocs whenever BlockNote's\n// underlying ProseMirror schema changes. The plugin reads the current Yjs\n// fragment and dispatches additional transactions to the ProseMirror state, in\n// case things are found in the fragment that don't adhere to the editor schema\n// and need to be fixed. These fixes are defined as `MigrationRule`s within the\n// `migrationRules` directory.\nexport const SchemaMigration = createExtension(\n ({ options }: ExtensionOptions<{ fragment: Y.XmlFragment }>) => {\n let migrationDone = false;\n const pluginKey = new PluginKey(\"schemaMigration\");\n\n return {\n key: \"schemaMigration\",\n prosemirrorPlugins: [\n new Plugin({\n key: pluginKey,\n appendTransaction: (transactions, _oldState, newState) => {\n if (migrationDone) {\n return undefined;\n }\n\n if (\n // If any of the transactions are not due to a yjs sync, we don't need to run the migration\n !transactions.some((tr) => tr.getMeta(\"y-sync$\")) ||\n // If none of the transactions result in a document change, we don't need to run the migration\n transactions.every((tr) => !tr.docChanged) ||\n // If the fragment is still empty, we can't run the migration (since it has not yet been applied to the Y.Doc)\n !options.fragment.firstChild\n ) {\n return undefined;\n }\n\n const tr = newState.tr;\n for (const migrationRule of migrationRules) {\n migrationRule(options.fragment, tr);\n }\n\n migrationDone = true;\n\n if (!tr.docChanged) {\n return undefined;\n }\n\n return tr;\n },\n }),\n ],\n } as const;\n },\n);\n","import * as Y from \"yjs\";\n\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport type { PreviewController } from \"../../extensions/Versioning/index.js\";\nimport type { CollaborationOptions } from \"./index.js\";\nimport { ForkYDocExtension } from \"./ForkYDoc.js\";\n\n/**\n * Creates a Yjs v13 adapter that provides the {@link PreviewController}\n * and `getCurrentDocument` callback required by the base\n * {@link VersioningExtension}.\n *\n * Delegates to the {@link ForkYDocExtension} for entering/exiting preview:\n * - **enterPreview**: calls `fork({ initialUpdate: snapshotContent })` to\n * switch the editor to a temporary doc built from the snapshot.\n * - **exitPreview**: calls `merge({ keepChanges: false })` to discard the\n * preview and restore the live document.\n * - **applyRestore**: calls `merge({ keepChanges: true })` to apply the\n * snapshot content back to the live document.\n */\nexport function createYjsVersioningAdapter(\n /** The BlockNote editor instance (must have ForkYDocExtension). */\n editor: BlockNoteEditor<any, any, any>,\n /** The full collaboration options (used for `fragment` access). */\n options: CollaborationOptions,\n): {\n preview: PreviewController<Uint8Array>;\n getCurrentDocument: () => Y.XmlFragment;\n serializeCurrentContent: () => Uint8Array;\n} {\n const { fragment } = options;\n\n function getForkYDoc() {\n const ext = editor.getExtension(ForkYDocExtension);\n if (!ext) {\n throw new Error(\n \"ForkYDocExtension is required for the Yjs versioning adapter. \" +\n \"Make sure it is registered before the VersioningExtension.\",\n );\n }\n return ext;\n }\n\n return {\n getCurrentDocument: () => fragment,\n serializeCurrentContent: () => Y.encodeStateAsUpdateV2(fragment.doc!),\n preview: {\n // Yjs v13 can only fork the document to a single snapshot; it has no way\n // to diff two versions, so comparison is unsupported.\n supportsComparison: false,\n enterPreview(\n snapshotContent: Uint8Array,\n _compareToContent?: Uint8Array,\n ) {\n const forkYDoc = getForkYDoc();\n\n // If already in a preview (forked state), exit first.\n if (forkYDoc.store.state.isForked) {\n forkYDoc.merge({ keepChanges: false });\n }\n\n forkYDoc.fork({ initialUpdate: snapshotContent });\n },\n\n exitPreview() {\n const forkYDoc = getForkYDoc();\n if (forkYDoc.store.state.isForked) {\n forkYDoc.merge({ keepChanges: false });\n }\n },\n\n applyRestore(_snapshotContent: Uint8Array) {\n // Restoring to an older Yjs state cannot be done by merging a fork\n // because the original doc already contains all CRDT state vectors\n // from the snapshot. Restore must be handled at the endpoint/server\n // level (e.g., the server creates a new Y.Doc and syncs it).\n throw new Error(\n \"Restore is not yet implemented for Yjs v13 versioning adapter.\",\n );\n },\n },\n };\n}\n","import type { Awareness } from \"y-protocols/awareness\";\nimport type * as Y from \"yjs\";\nimport type { BlockNoteEditorOptions } from \"../../editor/BlockNoteEditor\";\nimport {\n createExtension,\n type ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport { FixUpSchemaExtension } from \"./FixUpSchema.js\";\nimport { ForkYDocExtension } from \"./ForkYDoc.js\";\nimport { RelativePositionMappingExtension } from \"./RelativePositionMapping.js\";\nimport { SchemaMigration } from \"./schemaMigration/SchemaMigration.js\";\nimport { CollaborationUser, YCursorExtension } from \"./YCursorPlugin.js\";\nimport { YSyncExtension } from \"./YSync.js\";\nimport { YUndoExtension } from \"./YUndo.js\";\n\nexport type CollaborationOptions = {\n /**\n * The Yjs XML fragment that's used for collaboration.\n */\n fragment: Y.XmlFragment;\n /**\n * The user info for the current user that's shown to other collaborators.\n */\n user: CollaborationUser;\n /**\n * A Yjs provider (used for awareness / cursor information)\n */\n provider?: { awareness?: Awareness };\n /**\n * Optional function to customize how cursors of users are rendered\n */\n renderCursor?: (user: CollaborationUser) => HTMLElement;\n /**\n * Optional flag to set when the user label should be shown with the default\n * collaboration cursor. Setting to \"always\" will always show the label,\n * while \"activity\" will only show the label when the user moves the cursor\n * or types. Defaults to \"activity\".\n */\n showCursorLabels?: \"always\" | \"activity\";\n};\n\nexport const CollaborationExtension = createExtension(\n ({ options }: ExtensionOptions<CollaborationOptions>) => {\n return {\n key: \"collaboration\",\n blockNoteExtensions: [\n FixUpSchemaExtension(),\n ForkYDocExtension(options),\n RelativePositionMappingExtension(),\n SchemaMigration(options),\n YCursorExtension(options),\n YSyncExtension(options),\n YUndoExtension(),\n ],\n } as const;\n },\n);\n\nexport function withCollaboration<\n Options extends Partial<BlockNoteEditorOptions<any, any, any>>,\n>(\n options: Options & {\n /**\n * Options for configuring the collaboration functionality.\n */\n collaboration: CollaborationOptions;\n },\n): Options {\n return {\n ...options,\n extensions: [\n ...(options.extensions ?? []),\n CollaborationExtension(options.collaboration),\n ],\n // We disable the default prosemirror history plugin, since it's not compatible with yjs\n disableExtensions: [\"history\", ...(options.disableExtensions ?? [])],\n // We don't want the default initial content, since it will generate a random id for the initial block on each client,\n // leading to conflicts when syncing happens afterwards.\n initialContent: [{ type: \"paragraph\", id: \"initialBlockId\" }],\n };\n}\n\nexport * from \"./ForkYDoc.js\";\nexport * from \"./RelativePositionMapping.js\";\nexport * from \"./schemaMigration/SchemaMigration.js\";\nexport * from \"./Versioning.js\";\nexport * from \"./YCursorPlugin.js\";\nexport * from \"./YSync.js\";\nexport * from \"./YUndo.js\";\n","import * as Y from \"yjs\";\nimport type {\n CommentData,\n CommentReactionData,\n ThreadData,\n} from \"../../comments/types.js\";\n\nexport function commentToYMap(comment: CommentData) {\n const yMap = new Y.Map<any>();\n yMap.set(\"id\", comment.id);\n yMap.set(\"userId\", comment.userId);\n yMap.set(\"createdAt\", comment.createdAt.getTime());\n yMap.set(\"updatedAt\", comment.updatedAt.getTime());\n if (comment.deletedAt) {\n yMap.set(\"deletedAt\", comment.deletedAt.getTime());\n yMap.set(\"body\", undefined);\n } else {\n yMap.set(\"body\", comment.body);\n }\n if (comment.reactions.length > 0) {\n throw new Error(\"Reactions should be empty in commentToYMap\");\n }\n\n /**\n * Reactions are stored in a map keyed by {userId-emoji},\n * this makes it easy to add / remove reactions and in a way that works local-first.\n * The cost is that \"reading\" the reactions is a bit more complex (see yMapToReactions).\n */\n yMap.set(\"reactionsByUser\", new Y.Map());\n yMap.set(\"metadata\", comment.metadata);\n\n return yMap;\n}\n\nexport function threadToYMap(thread: ThreadData) {\n const yMap = new Y.Map();\n yMap.set(\"id\", thread.id);\n yMap.set(\"createdAt\", thread.createdAt.getTime());\n yMap.set(\"updatedAt\", thread.updatedAt.getTime());\n const commentsArray = new Y.Array<Y.Map<any>>();\n\n commentsArray.push(thread.comments.map((comment) => commentToYMap(comment)));\n\n yMap.set(\"comments\", commentsArray);\n yMap.set(\"resolved\", thread.resolved);\n yMap.set(\"resolvedUpdatedAt\", thread.resolvedUpdatedAt?.getTime());\n yMap.set(\"resolvedBy\", thread.resolvedBy);\n yMap.set(\"metadata\", thread.metadata);\n return yMap;\n}\n\ntype SingleUserCommentReactionData = {\n emoji: string;\n createdAt: Date;\n userId: string;\n};\n\nexport function yMapToReaction(\n yMap: Y.Map<any>,\n): SingleUserCommentReactionData {\n return {\n emoji: yMap.get(\"emoji\"),\n createdAt: new Date(yMap.get(\"createdAt\")),\n userId: yMap.get(\"userId\"),\n };\n}\n\nfunction yMapToReactions(yMap: Y.Map<any>): CommentReactionData[] {\n const flatReactions = [...yMap.values()].map((reaction: Y.Map<any>) =>\n yMapToReaction(reaction),\n );\n // combine reactions by the same emoji\n return flatReactions.reduce(\n (acc: CommentReactionData[], reaction: SingleUserCommentReactionData) => {\n const existingReaction = acc.find((r) => r.emoji === reaction.emoji);\n if (existingReaction) {\n existingReaction.userIds.push(reaction.userId);\n existingReaction.createdAt = new Date(\n Math.min(\n existingReaction.createdAt.getTime(),\n reaction.createdAt.getTime(),\n ),\n );\n } else {\n acc.push({\n emoji: reaction.emoji,\n createdAt: reaction.createdAt,\n userIds: [reaction.userId],\n });\n }\n return acc;\n },\n [] as CommentReactionData[],\n );\n}\n\nexport function yMapToComment(yMap: Y.Map<any>): CommentData {\n return {\n type: \"comment\",\n id: yMap.get(\"id\"),\n userId: yMap.get(\"userId\"),\n createdAt: new Date(yMap.get(\"createdAt\")),\n updatedAt: new Date(yMap.get(\"updatedAt\")),\n deletedAt: yMap.get(\"deletedAt\")\n ? new Date(yMap.get(\"deletedAt\"))\n : undefined,\n reactions: yMapToReactions(yMap.get(\"reactionsByUser\")),\n metadata: yMap.get(\"metadata\"),\n body: yMap.get(\"body\"),\n };\n}\n\nexport function yMapToThread(yMap: Y.Map<any>): ThreadData {\n return {\n type: \"thread\",\n id: yMap.get(\"id\"),\n createdAt: new Date(yMap.get(\"createdAt\")),\n updatedAt: new Date(yMap.get(\"updatedAt\")),\n comments: ((yMap.get(\"comments\") as Y.Array<Y.Map<any>>) || []).map(\n (comment) => yMapToComment(comment),\n ),\n resolved: yMap.get(\"resolved\"),\n resolvedUpdatedAt: new Date(yMap.get(\"resolvedUpdatedAt\")),\n resolvedBy: yMap.get(\"resolvedBy\"),\n metadata: yMap.get(\"metadata\"),\n };\n}\n","import * as Y from \"yjs\";\nimport type { ThreadData } from \"../../comments/types.js\";\nimport { ThreadStore } from \"../../comments/threadstore/ThreadStore.js\";\nimport type { ThreadStoreAuth } from \"../../comments/threadstore/ThreadStoreAuth.js\";\nimport { yMapToThread } from \"./yjsHelpers.js\";\n\n/**\n * This is an abstract class that only implements the READ methods required by the ThreadStore interface.\n * The data is read from a Yjs Map.\n */\nexport abstract class YjsThreadStoreBase extends ThreadStore {\n constructor(\n protected readonly threadsYMap: Y.Map<any>,\n auth: ThreadStoreAuth,\n ) {\n super(auth);\n }\n\n // TODO: async / reactive interface?\n public getThread(threadId: string) {\n const yThread = this.threadsYMap.get(threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n const thread = yMapToThread(yThread);\n return thread;\n }\n\n public getThreads(): Map<string, ThreadData> {\n const threadMap = new Map<string, ThreadData>();\n this.threadsYMap.forEach((yThread, id) => {\n if (yThread instanceof Y.Map) {\n threadMap.set(id, yMapToThread(yThread));\n }\n });\n return threadMap;\n }\n\n public subscribe(cb: (threads: Map<string, ThreadData>) => void) {\n const observer = () => {\n cb(this.getThreads());\n };\n\n this.threadsYMap.observeDeep(observer);\n\n return () => {\n this.threadsYMap.unobserveDeep(observer);\n };\n }\n}\n","import * as Y from \"yjs\";\nimport {\n absolutePositionToRelativePosition,\n ySyncPluginKey,\n} from \"y-prosemirror\";\nimport type { CommentBody } from \"../../comments/types.js\";\nimport type { ThreadStoreAuth } from \"../../comments/threadstore/ThreadStoreAuth.js\";\nimport { YjsThreadStoreBase } from \"./YjsThreadStoreBase.js\";\nimport { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\n\n/**\n * This is a REST-based implementation of the YjsThreadStoreBase.\n * It Reads data directly from the underlying document (same as YjsThreadStore),\n * but for Writes, it sends data to a REST API that should:\n * - check the user has the correct permissions to make the desired changes\n * - apply the updates to the underlying Yjs document\n *\n * (see https://github.com/TypeCellOS/BlockNote-demo-nextjs-hocuspocus)\n *\n * The reason we still use the Yjs document as underlying storage is that it makes it easy to\n * sync updates in real-time to other collaborators.\n * (but technically, you could also implement a different storage altogether\n * and not store the thread related data in the Yjs document)\n */\nexport class RESTYjsThreadStore extends YjsThreadStoreBase {\n constructor(\n private readonly BASE_URL: string,\n private readonly headers: Record<string, string>,\n threadsYMap: Y.Map<any>,\n auth: ThreadStoreAuth,\n ) {\n super(threadsYMap, auth);\n }\n\n private doRequest = async (path: string, method: string, body?: any) => {\n const response = await fetch(`${this.BASE_URL}${path}`, {\n method,\n body: JSON.stringify(body),\n headers: {\n \"Content-Type\": \"application/json\",\n ...this.headers,\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to ${method} ${path}: ${response.statusText}`);\n }\n\n return response.json();\n };\n\n public addThreadToDocument = async (options: {\n threadId: string;\n selection: {\n head: number;\n anchor: number;\n };\n editor: BlockNoteEditor<any, any, any>;\n }) => {\n const { threadId, selection } = options;\n\n // Note: the positions have to be resolved against the *binding's* type and\n // mapping. The plugin state has a `type` of its own, but no `mapping`, and\n // its `type` can go stale (e.g. while the doc is forked, see\n // `ForkYDocExtension`).\n const binding = ySyncPluginKey.getState(\n options.editor.prosemirrorState,\n )?.binding;\n const yjsSelection = binding\n ? {\n head: absolutePositionToRelativePosition(\n selection.head,\n binding.type,\n binding.mapping,\n ),\n anchor: absolutePositionToRelativePosition(\n selection.anchor,\n binding.type,\n binding.mapping,\n ),\n }\n : undefined;\n\n return this.doRequest(`/${threadId}/addToDocument`, \"POST\", {\n selection: {\n prosemirror: selection,\n yjs: yjsSelection,\n },\n });\n };\n\n public createThread = async (options: {\n initialComment: {\n body: CommentBody;\n metadata?: any;\n };\n metadata?: any;\n }) => {\n return this.doRequest(\"\", \"POST\", options);\n };\n\n public addComment = (options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n }) => {\n const { threadId, ...rest } = options;\n return this.doRequest(`/${threadId}/comments`, \"POST\", rest);\n };\n\n public updateComment = (options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n commentId: string;\n }) => {\n const { threadId, commentId, ...rest } = options;\n return this.doRequest(`/${threadId}/comments/${commentId}`, \"PUT\", rest);\n };\n\n public deleteComment = (options: {\n threadId: string;\n commentId: string;\n softDelete?: boolean;\n }) => {\n const { threadId, commentId, ...rest } = options;\n return this.doRequest(\n `/${threadId}/comments/${commentId}?soft=${!!rest.softDelete}`,\n \"DELETE\",\n );\n };\n\n public deleteThread = (options: { threadId: string }) => {\n return this.doRequest(`/${options.threadId}`, \"DELETE\");\n };\n\n public resolveThread = (options: { threadId: string }) => {\n return this.doRequest(`/${options.threadId}/resolve`, \"POST\");\n };\n\n public unresolveThread = (options: { threadId: string }) => {\n return this.doRequest(`/${options.threadId}/unresolve`, \"POST\");\n };\n\n public addReaction = (options: {\n threadId: string;\n commentId: string;\n emoji: string;\n }) => {\n const { threadId, commentId, ...rest } = options;\n return this.doRequest(\n `/${threadId}/comments/${commentId}/reactions`,\n \"POST\",\n rest,\n );\n };\n\n public deleteReaction = (options: {\n threadId: string;\n commentId: string;\n emoji: string;\n }) => {\n return this.doRequest(\n `/${options.threadId}/comments/${options.commentId}/reactions/${options.emoji}`,\n \"DELETE\",\n );\n };\n}\n","import * as Y from \"yjs\";\nimport { uuidv4 } from \"lib0/random\";\nimport type {\n CommentBody,\n CommentData,\n ThreadData,\n} from \"../../comments/types.js\";\nimport type { ThreadStoreAuth } from \"../../comments/threadstore/ThreadStoreAuth.js\";\nimport { YjsThreadStoreBase } from \"./YjsThreadStoreBase.js\";\nimport {\n commentToYMap,\n threadToYMap,\n yMapToComment,\n yMapToThread,\n} from \"./yjsHelpers.js\";\n\n/**\n * This is a Yjs-based implementation of the ThreadStore interface.\n *\n * It reads and writes thread / comments information directly to the underlying Yjs Document.\n *\n * @important While this is the easiest to add to your app, there are two challenges:\n * - The user needs to be able to write to the Yjs document to store the information.\n * So a user without write access to the Yjs document cannot leave any comments.\n * - Even with write access, the operations are not secure. Unless your Yjs server\n * guards against malicious operations, it's technically possible for one user to make changes to another user's comments, etc.\n * (even though these options are not visible in the UI, a malicious user can make unauthorized changes to the underlying Yjs document)\n */\nexport class YjsThreadStore extends YjsThreadStoreBase {\n constructor(\n private readonly userId: string,\n threadsYMap: Y.Map<any>,\n auth: ThreadStoreAuth,\n ) {\n super(threadsYMap, auth);\n }\n\n private transact = <T, R>(\n fn: (options: T) => R,\n ): ((options: T) => Promise<R>) => {\n return async (options: T) => {\n return this.threadsYMap.doc!.transact(() => {\n return fn(options);\n });\n };\n };\n\n public createThread = this.transact(\n (options: {\n initialComment: {\n body: CommentBody;\n metadata?: any;\n };\n metadata?: any;\n }) => {\n if (!this.auth.canCreateThread()) {\n throw new Error(\"Not authorized\");\n }\n\n const date = new Date();\n\n const comment: CommentData = {\n type: \"comment\",\n id: uuidv4(),\n userId: this.userId,\n createdAt: date,\n updatedAt: date,\n reactions: [],\n metadata: options.initialComment.metadata,\n body: options.initialComment.body,\n };\n\n const thread: ThreadData = {\n type: \"thread\",\n id: uuidv4(),\n createdAt: date,\n updatedAt: date,\n comments: [comment],\n resolved: false,\n metadata: options.metadata,\n };\n\n this.threadsYMap.set(thread.id, threadToYMap(thread));\n\n return thread;\n },\n );\n\n // YjsThreadStore does not support addThreadToDocument\n public addThreadToDocument = undefined;\n\n public addComment = this.transact(\n (options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canAddComment(yMapToThread(yThread))) {\n throw new Error(\"Not authorized\");\n }\n\n const date = new Date();\n const comment: CommentData = {\n type: \"comment\",\n id: uuidv4(),\n userId: this.userId,\n createdAt: date,\n updatedAt: date,\n deletedAt: undefined,\n reactions: [],\n metadata: options.comment.metadata,\n body: options.comment.body,\n };\n\n (yThread.get(\"comments\") as Y.Array<Y.Map<any>>).push([\n commentToYMap(comment),\n ]);\n\n yThread.set(\"updatedAt\", new Date().getTime());\n return comment;\n },\n );\n\n public updateComment = this.transact(\n (options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n commentId: string;\n }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const yCommentIndex = yArrayFindIndex(\n yThread.get(\"comments\"),\n (comment) => comment.get(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = yThread.get(\"comments\").get(yCommentIndex);\n\n if (!this.auth.canUpdateComment(yMapToComment(yComment))) {\n throw new Error(\"Not authorized\");\n }\n\n yComment.set(\"body\", options.comment.body);\n yComment.set(\"updatedAt\", new Date().getTime());\n yComment.set(\"metadata\", options.comment.metadata);\n },\n );\n\n public deleteComment = this.transact(\n (options: {\n threadId: string;\n commentId: string;\n softDelete?: boolean;\n }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const yCommentIndex = yArrayFindIndex(\n yThread.get(\"comments\"),\n (comment) => comment.get(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = yThread.get(\"comments\").get(yCommentIndex);\n\n if (!this.auth.canDeleteComment(yMapToComment(yComment))) {\n throw new Error(\"Not authorized\");\n }\n\n if (yComment.get(\"deletedAt\")) {\n throw new Error(\"Comment already deleted\");\n }\n\n if (options.softDelete) {\n yComment.set(\"deletedAt\", new Date().getTime());\n yComment.set(\"body\", undefined);\n } else {\n yThread.get(\"comments\").delete(yCommentIndex);\n }\n\n if (\n (yThread.get(\"comments\") as Y.Array<any>)\n .toArray()\n .every((comment) => comment.get(\"deletedAt\"))\n ) {\n // all comments deleted\n if (options.softDelete) {\n yThread.set(\"deletedAt\", new Date().getTime());\n } else {\n this.threadsYMap.delete(options.threadId);\n }\n }\n\n yThread.set(\"updatedAt\", new Date().getTime());\n },\n );\n\n public deleteThread = this.transact((options: { threadId: string }) => {\n if (\n !this.auth.canDeleteThread(\n yMapToThread(this.threadsYMap.get(options.threadId)),\n )\n ) {\n throw new Error(\"Not authorized\");\n }\n\n this.threadsYMap.delete(options.threadId);\n });\n\n public resolveThread = this.transact((options: { threadId: string }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canResolveThread(yMapToThread(yThread))) {\n throw new Error(\"Not authorized\");\n }\n\n yThread.set(\"resolved\", true);\n yThread.set(\"resolvedUpdatedAt\", new Date().getTime());\n yThread.set(\"resolvedBy\", this.userId);\n });\n\n public unresolveThread = this.transact((options: { threadId: string }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canUnresolveThread(yMapToThread(yThread))) {\n throw new Error(\"Not authorized\");\n }\n\n yThread.set(\"resolved\", false);\n yThread.set(\"resolvedUpdatedAt\", new Date().getTime());\n });\n\n public addReaction = this.transact(\n (options: { threadId: string; commentId: string; emoji: string }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const yCommentIndex = yArrayFindIndex(\n yThread.get(\"comments\"),\n (comment) => comment.get(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = yThread.get(\"comments\").get(yCommentIndex);\n\n if (!this.auth.canAddReaction(yMapToComment(yComment), options.emoji)) {\n throw new Error(\"Not authorized\");\n }\n\n const date = new Date();\n\n const key = `${this.userId}-${options.emoji}`;\n\n const reactionsByUser = yComment.get(\"reactionsByUser\");\n\n if (reactionsByUser.has(key)) {\n // already exists\n return;\n } else {\n const reaction = new Y.Map();\n reaction.set(\"emoji\", options.emoji);\n reaction.set(\"createdAt\", date.getTime());\n reaction.set(\"userId\", this.userId);\n reactionsByUser.set(key, reaction);\n }\n },\n );\n\n public deleteReaction = this.transact(\n (options: { threadId: string; commentId: string; emoji: string }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const yCommentIndex = yArrayFindIndex(\n yThread.get(\"comments\"),\n (comment) => comment.get(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = yThread.get(\"comments\").get(yCommentIndex);\n\n if (\n !this.auth.canDeleteReaction(yMapToComment(yComment), options.emoji)\n ) {\n throw new Error(\"Not authorized\");\n }\n\n const key = `${this.userId}-${options.emoji}`;\n\n const reactionsByUser = yComment.get(\"reactionsByUser\");\n\n reactionsByUser.delete(key);\n },\n );\n}\n\nfunction yArrayFindIndex(\n yArray: Y.Array<any>,\n predicate: (item: any) => boolean,\n) {\n for (let i = 0; i < yArray.length; i++) {\n if (predicate(yArray.get(i))) {\n return i;\n }\n }\n return -1;\n}\n"],"mappings":";;;;;;;;;AAsBA,SAAgB,EACd,GACA,GACG;CACH,IAAM,IAAO,EAAM;CACnB,IAAI,CAAC,GACH,MAAU,MAAM,2BAA2B;CAE7C,IAAI,EAAM,UAAU,MAAM;EACxB,IAAM,IAAU,MAAM,KAAK,EAAK,MAAM,KAAK,CAAC,CAAC,CAAC,MAC3C,MAAQ,EAAK,MAAM,IAAI,CAAG,MAAM,CACnC;EACA,IAAI,KAAW,MACb,MAAU,MAAM,mCAAmC;EAErD,OAAO,EAAU,IAAI,GAAS,EAAM,WAA0B;CAChE;CAAO;EACL,IAAM,IAAY,EAAM,OAClB,IAAe,EAAU,MAAM,QAAQ,IAAI,EAAU,GAAG,MAAM,KAAK,CAAC,GAEpE,IAAY,EADA,EAAE,YAA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GlC,IAAM,oBAAO,IAAI,KAAK,GAEhB,IAAM,GAAG,KAAK,OAAO,GAAG,EAAQ,SAEhC,IAAkB,EAAS,IAAI,iBAAiB;EAElD,OAAgB,IAAI,CAAG,GAGpB;GACL,IAAM,IAAW,IAAI,EAAE,IAAI;GAI3B,AAHA,EAAS,IAAI,SAAS,EAAQ,KAAK,GACnC,EAAS,IAAI,aAAa,EAAK,QAAQ,CAAC,GACxC,EAAS,IAAI,UAAU,KAAK,MAAM,GAClC,EAAgB,IAAI,GAAK,CAAQ;EACnC;CACF,CACF;CAEA,iBAAwB,KAAK,UAC1B,MAAoE;EACnE,IAAM,IAAU,KAAK,YAAY,IAAI,EAAQ,QAAQ;EACrD,IAAI,CAAC,GACH,MAAU,MAAM,kBAAkB;EAGpC,IAAM,IAAgB,EACpB,EAAQ,IAAI,UAAU,IACrB,MAAY,EAAQ,IAAI,IAAI,MAAM,EAAQ,SAC7C;EAEA,IAAI,MAAkB,IACpB,MAAU,MAAM,mBAAmB;EAGrC,IAAM,IAAW,EAAQ,IAAI,UAAU,CAAC,CAAC,IAAI,CAAa;EAE1D,IACE,CAAC,KAAK,KAAK,kBAAkB,EAAc,CAAQ,GAAG,EAAQ,KAAK,GAEnE,MAAU,MAAM,gBAAgB;EAGlC,IAAM,IAAM,GAAG,KAAK,OAAO,GAAG,EAAQ;EAItC,EAFiC,IAAI,iBAErC,CAAA,CAAgB,OAAO,CAAG;CAC5B,CACF;AACF;AAEA,SAAS,EACP,GACA,GACA;CACA,KAAK,IAAI,IAAI,GAAG,IAAI,EAAO,QAAQ,KACjC,IAAI,EAAU,EAAO,IAAI,CAAC,CAAC,GACzB,OAAO;CAGX,OAAO;AACT"}
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "directory": "packages/core"
12
12
  },
13
13
  "license": "MPL-2.0",
14
- "version": "0.53.0",
14
+ "version": "0.54.1",
15
15
  "files": [
16
16
  "dist",
17
17
  "types",
@@ -86,8 +86,7 @@
86
86
  "dependencies": {
87
87
  "@emoji-mart/data": "^1.2.1",
88
88
  "@handlewithcare/prosemirror-inputrules": "^0.1.4",
89
- "@shikijs/types": "^4",
90
- "@tanstack/store": "^0.7.7",
89
+ "@shikijs/types": "^4.4.3",
91
90
  "@tiptap/core": "^3.29.2",
92
91
  "@tiptap/extension-bold": "^3.29.2",
93
92
  "@tiptap/extension-code": "^3.29.2",
@@ -100,48 +99,48 @@
100
99
  "emoji-mart": "^5.6.0",
101
100
  "fast-deep-equal": "^3.1.3",
102
101
  "lib0": "1.0.0-rc.22",
103
- "prosemirror-highlight": "^0.15.1",
102
+ "prosemirror-highlight": "^0.15.3",
104
103
  "prosemirror-model": "^1.25.11",
105
104
  "prosemirror-state": "^1.4.4",
106
105
  "prosemirror-tables": "^1.8.5",
107
106
  "prosemirror-transform": "^1.12.0",
108
- "prosemirror-view": "^1.41.9"
107
+ "prosemirror-view": "^1.42.2"
109
108
  },
110
109
  "devDependencies": {
111
110
  "jsdom": "^29.0.2",
112
111
  "rimraf": "^5.0.10",
113
112
  "rollup-plugin-webpack-stats": "^0.2.6",
114
- "typescript": "^5.9.3",
115
- "vite-plus": "^0.1.24",
113
+ "typescript": "^7.0.2",
114
+ "vite-plus": "^0.2.9",
116
115
  "y-prosemirror": "^1.3.7",
117
116
  "y-protocols": "^1.0.6",
118
117
  "yjs": "^13.6.27"
119
118
  },
120
119
  "peerDependencies": {
120
+ "@y/prosemirror": "^2.0.0-6",
121
+ "@y/protocols": "^1.0.6-rc.1",
122
+ "@y/y": "^14.0.0-rc.23",
121
123
  "y-prosemirror": "^1.3.7",
122
124
  "y-protocols": "^1.0.6",
123
- "yjs": "^13.6.27",
124
- "@y/y": "^14.0.0-rc.23",
125
- "@y/prosemirror": "^2.0.0-6",
126
- "@y/protocols": "^1.0.6-rc.1"
125
+ "yjs": "^13.6.27"
127
126
  },
128
127
  "peerDependenciesMeta": {
129
- "y-prosemirror": {
128
+ "@y/y": {
130
129
  "optional": true
131
130
  },
132
- "y-protocols": {
131
+ "@y/prosemirror": {
133
132
  "optional": true
134
133
  },
135
- "yjs": {
134
+ "@y/protocols": {
136
135
  "optional": true
137
136
  },
138
- "@y/y": {
137
+ "y-prosemirror": {
139
138
  "optional": true
140
139
  },
141
- "@y/prosemirror": {
140
+ "y-protocols": {
142
141
  "optional": true
143
142
  },
144
- "@y/protocols": {
143
+ "yjs": {
145
144
  "optional": true
146
145
  }
147
146
  },
@@ -153,7 +152,7 @@
153
152
  "gitHead": "37614ab348dcc7faa830a9a88437b37197a2162d",
154
153
  "scripts": {
155
154
  "dev": "vp dev",
156
- "build-bundled": "tsgo && vp build --config vite.config.bundled.ts && git checkout tmp-releases && rm -rf ../../release && mv ../../release-tmp ../../release",
155
+ "build-bundled": "tsc && vp build --config vite.config.bundled.ts && git checkout tmp-releases && rm -rf ../../release && mv ../../release-tmp ../../release",
157
156
  "preview": "vp preview",
158
157
  "lint": "vp lint src",
159
158
  "test": "vp test --run",