@kritzel/engine 0.4.31

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 (373) hide show
  1. package/LICENSE.md +50 -0
  2. package/dist/cjs/app-globals-V2Kpy_OQ.js +5 -0
  3. package/dist/cjs/engine.constants-CakmdKMW.js +28206 -0
  4. package/dist/cjs/index-BbbWU2aN.js +1742 -0
  5. package/dist/cjs/index.cjs.js +4232 -0
  6. package/dist/cjs/kritzel-awareness-cursors_5.cjs.entry.js +28004 -0
  7. package/dist/cjs/loader.cjs.js +13 -0
  8. package/dist/cjs/stencil.cjs.js +25 -0
  9. package/dist/collection/classes/core/core.class.js +1389 -0
  10. package/dist/collection/classes/core/reviver.class.js +124 -0
  11. package/dist/collection/classes/core/store.class.js +337 -0
  12. package/dist/collection/classes/core/viewport.class.js +794 -0
  13. package/dist/collection/classes/core/workspace.class.js +112 -0
  14. package/dist/collection/classes/handlers/base.handler.js +20 -0
  15. package/dist/collection/classes/handlers/context-menu.handler.js +170 -0
  16. package/dist/collection/classes/handlers/hover.handler.js +35 -0
  17. package/dist/collection/classes/handlers/key.handler.js +162 -0
  18. package/dist/collection/classes/handlers/line-handle.handler.js +475 -0
  19. package/dist/collection/classes/handlers/move.handler.js +295 -0
  20. package/dist/collection/classes/handlers/resize.handler.js +327 -0
  21. package/dist/collection/classes/handlers/rotation.handler.js +174 -0
  22. package/dist/collection/classes/handlers/selection.handler.js +526 -0
  23. package/dist/collection/classes/managers/anchor.manager.js +1476 -0
  24. package/dist/collection/classes/managers/browser-permission.manager.js +64 -0
  25. package/dist/collection/classes/managers/clipboard.manager.js +346 -0
  26. package/dist/collection/classes/managers/clipboard.types.js +1 -0
  27. package/dist/collection/classes/managers/cursor.manager.js +139 -0
  28. package/dist/collection/classes/managers/license.manager.js +341 -0
  29. package/dist/collection/classes/managers/localization.manager.js +227 -0
  30. package/dist/collection/classes/managers/theme.manager.js +206 -0
  31. package/dist/collection/classes/objects/base-object.class.js +462 -0
  32. package/dist/collection/classes/objects/dynamic-object.class.js +437 -0
  33. package/dist/collection/classes/objects/group.class.js +590 -0
  34. package/dist/collection/classes/objects/image.class.js +500 -0
  35. package/dist/collection/classes/objects/line.class.js +789 -0
  36. package/dist/collection/classes/objects/path.class.js +578 -0
  37. package/dist/collection/classes/objects/selection-box.class.js +32 -0
  38. package/dist/collection/classes/objects/selection-group.class.js +752 -0
  39. package/dist/collection/classes/objects/shape.class.js +628 -0
  40. package/dist/collection/classes/objects/text.class.js +461 -0
  41. package/dist/collection/classes/providers/assets/asset-resolver.class.js +536 -0
  42. package/dist/collection/classes/providers/assets/http-asset-provider.class.js +111 -0
  43. package/dist/collection/classes/providers/assets/indexeddb-asset-provider.class.js +241 -0
  44. package/dist/collection/classes/providers/assets/presigned-asset-provider.class.js +86 -0
  45. package/dist/collection/classes/providers/paste-intent/event-paste-intent.provider.js +48 -0
  46. package/dist/collection/classes/providers/paste-intent/ios-paste-intent.provider.js +16 -0
  47. package/dist/collection/classes/providers/paste-intent/navigator-paste-intent.provider.js +86 -0
  48. package/dist/collection/classes/providers/sync/broadcast-sync-provider.class.js +100 -0
  49. package/dist/collection/classes/providers/sync/hocuspocus-sync-provider.class.js +333 -0
  50. package/dist/collection/classes/providers/sync/in-memory-sync-provider.class.js +69 -0
  51. package/dist/collection/classes/providers/sync/indexeddb-sync-provider.class.js +39 -0
  52. package/dist/collection/classes/providers/sync/websocket-sync-provider.class.js +110 -0
  53. package/dist/collection/classes/registries/dynamic-object-renderer.registry.js +52 -0
  54. package/dist/collection/classes/registries/font-registry.class.js +161 -0
  55. package/dist/collection/classes/registries/icon-registry.class.js +118 -0
  56. package/dist/collection/classes/registries/paste-intent-provider.registry.js +26 -0
  57. package/dist/collection/classes/registries/tool.registry.js +69 -0
  58. package/dist/collection/classes/structures/app-state-map.structure.js +461 -0
  59. package/dist/collection/classes/structures/object-map.structure.js +1103 -0
  60. package/dist/collection/classes/structures/quadtree.structure.js +251 -0
  61. package/dist/collection/classes/tools/base-tool.class.js +88 -0
  62. package/dist/collection/classes/tools/brush-tool.class.js +236 -0
  63. package/dist/collection/classes/tools/eraser-tool.class.js +133 -0
  64. package/dist/collection/classes/tools/image-tool.class.js +152 -0
  65. package/dist/collection/classes/tools/line-tool.class.js +249 -0
  66. package/dist/collection/classes/tools/selection-tool.class.js +611 -0
  67. package/dist/collection/classes/tools/shape-tool.class.js +251 -0
  68. package/dist/collection/classes/tools/text-tool.class.js +179 -0
  69. package/dist/collection/collection-manifest.json +17 -0
  70. package/dist/collection/components/kritzel-awareness-cursors/kritzel-awareness-cursors.css +115 -0
  71. package/dist/collection/components/kritzel-awareness-cursors/kritzel-awareness-cursors.js +380 -0
  72. package/dist/collection/components/kritzel-cursor-trail/kritzel-cursor-trail.css +10 -0
  73. package/dist/collection/components/kritzel-cursor-trail/kritzel-cursor-trail.js +153 -0
  74. package/dist/collection/components/kritzel-engine/kritzel-engine.css +81 -0
  75. package/dist/collection/components/kritzel-engine/kritzel-engine.js +6345 -0
  76. package/dist/collection/components/kritzel-icon/kritzel-icon.css +18 -0
  77. package/dist/collection/components/kritzel-icon/kritzel-icon.js +93 -0
  78. package/dist/collection/components/kritzel-watermark/kritzel-watermark.css +29 -0
  79. package/dist/collection/components/kritzel-watermark/kritzel-watermark.js +83 -0
  80. package/dist/collection/configs/default-asset-storage.config.js +9 -0
  81. package/dist/collection/configs/default-brush-tool.config.js +9 -0
  82. package/dist/collection/configs/default-engine-config.js +73 -0
  83. package/dist/collection/configs/default-line-tool.config.js +12 -0
  84. package/dist/collection/configs/default-shape-tool.config.js +15 -0
  85. package/dist/collection/configs/default-sync.config.js +6 -0
  86. package/dist/collection/configs/default-text-tool.config.js +12 -0
  87. package/dist/collection/constants/color-palette.constants.js +40 -0
  88. package/dist/collection/constants/core.constants.js +1 -0
  89. package/dist/collection/constants/engine.constants.js +4 -0
  90. package/dist/collection/constants/license.constants.js +25 -0
  91. package/dist/collection/constants/schema.constants.js +4 -0
  92. package/dist/collection/constants/storage.constants.js +1 -0
  93. package/dist/collection/constants/stroke-size.constants.js +2 -0
  94. package/dist/collection/constants/text-tool-fonts.constants.js +18 -0
  95. package/dist/collection/constants/version.js +6 -0
  96. package/dist/collection/enums/alignment.enum.js +9 -0
  97. package/dist/collection/enums/event-button.enum.js +6 -0
  98. package/dist/collection/enums/handle-type.enum.js +7 -0
  99. package/dist/collection/enums/shape-type.enum.js +6 -0
  100. package/dist/collection/events/active-workspace-change.event.js +1 -0
  101. package/dist/collection/events/editor-is-ready.event.js +1 -0
  102. package/dist/collection/events/login.event.js +1 -0
  103. package/dist/collection/helpers/alignment.helper.js +73 -0
  104. package/dist/collection/helpers/class.helper.js +5 -0
  105. package/dist/collection/helpers/color.helper.js +106 -0
  106. package/dist/collection/helpers/cursor.helper.js +57 -0
  107. package/dist/collection/helpers/devices.helper.js +28 -0
  108. package/dist/collection/helpers/event.helper.js +58 -0
  109. package/dist/collection/helpers/geometry.helper.js +149 -0
  110. package/dist/collection/helpers/html.helper.js +116 -0
  111. package/dist/collection/helpers/image-file.helper.js +6 -0
  112. package/dist/collection/helpers/keyboard.helper.js +55 -0
  113. package/dist/collection/helpers/localization.helper.js +25 -0
  114. package/dist/collection/helpers/math.helper.js +8 -0
  115. package/dist/collection/helpers/migration.helper.js +45 -0
  116. package/dist/collection/helpers/object.helper.js +29 -0
  117. package/dist/collection/helpers/svg-export.helper.js +655 -0
  118. package/dist/collection/helpers/theme.helper.js +77 -0
  119. package/dist/collection/helpers/tool-config.helper.js +63 -0
  120. package/dist/collection/helpers/wheel.helper.js +113 -0
  121. package/dist/collection/index.js +107 -0
  122. package/dist/collection/interfaces/anchor.interface.js +1 -0
  123. package/dist/collection/interfaces/arrow-head.interface.js +1 -0
  124. package/dist/collection/interfaces/asset-provider.interface.js +1 -0
  125. package/dist/collection/interfaces/asset-storage-config.interface.js +1 -0
  126. package/dist/collection/interfaces/asset.interface.js +1 -0
  127. package/dist/collection/interfaces/bounding-box.interface.js +1 -0
  128. package/dist/collection/interfaces/clonable.interface.js +1 -0
  129. package/dist/collection/interfaces/context-menu-item.interface.js +1 -0
  130. package/dist/collection/interfaces/context-menu-state.interface.js +1 -0
  131. package/dist/collection/interfaces/debug-info.interface.js +1 -0
  132. package/dist/collection/interfaces/dialog.interface.js +1 -0
  133. package/dist/collection/interfaces/document-metadata.interface.js +1 -0
  134. package/dist/collection/interfaces/dynamic-object-renderer.interface.js +1 -0
  135. package/dist/collection/interfaces/engine-state.interface.js +1 -0
  136. package/dist/collection/interfaces/font.interface.js +1 -0
  137. package/dist/collection/interfaces/localization.interface.js +1 -0
  138. package/dist/collection/interfaces/login-config.interface.js +1 -0
  139. package/dist/collection/interfaces/master-detail.interface.js +1 -0
  140. package/dist/collection/interfaces/menu-item.interface.js +1 -0
  141. package/dist/collection/interfaces/migration.interface.js +1 -0
  142. package/dist/collection/interfaces/notification.interface.js +1 -0
  143. package/dist/collection/interfaces/object-change-event.interface.js +1 -0
  144. package/dist/collection/interfaces/object-export.interface.js +1 -0
  145. package/dist/collection/interfaces/object.interface.js +1 -0
  146. package/dist/collection/interfaces/paste-intent-provider.interface.js +1 -0
  147. package/dist/collection/interfaces/point.interface.js +1 -0
  148. package/dist/collection/interfaces/polygon.interface.js +1 -0
  149. package/dist/collection/interfaces/remote-cursor.interface.js +1 -0
  150. package/dist/collection/interfaces/selection-state.interface.js +1 -0
  151. package/dist/collection/interfaces/serializable.interface.js +1 -0
  152. package/dist/collection/interfaces/settings.interface.js +1 -0
  153. package/dist/collection/interfaces/share.interface.js +1 -0
  154. package/dist/collection/interfaces/shortcut.interface.js +1 -0
  155. package/dist/collection/interfaces/sync-config.interface.js +21 -0
  156. package/dist/collection/interfaces/sync-provider.interface.js +1 -0
  157. package/dist/collection/interfaces/theme.interface.js +1 -0
  158. package/dist/collection/interfaces/tool-config.interface.js +1 -0
  159. package/dist/collection/interfaces/tool-type.interface.js +1 -0
  160. package/dist/collection/interfaces/tool.interface.js +1 -0
  161. package/dist/collection/interfaces/toolbar-item.interface.js +1 -0
  162. package/dist/collection/interfaces/undo-state.interface.js +1 -0
  163. package/dist/collection/interfaces/user.interface.js +1 -0
  164. package/dist/collection/interfaces/viewport-state.interface.js +1 -0
  165. package/dist/collection/locales/de-locale.js +119 -0
  166. package/dist/collection/locales/en-locale.js +120 -0
  167. package/dist/collection/locales/fr-locale.js +119 -0
  168. package/dist/collection/migrations/app-state.migrations.js +47 -0
  169. package/dist/collection/migrations/workspace.migrations.js +67 -0
  170. package/dist/collection/themes/dark-theme.js +340 -0
  171. package/dist/collection/themes/light-theme.js +346 -0
  172. package/dist/collection/types/deep-readonly.type.js +1 -0
  173. package/dist/collection/types/state.types.js +1 -0
  174. package/dist/components/index.d.ts +47 -0
  175. package/dist/components/index.js +4143 -0
  176. package/dist/components/kritzel-awareness-cursors.d.ts +11 -0
  177. package/dist/components/kritzel-awareness-cursors.js +6 -0
  178. package/dist/components/kritzel-cursor-trail.d.ts +11 -0
  179. package/dist/components/kritzel-cursor-trail.js +6 -0
  180. package/dist/components/kritzel-engine.d.ts +11 -0
  181. package/dist/components/kritzel-engine.js +52641 -0
  182. package/dist/components/kritzel-icon.d.ts +11 -0
  183. package/dist/components/kritzel-icon.js +6 -0
  184. package/dist/components/kritzel-watermark.d.ts +11 -0
  185. package/dist/components/kritzel-watermark.js +6 -0
  186. package/dist/components/p-B2Htv9ou.js +49 -0
  187. package/dist/components/p-BvRGQvVI.js +3456 -0
  188. package/dist/components/p-CfSx6HU_.js +1469 -0
  189. package/dist/components/p-YP8wAcF4.js +122 -0
  190. package/dist/components/p-fx6msYHJ.js +167 -0
  191. package/dist/esm/app-globals-DQuL1Twl.js +3 -0
  192. package/dist/esm/engine.constants-Bl5-pbq-.js +28143 -0
  193. package/dist/esm/index-BU9Mv7y0.js +1715 -0
  194. package/dist/esm/index.js +4134 -0
  195. package/dist/esm/kritzel-awareness-cursors_5.entry.js +27978 -0
  196. package/dist/esm/loader.js +11 -0
  197. package/dist/esm/stencil.js +21 -0
  198. package/dist/index.cjs.js +1 -0
  199. package/dist/index.js +1 -0
  200. package/dist/stencil/index.esm.js +4134 -0
  201. package/dist/stencil/p-BU9Mv7y0.js +1702 -0
  202. package/dist/stencil/p-Bl5-pbq-.js +28143 -0
  203. package/dist/stencil/p-DQuL1Twl.js +3 -0
  204. package/dist/stencil/p-f0a8b7af.entry.js +27978 -0
  205. package/dist/stencil/stencil.esm.js +21 -0
  206. package/dist/types/classes/core/core.class.d.ts +532 -0
  207. package/dist/types/classes/core/reviver.class.d.ts +32 -0
  208. package/dist/types/classes/core/store.class.d.ts +198 -0
  209. package/dist/types/classes/core/viewport.class.d.ts +256 -0
  210. package/dist/types/classes/core/workspace.class.d.ts +95 -0
  211. package/dist/types/classes/handlers/base.handler.d.ts +18 -0
  212. package/dist/types/classes/handlers/context-menu.handler.d.ts +67 -0
  213. package/dist/types/classes/handlers/hover.handler.d.ts +23 -0
  214. package/dist/types/classes/handlers/key.handler.d.ts +44 -0
  215. package/dist/types/classes/handlers/line-handle.handler.d.ts +115 -0
  216. package/dist/types/classes/handlers/move.handler.d.ts +94 -0
  217. package/dist/types/classes/handlers/resize.handler.d.ts +95 -0
  218. package/dist/types/classes/handlers/rotation.handler.d.ts +50 -0
  219. package/dist/types/classes/handlers/selection.handler.d.ts +153 -0
  220. package/dist/types/classes/managers/anchor.manager.d.ts +513 -0
  221. package/dist/types/classes/managers/browser-permission.manager.d.ts +41 -0
  222. package/dist/types/classes/managers/clipboard.manager.d.ts +71 -0
  223. package/dist/types/classes/managers/clipboard.types.d.ts +23 -0
  224. package/dist/types/classes/managers/cursor.manager.d.ts +66 -0
  225. package/dist/types/classes/managers/license.manager.d.ts +147 -0
  226. package/dist/types/classes/managers/localization.manager.d.ts +145 -0
  227. package/dist/types/classes/managers/theme.manager.d.ts +112 -0
  228. package/dist/types/classes/objects/base-object.class.d.ts +266 -0
  229. package/dist/types/classes/objects/dynamic-object.class.d.ts +148 -0
  230. package/dist/types/classes/objects/group.class.d.ts +231 -0
  231. package/dist/types/classes/objects/image.class.d.ts +246 -0
  232. package/dist/types/classes/objects/line.class.d.ts +285 -0
  233. package/dist/types/classes/objects/path.class.d.ts +220 -0
  234. package/dist/types/classes/objects/selection-box.class.d.ts +19 -0
  235. package/dist/types/classes/objects/selection-group.class.d.ts +267 -0
  236. package/dist/types/classes/objects/shape.class.d.ts +322 -0
  237. package/dist/types/classes/objects/text.class.d.ts +197 -0
  238. package/dist/types/classes/providers/assets/asset-resolver.class.d.ts +141 -0
  239. package/dist/types/classes/providers/assets/http-asset-provider.class.d.ts +79 -0
  240. package/dist/types/classes/providers/assets/indexeddb-asset-provider.class.d.ts +69 -0
  241. package/dist/types/classes/providers/assets/presigned-asset-provider.class.d.ts +69 -0
  242. package/dist/types/classes/providers/paste-intent/event-paste-intent.provider.d.ts +8 -0
  243. package/dist/types/classes/providers/paste-intent/ios-paste-intent.provider.d.ts +6 -0
  244. package/dist/types/classes/providers/paste-intent/navigator-paste-intent.provider.d.ts +9 -0
  245. package/dist/types/classes/providers/sync/broadcast-sync-provider.class.d.ts +23 -0
  246. package/dist/types/classes/providers/sync/hocuspocus-sync-provider.class.d.ts +163 -0
  247. package/dist/types/classes/providers/sync/in-memory-sync-provider.class.d.ts +39 -0
  248. package/dist/types/classes/providers/sync/indexeddb-sync-provider.class.d.ts +25 -0
  249. package/dist/types/classes/providers/sync/websocket-sync-provider.class.d.ts +63 -0
  250. package/dist/types/classes/registries/dynamic-object-renderer.registry.d.ts +32 -0
  251. package/dist/types/classes/registries/font-registry.class.d.ts +19 -0
  252. package/dist/types/classes/registries/icon-registry.class.d.ts +39 -0
  253. package/dist/types/classes/registries/paste-intent-provider.registry.d.ts +10 -0
  254. package/dist/types/classes/registries/tool.registry.d.ts +53 -0
  255. package/dist/types/classes/structures/app-state-map.structure.d.ts +171 -0
  256. package/dist/types/classes/structures/object-map.structure.d.ts +403 -0
  257. package/dist/types/classes/structures/quadtree.structure.d.ts +128 -0
  258. package/dist/types/classes/tools/base-tool.class.d.ts +72 -0
  259. package/dist/types/classes/tools/brush-tool.class.d.ts +68 -0
  260. package/dist/types/classes/tools/eraser-tool.class.d.ts +38 -0
  261. package/dist/types/classes/tools/image-tool.class.d.ts +74 -0
  262. package/dist/types/classes/tools/line-tool.class.d.ts +63 -0
  263. package/dist/types/classes/tools/selection-tool.class.d.ts +188 -0
  264. package/dist/types/classes/tools/shape-tool.class.d.ts +90 -0
  265. package/dist/types/classes/tools/text-tool.class.d.ts +66 -0
  266. package/dist/types/components/kritzel-awareness-cursors/kritzel-awareness-cursors.d.ts +29 -0
  267. package/dist/types/components/kritzel-cursor-trail/kritzel-cursor-trail.d.ts +19 -0
  268. package/dist/types/components/kritzel-engine/kritzel-engine.d.ts +695 -0
  269. package/dist/types/components/kritzel-icon/kritzel-icon.d.ts +6 -0
  270. package/dist/types/components/kritzel-watermark/kritzel-watermark.d.ts +20 -0
  271. package/dist/types/components.d.ts +981 -0
  272. package/dist/types/configs/default-asset-storage.config.d.ts +8 -0
  273. package/dist/types/configs/default-brush-tool.config.d.ts +2 -0
  274. package/dist/types/configs/default-engine-config.d.ts +2 -0
  275. package/dist/types/configs/default-line-tool.config.d.ts +2 -0
  276. package/dist/types/configs/default-shape-tool.config.d.ts +2 -0
  277. package/dist/types/configs/default-sync.config.d.ts +5 -0
  278. package/dist/types/configs/default-text-tool.config.d.ts +2 -0
  279. package/dist/types/constants/color-palette.constants.d.ts +31 -0
  280. package/dist/types/constants/core.constants.d.ts +0 -0
  281. package/dist/types/constants/engine.constants.d.ts +4 -0
  282. package/dist/types/constants/license.constants.d.ts +25 -0
  283. package/dist/types/constants/schema.constants.d.ts +4 -0
  284. package/dist/types/constants/storage.constants.d.ts +1 -0
  285. package/dist/types/constants/stroke-size.constants.d.ts +2 -0
  286. package/dist/types/constants/text-tool-fonts.constants.d.ts +3 -0
  287. package/dist/types/constants/version.d.ts +6 -0
  288. package/dist/types/enums/alignment.enum.d.ts +8 -0
  289. package/dist/types/enums/event-button.enum.d.ts +5 -0
  290. package/dist/types/enums/handle-type.enum.d.ts +6 -0
  291. package/dist/types/enums/shape-type.enum.d.ts +5 -0
  292. package/dist/types/events/active-workspace-change.event.d.ts +7 -0
  293. package/dist/types/events/editor-is-ready.event.d.ts +18 -0
  294. package/dist/types/events/login.event.d.ts +3 -0
  295. package/dist/types/helpers/alignment.helper.d.ts +21 -0
  296. package/dist/types/helpers/class.helper.d.ts +3 -0
  297. package/dist/types/helpers/color.helper.d.ts +34 -0
  298. package/dist/types/helpers/cursor.helper.d.ts +22 -0
  299. package/dist/types/helpers/devices.helper.d.ts +8 -0
  300. package/dist/types/helpers/event.helper.d.ts +6 -0
  301. package/dist/types/helpers/geometry.helper.d.ts +38 -0
  302. package/dist/types/helpers/html.helper.d.ts +8 -0
  303. package/dist/types/helpers/image-file.helper.d.ts +3 -0
  304. package/dist/types/helpers/keyboard.helper.d.ts +6 -0
  305. package/dist/types/helpers/localization.helper.d.ts +18 -0
  306. package/dist/types/helpers/math.helper.d.ts +4 -0
  307. package/dist/types/helpers/migration.helper.d.ts +30 -0
  308. package/dist/types/helpers/object.helper.d.ts +9 -0
  309. package/dist/types/helpers/svg-export.helper.d.ts +231 -0
  310. package/dist/types/helpers/theme.helper.d.ts +42 -0
  311. package/dist/types/helpers/tool-config.helper.d.ts +4 -0
  312. package/dist/types/helpers/wheel.helper.d.ts +9 -0
  313. package/dist/types/index.d.ts +109 -0
  314. package/dist/types/interfaces/anchor.interface.d.ts +147 -0
  315. package/dist/types/interfaces/arrow-head.interface.d.ts +27 -0
  316. package/dist/types/interfaces/asset-provider.interface.d.ts +88 -0
  317. package/dist/types/interfaces/asset-storage-config.interface.d.ts +40 -0
  318. package/dist/types/interfaces/asset.interface.d.ts +43 -0
  319. package/dist/types/interfaces/bounding-box.interface.d.ts +8 -0
  320. package/dist/types/interfaces/clonable.interface.d.ts +3 -0
  321. package/dist/types/interfaces/context-menu-item.interface.d.ts +25 -0
  322. package/dist/types/interfaces/context-menu-state.interface.d.ts +16 -0
  323. package/dist/types/interfaces/debug-info.interface.d.ts +7 -0
  324. package/dist/types/interfaces/dialog.interface.d.ts +4 -0
  325. package/dist/types/interfaces/document-metadata.interface.d.ts +6 -0
  326. package/dist/types/interfaces/dynamic-object-renderer.interface.d.ts +40 -0
  327. package/dist/types/interfaces/engine-state.interface.d.ts +82 -0
  328. package/dist/types/interfaces/font.interface.d.ts +15 -0
  329. package/dist/types/interfaces/localization.interface.d.ts +143 -0
  330. package/dist/types/interfaces/login-config.interface.d.ts +24 -0
  331. package/dist/types/interfaces/master-detail.interface.d.ts +14 -0
  332. package/dist/types/interfaces/menu-item.interface.d.ts +27 -0
  333. package/dist/types/interfaces/migration.interface.d.ts +16 -0
  334. package/dist/types/interfaces/notification.interface.d.ts +10 -0
  335. package/dist/types/interfaces/object-change-event.interface.d.ts +31 -0
  336. package/dist/types/interfaces/object-export.interface.d.ts +20 -0
  337. package/dist/types/interfaces/object.interface.d.ts +53 -0
  338. package/dist/types/interfaces/paste-intent-provider.interface.d.ts +10 -0
  339. package/dist/types/interfaces/point.interface.d.ts +4 -0
  340. package/dist/types/interfaces/polygon.interface.d.ts +7 -0
  341. package/dist/types/interfaces/remote-cursor.interface.d.ts +18 -0
  342. package/dist/types/interfaces/selection-state.interface.d.ts +7 -0
  343. package/dist/types/interfaces/serializable.interface.d.ts +5 -0
  344. package/dist/types/interfaces/settings.interface.d.ts +25 -0
  345. package/dist/types/interfaces/share.interface.d.ts +9 -0
  346. package/dist/types/interfaces/shortcut.interface.d.ts +10 -0
  347. package/dist/types/interfaces/sync-config.interface.d.ts +41 -0
  348. package/dist/types/interfaces/sync-provider.interface.d.ts +66 -0
  349. package/dist/types/interfaces/theme.interface.d.ts +553 -0
  350. package/dist/types/interfaces/tool-config.interface.d.ts +24 -0
  351. package/dist/types/interfaces/tool-type.interface.d.ts +1 -0
  352. package/dist/types/interfaces/tool.interface.d.ts +8 -0
  353. package/dist/types/interfaces/toolbar-item.interface.d.ts +66 -0
  354. package/dist/types/interfaces/undo-state.interface.d.ts +6 -0
  355. package/dist/types/interfaces/user.interface.d.ts +22 -0
  356. package/dist/types/interfaces/viewport-state.interface.d.ts +7 -0
  357. package/dist/types/locales/de-locale.d.ts +5 -0
  358. package/dist/types/locales/en-locale.d.ts +6 -0
  359. package/dist/types/locales/fr-locale.d.ts +5 -0
  360. package/dist/types/migrations/app-state.migrations.d.ts +11 -0
  361. package/dist/types/migrations/workspace.migrations.d.ts +11 -0
  362. package/dist/types/stencil-public-runtime.d.ts +1873 -0
  363. package/dist/types/themes/dark-theme.d.ts +5 -0
  364. package/dist/types/themes/light-theme.d.ts +5 -0
  365. package/dist/types/types/deep-readonly.type.d.ts +7 -0
  366. package/dist/types/types/state.types.d.ts +3 -0
  367. package/loader/cdn.js +1 -0
  368. package/loader/index.cjs.js +1 -0
  369. package/loader/index.d.ts +24 -0
  370. package/loader/index.es2017.js +1 -0
  371. package/loader/index.js +2 -0
  372. package/package.json +101 -0
  373. package/readme.md +11 -0
@@ -0,0 +1,4143 @@
1
+ export { g as getAssetPath, r as render, s as setAssetPath, a as setNonce, b as setPlatformOptions } from './p-CfSx6HU_.js';
2
+ import { D as DEFAULT_COLOR_PALETTE } from './p-BvRGQvVI.js';
3
+ export { K as KritzelBaseObject, c as KritzelColorHelper, b as KritzelLine, a as KritzelPath, d as KritzelThemeManager, O as ObjectHelper, T as ThemeHelper, e as darkTheme, l as lightTheme, r as resolveColor } from './p-BvRGQvVI.js';
4
+ import { D as DEFAULT_STROKE_SIZES, a as DEFAULT_FONT_SIZES, b as DEFAULT_TEXT_TOOL_AVAILABLE_FONTS, S as ShapeType } from './kritzel-engine.js';
5
+ export { L as APP_STATE_MIGRATIONS, A as AssetNotFoundError, N as CURRENT_APP_STATE_SCHEMA_VERSION, O as CURRENT_WORKSPACE_SCHEMA_VERSION, C as DEFAULT_SYNC_CONFIG, F as DE_LOCALE, E as EN_LOCALE, G as FR_LOCALE, I as IndexedDBAssetProvider, H as KritzelAlignment, w as KritzelAnchorManager, u as KritzelAssetResolver, i as KritzelBaseTool, j as KritzelBrushTool, p as KritzelCursorHelper, r as KritzelDevicesHelper, f as KritzelDynamicObject, z as KritzelDynamicObjectRendererRegistry, KritzelEngine, l as KritzelEraserTool, B as KritzelFontRegistry, d as KritzelGroup, s as KritzelHTMLHelper, c as KritzelImage, m as KritzelImageTool, q as KritzelKeyboardHelper, y as KritzelLicenseManager, k as KritzelLineTool, x as KritzelLocalizationManager, h as KritzelSelectionBox, g as KritzelSelectionGroup, t as KritzelSelectionTool, e as KritzelShape, o as KritzelShapeTool, K as KritzelText, n as KritzelTextTool, v as KritzelWorkspace, W as WORKSPACE_EXPORT_VERSION, M as WORKSPACE_MIGRATIONS, defineCustomElement as defineCustomElementKritzelEngine, P as resolveTextToolAvailableFonts, J as runMigrations } from './kritzel-engine.js';
6
+ import * as Y from 'yjs';
7
+ import { IndexeddbPersistence } from 'y-indexeddb';
8
+ import { WebsocketProvider } from 'y-websocket';
9
+ export { K as KritzelIconRegistry } from './p-fx6msYHJ.js';
10
+ export { A as ABSOLUTE_SCALE_MAX, a as ABSOLUTE_SCALE_MIN, K as KRITZEL_WEBSITE_URL } from './p-B2Htv9ou.js';
11
+ export { KritzelAwarenessCursors, defineCustomElement as defineCustomElementKritzelAwarenessCursors } from './kritzel-awareness-cursors.js';
12
+ export { KritzelCursorTrail, defineCustomElement as defineCustomElementKritzelCursorTrail } from './kritzel-cursor-trail.js';
13
+ export { KritzelIcon, defineCustomElement as defineCustomElementKritzelIcon } from './kritzel-icon.js';
14
+ export { KritzelWatermark, defineCustomElement as defineCustomElementKritzelWatermark } from './kritzel-watermark.js';
15
+
16
+ class KritzelToolConfigHelper {
17
+ static getToolConfig(tool) {
18
+ switch (tool?.toolType) {
19
+ case 'selection':
20
+ return 'getToolConfig' in tool && typeof tool.getToolConfig === 'function'
21
+ ? tool.getToolConfig()
22
+ : null;
23
+ case 'brush':
24
+ return {
25
+ type: 'brush',
26
+ colorProperty: 'color',
27
+ sizeProperty: 'size',
28
+ opacityProperty: 'opacity',
29
+ paletteSource: 'palette',
30
+ sizesSource: 'sizes',
31
+ controls: [
32
+ { type: 'stroke-size', propertyName: 'size' },
33
+ ],
34
+ };
35
+ case 'line':
36
+ return {
37
+ type: 'line',
38
+ colorProperty: 'color',
39
+ sizeProperty: 'size',
40
+ opacityProperty: 'opacity',
41
+ paletteSource: 'palette',
42
+ sizesSource: 'sizes',
43
+ controls: [
44
+ { type: 'stroke-size', propertyName: 'size' },
45
+ { type: 'line-endings', propertyName: 'arrows', additionalProps: {} },
46
+ ],
47
+ };
48
+ case 'shape':
49
+ return {
50
+ type: 'shape',
51
+ colorProperty: 'strokeColor',
52
+ sizeProperty: 'strokeWidth',
53
+ opacityProperty: 'opacity',
54
+ paletteSource: 'palette',
55
+ sizesSource: 'sizes',
56
+ controls: [
57
+ { type: 'stroke-size', propertyName: 'strokeWidth' },
58
+ { type: 'shape-fill', propertyName: 'fillColor', additionalProps: {} },
59
+ ],
60
+ };
61
+ case 'text':
62
+ return {
63
+ type: 'text',
64
+ colorProperty: 'fontColor',
65
+ sizeProperty: 'fontSize',
66
+ opacityProperty: 'opacity',
67
+ paletteSource: 'palette',
68
+ sizesSource: 'sizes',
69
+ controls: [
70
+ { type: 'font-size', propertyName: 'fontSize', additionalProps: {} },
71
+ { type: 'font-family', propertyName: 'fontFamily' },
72
+ ],
73
+ };
74
+ default:
75
+ return null;
76
+ }
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Common Math expressions.
82
+ *
83
+ * @module math
84
+ */
85
+
86
+ const floor$2 = Math.floor;
87
+
88
+ /**
89
+ * @function
90
+ * @param {number} a
91
+ * @param {number} b
92
+ * @return {number} The smaller element of a and b
93
+ */
94
+ const min$2 = (a, b) => a < b ? a : b;
95
+
96
+ /**
97
+ * @function
98
+ * @param {number} a
99
+ * @param {number} b
100
+ * @return {number} The bigger element of a and b
101
+ */
102
+ const max$2 = (a, b) => a > b ? a : b;
103
+
104
+ /* eslint-env browser */
105
+
106
+ const BIT8$2 = 128;
107
+ const BITS7$2 = 127;
108
+
109
+ /**
110
+ * Utility helpers for working with numbers.
111
+ *
112
+ * @module number
113
+ */
114
+
115
+
116
+ const MAX_SAFE_INTEGER$2 = Number.MAX_SAFE_INTEGER;
117
+
118
+ /**
119
+ * Efficient schema-less binary encoding with support for variable length encoding.
120
+ *
121
+ * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.
122
+ *
123
+ * Encodes numbers in little-endian order (least to most significant byte order)
124
+ * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)
125
+ * which is also used in Protocol Buffers.
126
+ *
127
+ * ```js
128
+ * // encoding step
129
+ * const encoder = encoding.createEncoder()
130
+ * encoding.writeVarUint(encoder, 256)
131
+ * encoding.writeVarString(encoder, 'Hello world!')
132
+ * const buf = encoding.toUint8Array(encoder)
133
+ * ```
134
+ *
135
+ * ```js
136
+ * // decoding step
137
+ * const decoder = decoding.createDecoder(buf)
138
+ * decoding.readVarUint(decoder) // => 256
139
+ * decoding.readVarString(decoder) // => 'Hello world!'
140
+ * decoding.hasContent(decoder) // => false - all data is read
141
+ * ```
142
+ *
143
+ * @module encoding
144
+ */
145
+
146
+
147
+ /**
148
+ * A BinaryEncoder handles the encoding to an Uint8Array.
149
+ */
150
+ let Encoder$1 = class Encoder {
151
+ constructor () {
152
+ this.cpos = 0;
153
+ this.cbuf = new Uint8Array(100);
154
+ /**
155
+ * @type {Array<Uint8Array>}
156
+ */
157
+ this.bufs = [];
158
+ }
159
+ };
160
+
161
+ /**
162
+ * @function
163
+ * @return {Encoder}
164
+ */
165
+ const createEncoder$1 = () => new Encoder$1();
166
+
167
+ /**
168
+ * The current length of the encoded data.
169
+ *
170
+ * @function
171
+ * @param {Encoder} encoder
172
+ * @return {number}
173
+ */
174
+ const length$2 = encoder => {
175
+ let len = encoder.cpos;
176
+ for (let i = 0; i < encoder.bufs.length; i++) {
177
+ len += encoder.bufs[i].length;
178
+ }
179
+ return len
180
+ };
181
+
182
+ /**
183
+ * Transform to Uint8Array.
184
+ *
185
+ * @function
186
+ * @param {Encoder} encoder
187
+ * @return {Uint8Array<ArrayBuffer>} The created ArrayBuffer.
188
+ */
189
+ const toUint8Array$1 = encoder => {
190
+ const uint8arr = new Uint8Array(length$2(encoder));
191
+ let curPos = 0;
192
+ for (let i = 0; i < encoder.bufs.length; i++) {
193
+ const d = encoder.bufs[i];
194
+ uint8arr.set(d, curPos);
195
+ curPos += d.length;
196
+ }
197
+ uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos);
198
+ return uint8arr
199
+ };
200
+
201
+ /**
202
+ * Write one byte to the encoder.
203
+ *
204
+ * @function
205
+ * @param {Encoder} encoder
206
+ * @param {number} num The byte that is to be encoded.
207
+ */
208
+ const write$2 = (encoder, num) => {
209
+ const bufferLen = encoder.cbuf.length;
210
+ if (encoder.cpos === bufferLen) {
211
+ encoder.bufs.push(encoder.cbuf);
212
+ encoder.cbuf = new Uint8Array(bufferLen * 2);
213
+ encoder.cpos = 0;
214
+ }
215
+ encoder.cbuf[encoder.cpos++] = num;
216
+ };
217
+
218
+ /**
219
+ * Write a variable length unsigned integer. Max encodable integer is 2^53.
220
+ *
221
+ * @function
222
+ * @param {Encoder} encoder
223
+ * @param {number} num The number that is to be encoded.
224
+ */
225
+ const writeVarUint$2 = (encoder, num) => {
226
+ while (num > BITS7$2) {
227
+ write$2(encoder, BIT8$2 | (BITS7$2 & num));
228
+ num = floor$2(num / 128); // shift >>> 7
229
+ }
230
+ write$2(encoder, BITS7$2 & num);
231
+ };
232
+
233
+ /**
234
+ * Append fixed-length Uint8Array to the encoder.
235
+ *
236
+ * @function
237
+ * @param {Encoder} encoder
238
+ * @param {Uint8Array} uint8Array
239
+ */
240
+ const writeUint8Array$2 = (encoder, uint8Array) => {
241
+ const bufferLen = encoder.cbuf.length;
242
+ const cpos = encoder.cpos;
243
+ const leftCopyLen = min$2(bufferLen - cpos, uint8Array.length);
244
+ const rightCopyLen = uint8Array.length - leftCopyLen;
245
+ encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
246
+ encoder.cpos += leftCopyLen;
247
+ if (rightCopyLen > 0) {
248
+ // Still something to write, write right half..
249
+ // Append new buffer
250
+ encoder.bufs.push(encoder.cbuf);
251
+ // must have at least size of remaining buffer
252
+ encoder.cbuf = new Uint8Array(max$2(bufferLen * 2, rightCopyLen));
253
+ // copy array
254
+ encoder.cbuf.set(uint8Array.subarray(leftCopyLen));
255
+ encoder.cpos = rightCopyLen;
256
+ }
257
+ };
258
+
259
+ /**
260
+ * Append an Uint8Array to Encoder.
261
+ *
262
+ * @function
263
+ * @param {Encoder} encoder
264
+ * @param {Uint8Array} uint8Array
265
+ */
266
+ const writeVarUint8Array$2 = (encoder, uint8Array) => {
267
+ writeVarUint$2(encoder, uint8Array.byteLength);
268
+ writeUint8Array$2(encoder, uint8Array);
269
+ };
270
+
271
+ /**
272
+ * Error helpers.
273
+ *
274
+ * @module error
275
+ */
276
+
277
+ /**
278
+ * @param {string} s
279
+ * @return {Error}
280
+ */
281
+ /* c8 ignore next */
282
+ const create$4 = s => new Error(s);
283
+
284
+ /**
285
+ * Efficient schema-less binary decoding with support for variable length encoding.
286
+ *
287
+ * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.
288
+ *
289
+ * Encodes numbers in little-endian order (least to most significant byte order)
290
+ * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)
291
+ * which is also used in Protocol Buffers.
292
+ *
293
+ * ```js
294
+ * // encoding step
295
+ * const encoder = encoding.createEncoder()
296
+ * encoding.writeVarUint(encoder, 256)
297
+ * encoding.writeVarString(encoder, 'Hello world!')
298
+ * const buf = encoding.toUint8Array(encoder)
299
+ * ```
300
+ *
301
+ * ```js
302
+ * // decoding step
303
+ * const decoder = decoding.createDecoder(buf)
304
+ * decoding.readVarUint(decoder) // => 256
305
+ * decoding.readVarString(decoder) // => 'Hello world!'
306
+ * decoding.hasContent(decoder) // => false - all data is read
307
+ * ```
308
+ *
309
+ * @module decoding
310
+ */
311
+
312
+
313
+ const errorUnexpectedEndOfArray$2 = create$4('Unexpected end of array');
314
+ const errorIntegerOutOfRange$2 = create$4('Integer out of Range');
315
+
316
+ /**
317
+ * A Decoder handles the decoding of an Uint8Array.
318
+ * @template {ArrayBufferLike} [Buf=ArrayBufferLike]
319
+ */
320
+ let Decoder$1 = class Decoder {
321
+ /**
322
+ * @param {Uint8Array<Buf>} uint8Array Binary data to decode
323
+ */
324
+ constructor (uint8Array) {
325
+ /**
326
+ * Decoding target.
327
+ *
328
+ * @type {Uint8Array<Buf>}
329
+ */
330
+ this.arr = uint8Array;
331
+ /**
332
+ * Current decoding position.
333
+ *
334
+ * @type {number}
335
+ */
336
+ this.pos = 0;
337
+ }
338
+ };
339
+
340
+ /**
341
+ * @function
342
+ * @template {ArrayBufferLike} Buf
343
+ * @param {Uint8Array<Buf>} uint8Array
344
+ * @return {Decoder<Buf>}
345
+ */
346
+ const createDecoder$1 = uint8Array => new Decoder$1(uint8Array);
347
+
348
+ /**
349
+ * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.
350
+ *
351
+ * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.
352
+ * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.
353
+ *
354
+ * @function
355
+ * @template {ArrayBufferLike} Buf
356
+ * @param {Decoder<Buf>} decoder The decoder instance
357
+ * @param {number} len The length of bytes to read
358
+ * @return {Uint8Array<Buf>}
359
+ */
360
+ const readUint8Array$2 = (decoder, len) => {
361
+ const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len);
362
+ decoder.pos += len;
363
+ return view
364
+ };
365
+
366
+ /**
367
+ * Read variable length Uint8Array.
368
+ *
369
+ * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.
370
+ * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.
371
+ *
372
+ * @function
373
+ * @template {ArrayBufferLike} Buf
374
+ * @param {Decoder<Buf>} decoder
375
+ * @return {Uint8Array<Buf>}
376
+ */
377
+ const readVarUint8Array$2 = decoder => readUint8Array$2(decoder, readVarUint$2(decoder));
378
+
379
+ /**
380
+ * Read unsigned integer (32bit) with variable length.
381
+ * 1/8th of the storage is used as encoding overhead.
382
+ * * numbers < 2^7 is stored in one bytlength
383
+ * * numbers < 2^14 is stored in two bylength
384
+ *
385
+ * @function
386
+ * @param {Decoder} decoder
387
+ * @return {number} An unsigned integer.length
388
+ */
389
+ const readVarUint$2 = decoder => {
390
+ let num = 0;
391
+ let mult = 1;
392
+ const len = decoder.arr.length;
393
+ while (decoder.pos < len) {
394
+ const r = decoder.arr[decoder.pos++];
395
+ // num = num | ((r & binary.BITS7) << len)
396
+ num = num + (r & BITS7$2) * mult; // shift $r << (7*#iterations) and add it to num
397
+ mult *= 128; // next iteration, shift 7 "more" to the left
398
+ if (r < BIT8$2) {
399
+ return num
400
+ }
401
+ /* c8 ignore start */
402
+ if (num > MAX_SAFE_INTEGER$2) {
403
+ throw errorIntegerOutOfRange$2
404
+ }
405
+ /* c8 ignore stop */
406
+ }
407
+ throw errorUnexpectedEndOfArray$2
408
+ };
409
+
410
+ /**
411
+ * BroadcastChannel sync provider for cross-tab synchronization
412
+ * This is a lightweight alternative to y-webrtc for browser-tab-only sync
413
+ */
414
+ class BroadcastSyncProvider {
415
+ static type = 'local';
416
+ type = 'local';
417
+ doc;
418
+ channel;
419
+ _synced = false;
420
+ constructor(docName, doc, _options) {
421
+ this.doc = doc;
422
+ this.channel = new BroadcastChannel(docName);
423
+ // Handle incoming messages from other tabs
424
+ this.channel.onmessage = (event) => {
425
+ this.handleMessage(event.data);
426
+ };
427
+ // Listen to document updates and broadcast them
428
+ this.doc.on('update', this.handleDocUpdate);
429
+ // Send initial sync request
430
+ this.broadcastSync();
431
+ // Mark as synced after a short delay (to receive any pending updates)
432
+ setTimeout(() => {
433
+ this._synced = true;
434
+ }, 100);
435
+ if (!_options?.quiet) {
436
+ console.info(`BroadcastChannel Provider initialized: ${docName}`);
437
+ }
438
+ }
439
+ handleDocUpdate = (update, origin) => {
440
+ // Don't broadcast updates that came from other tabs (to prevent loops)
441
+ if (origin !== this) {
442
+ const encoder = createEncoder$1();
443
+ writeVarUint$2(encoder, 0); // Message type: sync update
444
+ writeVarUint8Array$2(encoder, update);
445
+ this.channel.postMessage(toUint8Array$1(encoder));
446
+ }
447
+ };
448
+ handleMessage(message) {
449
+ const decoder = createDecoder$1(new Uint8Array(message));
450
+ const messageType = readVarUint$2(decoder);
451
+ switch (messageType) {
452
+ case 0: // Sync update
453
+ const update = readVarUint8Array$2(decoder);
454
+ Y.applyUpdate(this.doc, update, this);
455
+ break;
456
+ case 1: // Sync request
457
+ this.broadcastSync();
458
+ break;
459
+ case 2: // Sync response
460
+ const stateVector = readVarUint8Array$2(decoder);
461
+ const updateResponse = Y.encodeStateAsUpdate(this.doc, stateVector);
462
+ if (updateResponse.length > 0) {
463
+ const encoder = createEncoder$1();
464
+ writeVarUint$2(encoder, 0); // Send as regular update
465
+ writeVarUint8Array$2(encoder, updateResponse);
466
+ this.channel.postMessage(toUint8Array$1(encoder));
467
+ }
468
+ break;
469
+ }
470
+ }
471
+ broadcastSync() {
472
+ // Broadcast our current state vector to request missing updates
473
+ const encoder = createEncoder$1();
474
+ writeVarUint$2(encoder, 2); // Message type: sync response
475
+ writeVarUint8Array$2(encoder, Y.encodeStateVector(this.doc));
476
+ this.channel.postMessage(toUint8Array$1(encoder));
477
+ }
478
+ async connect() {
479
+ // Wait for initial sync to complete
480
+ if (this._synced) {
481
+ return;
482
+ }
483
+ return new Promise((resolve) => {
484
+ const checkSync = () => {
485
+ if (this._synced) {
486
+ resolve();
487
+ }
488
+ else {
489
+ setTimeout(checkSync, 50);
490
+ }
491
+ };
492
+ checkSync();
493
+ });
494
+ }
495
+ disconnect() {
496
+ // BroadcastChannel doesn't have explicit disconnect
497
+ }
498
+ async reconnect() {
499
+ this.disconnect();
500
+ return this.connect();
501
+ }
502
+ destroy() {
503
+ this.doc.off('update', this.handleDocUpdate);
504
+ this.channel.close();
505
+ }
506
+ }
507
+
508
+ /**
509
+ * Module-scoped cache that survives component removal and remounting
510
+ * within the same JS runtime. Cleared on page reload.
511
+ */
512
+ const sessionCache = new Map();
513
+ /**
514
+ * In-memory sync provider for session-scoped persistence.
515
+ *
516
+ * State survives the component being removed from the DOM and later
517
+ * re-added within the same page session, but is lost on page reload.
518
+ * Intended for documentation demos where durable IndexedDB persistence
519
+ * is not desired.
520
+ */
521
+ class InMemorySyncProvider {
522
+ static type = 'local';
523
+ type = 'local';
524
+ doc;
525
+ cacheKey;
526
+ isConnected = false;
527
+ constructor(docName, doc, options) {
528
+ this.doc = doc;
529
+ this.cacheKey = options?.name ?? docName;
530
+ }
531
+ handleUpdate = (_update, origin) => {
532
+ // Skip updates that originated from connect() rehydration to avoid a
533
+ // redundant re-encode of the state we just applied.
534
+ if (origin === this) {
535
+ return;
536
+ }
537
+ sessionCache.set(this.cacheKey, Y.encodeStateAsUpdate(this.doc));
538
+ };
539
+ async connect() {
540
+ if (this.isConnected) {
541
+ return;
542
+ }
543
+ const cached = sessionCache.get(this.cacheKey);
544
+ if (cached) {
545
+ Y.applyUpdate(this.doc, cached, this);
546
+ }
547
+ this.doc.on('update', this.handleUpdate);
548
+ this.isConnected = true;
549
+ }
550
+ disconnect() {
551
+ this.isConnected = false;
552
+ }
553
+ async reconnect() {
554
+ this.disconnect();
555
+ return this.connect();
556
+ }
557
+ destroy() {
558
+ this.doc.off('update', this.handleUpdate);
559
+ this.isConnected = false;
560
+ }
561
+ /**
562
+ * Clears the in-memory cache.
563
+ *
564
+ * @param name - If provided, only the entry with this cache key is removed.
565
+ * If omitted, all entries are cleared.
566
+ */
567
+ static clear(name) {
568
+ if (name !== undefined) {
569
+ sessionCache.delete(name);
570
+ }
571
+ else {
572
+ sessionCache.clear();
573
+ }
574
+ }
575
+ }
576
+
577
+ /**
578
+ * IndexedDB sync provider for local persistence
579
+ */
580
+ class IndexedDBSyncProvider {
581
+ static type = 'local';
582
+ type = 'local';
583
+ provider;
584
+ isConnected = false;
585
+ constructor(docName, doc, options) {
586
+ const dbName = options?.name || docName;
587
+ this.provider = new IndexeddbPersistence(dbName, doc);
588
+ }
589
+ async connect() {
590
+ if (this.isConnected) {
591
+ return;
592
+ }
593
+ return new Promise(resolve => {
594
+ this.provider.on('synced', () => {
595
+ this.isConnected = true;
596
+ resolve();
597
+ });
598
+ });
599
+ }
600
+ disconnect() {
601
+ // IndexedDB doesn't need explicit disconnect
602
+ this.isConnected = false;
603
+ }
604
+ async reconnect() {
605
+ this.disconnect();
606
+ return this.connect();
607
+ }
608
+ destroy() {
609
+ if (this.provider) {
610
+ this.provider.destroy();
611
+ }
612
+ this.isConnected = false;
613
+ }
614
+ }
615
+
616
+ /**
617
+ * WebSocket sync provider for real-time collaboration
618
+ */
619
+ class WebSocketSyncProvider {
620
+ static type = 'network';
621
+ type = 'network';
622
+ provider;
623
+ isConnected = false;
624
+ _quiet = false;
625
+ get awareness() {
626
+ return this.provider.awareness;
627
+ }
628
+ get rawProvider() {
629
+ return this.provider;
630
+ }
631
+ constructor(docName, doc, options) {
632
+ const url = options?.url || 'ws://localhost:1234';
633
+ const roomName = options?.roomName || docName;
634
+ this.provider = new WebsocketProvider(url, roomName, doc, {
635
+ params: options?.params,
636
+ protocols: options?.protocols,
637
+ WebSocketPolyfill: options?.WebSocketPolyfill,
638
+ awareness: options?.awareness,
639
+ maxBackoffTime: options?.maxBackoffTime,
640
+ disableBc: true,
641
+ });
642
+ this._quiet = options?.quiet ?? false;
643
+ this.setupEventListeners();
644
+ if (!this._quiet) {
645
+ console.info(`WebSocket Provider initialized: ${url}/${roomName}`);
646
+ }
647
+ }
648
+ /**
649
+ * Static factory method for creating WebSocketSyncProvider with configuration options
650
+ * Returns a ProviderFactory that can be used in sync configuration
651
+ */
652
+ static with(options) {
653
+ return {
654
+ type: 'network',
655
+ create: (docName, doc, runtimeOptions) => {
656
+ const mergedOptions = runtimeOptions ? { ...options, ...runtimeOptions } : options;
657
+ return new WebSocketSyncProvider(docName, doc, mergedOptions);
658
+ },
659
+ };
660
+ }
661
+ setupEventListeners() {
662
+ this.provider.on('status', ({ status }) => {
663
+ if (status === 'connected') {
664
+ this.isConnected = true;
665
+ if (!this._quiet) {
666
+ console.info('WebSocket connected');
667
+ }
668
+ }
669
+ else if (status === 'disconnected') {
670
+ this.isConnected = false;
671
+ if (!this._quiet) {
672
+ console.info('WebSocket disconnected');
673
+ }
674
+ }
675
+ });
676
+ this.provider.on('sync', (synced) => {
677
+ if (synced && !this._quiet) {
678
+ console.info('WebSocket synced');
679
+ }
680
+ });
681
+ }
682
+ async connect() {
683
+ if (this.isConnected) {
684
+ return;
685
+ }
686
+ return new Promise((resolve, reject) => {
687
+ const timeout = setTimeout(() => {
688
+ reject(new Error('WebSocket connection timeout'));
689
+ }, 10000); // 10 second timeout
690
+ const statusHandler = ({ status }) => {
691
+ if (status === 'connected') {
692
+ clearTimeout(timeout);
693
+ this.provider.off('status', statusHandler);
694
+ this.isConnected = true;
695
+ resolve();
696
+ }
697
+ };
698
+ this.provider.on('status', statusHandler);
699
+ // If already connected, resolve immediately
700
+ if (this.provider.wsconnected) {
701
+ clearTimeout(timeout);
702
+ this.provider.off('status', statusHandler);
703
+ this.isConnected = true;
704
+ resolve();
705
+ }
706
+ });
707
+ }
708
+ disconnect() {
709
+ if (this.provider) {
710
+ this.provider.disconnect();
711
+ }
712
+ this.isConnected = false;
713
+ }
714
+ async reconnect() {
715
+ this.disconnect();
716
+ return this.connect();
717
+ }
718
+ destroy() {
719
+ if (this.provider) {
720
+ this.provider.destroy();
721
+ }
722
+ this.isConnected = false;
723
+ }
724
+ }
725
+
726
+ /**
727
+ * Common Math expressions.
728
+ *
729
+ * @module math
730
+ */
731
+
732
+ const floor$1 = Math.floor;
733
+
734
+ /**
735
+ * @function
736
+ * @param {number} a
737
+ * @param {number} b
738
+ * @return {number} The smaller element of a and b
739
+ */
740
+ const min$1 = (a, b) => a < b ? a : b;
741
+
742
+ /**
743
+ * @function
744
+ * @param {number} a
745
+ * @param {number} b
746
+ * @return {number} The bigger element of a and b
747
+ */
748
+ const max$1 = (a, b) => a > b ? a : b;
749
+
750
+ /* eslint-env browser */
751
+
752
+ const BIT8$1 = 128;
753
+ const BITS7$1 = 127;
754
+
755
+ /**
756
+ * Utility helpers for working with numbers.
757
+ *
758
+ * @module number
759
+ */
760
+
761
+
762
+ const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER;
763
+
764
+ /**
765
+ * @param {string} str
766
+ * @return {Uint8Array}
767
+ */
768
+ const _encodeUtf8Polyfill$1 = str => {
769
+ const encodedString = unescape(encodeURIComponent(str));
770
+ const len = encodedString.length;
771
+ const buf = new Uint8Array(len);
772
+ for (let i = 0; i < len; i++) {
773
+ buf[i] = /** @type {number} */ (encodedString.codePointAt(i));
774
+ }
775
+ return buf
776
+ };
777
+
778
+ /* c8 ignore next */
779
+ const utf8TextEncoder$1 = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null);
780
+
781
+ /**
782
+ * @param {string} str
783
+ * @return {Uint8Array}
784
+ */
785
+ const _encodeUtf8Native$1 = str => utf8TextEncoder$1.encode(str);
786
+
787
+ /**
788
+ * @param {string} str
789
+ * @return {Uint8Array}
790
+ */
791
+ /* c8 ignore next */
792
+ const encodeUtf8$1 = utf8TextEncoder$1 ? _encodeUtf8Native$1 : _encodeUtf8Polyfill$1;
793
+
794
+ /* c8 ignore next */
795
+ let utf8TextDecoder$1 = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
796
+
797
+ /* c8 ignore start */
798
+ if (utf8TextDecoder$1 && utf8TextDecoder$1.decode(new Uint8Array()).length === 1) {
799
+ // Safari doesn't handle BOM correctly.
800
+ // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.
801
+ // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and
802
+ // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call
803
+ // Another issue is that from then on no BOM chars are recognized anymore
804
+ /* c8 ignore next */
805
+ utf8TextDecoder$1 = null;
806
+ }
807
+
808
+ /**
809
+ * Efficient schema-less binary encoding with support for variable length encoding.
810
+ *
811
+ * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.
812
+ *
813
+ * Encodes numbers in little-endian order (least to most significant byte order)
814
+ * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)
815
+ * which is also used in Protocol Buffers.
816
+ *
817
+ * ```js
818
+ * // encoding step
819
+ * const encoder = encoding.createEncoder()
820
+ * encoding.writeVarUint(encoder, 256)
821
+ * encoding.writeVarString(encoder, 'Hello world!')
822
+ * const buf = encoding.toUint8Array(encoder)
823
+ * ```
824
+ *
825
+ * ```js
826
+ * // decoding step
827
+ * const decoder = decoding.createDecoder(buf)
828
+ * decoding.readVarUint(decoder) // => 256
829
+ * decoding.readVarString(decoder) // => 'Hello world!'
830
+ * decoding.hasContent(decoder) // => false - all data is read
831
+ * ```
832
+ *
833
+ * @module encoding
834
+ */
835
+
836
+
837
+ /**
838
+ * Write one byte to the encoder.
839
+ *
840
+ * @function
841
+ * @param {Encoder} encoder
842
+ * @param {number} num The byte that is to be encoded.
843
+ */
844
+ const write$1 = (encoder, num) => {
845
+ const bufferLen = encoder.cbuf.length;
846
+ if (encoder.cpos === bufferLen) {
847
+ encoder.bufs.push(encoder.cbuf);
848
+ encoder.cbuf = new Uint8Array(bufferLen * 2);
849
+ encoder.cpos = 0;
850
+ }
851
+ encoder.cbuf[encoder.cpos++] = num;
852
+ };
853
+
854
+ /**
855
+ * Write a variable length unsigned integer. Max encodable integer is 2^53.
856
+ *
857
+ * @function
858
+ * @param {Encoder} encoder
859
+ * @param {number} num The number that is to be encoded.
860
+ */
861
+ const writeVarUint$1 = (encoder, num) => {
862
+ while (num > BITS7$1) {
863
+ write$1(encoder, BIT8$1 | (BITS7$1 & num));
864
+ num = floor$1(num / 128); // shift >>> 7
865
+ }
866
+ write$1(encoder, BITS7$1 & num);
867
+ };
868
+
869
+ /**
870
+ * A cache to store strings temporarily
871
+ */
872
+ const _strBuffer$1 = new Uint8Array(30000);
873
+ const _maxStrBSize$1 = _strBuffer$1.length / 3;
874
+
875
+ /**
876
+ * Write a variable length string.
877
+ *
878
+ * @function
879
+ * @param {Encoder} encoder
880
+ * @param {String} str The string that is to be encoded.
881
+ */
882
+ const _writeVarStringNative$1 = (encoder, str) => {
883
+ if (str.length < _maxStrBSize$1) {
884
+ // We can encode the string into the existing buffer
885
+ /* c8 ignore next */
886
+ const written = utf8TextEncoder$1.encodeInto(str, _strBuffer$1).written || 0;
887
+ writeVarUint$1(encoder, written);
888
+ for (let i = 0; i < written; i++) {
889
+ write$1(encoder, _strBuffer$1[i]);
890
+ }
891
+ } else {
892
+ writeVarUint8Array$1(encoder, encodeUtf8$1(str));
893
+ }
894
+ };
895
+
896
+ /**
897
+ * Write a variable length string.
898
+ *
899
+ * @function
900
+ * @param {Encoder} encoder
901
+ * @param {String} str The string that is to be encoded.
902
+ */
903
+ const _writeVarStringPolyfill$1 = (encoder, str) => {
904
+ const encodedString = unescape(encodeURIComponent(str));
905
+ const len = encodedString.length;
906
+ writeVarUint$1(encoder, len);
907
+ for (let i = 0; i < len; i++) {
908
+ write$1(encoder, /** @type {number} */ (encodedString.codePointAt(i)));
909
+ }
910
+ };
911
+
912
+ /**
913
+ * Write a variable length string.
914
+ *
915
+ * @function
916
+ * @param {Encoder} encoder
917
+ * @param {String} str The string that is to be encoded.
918
+ */
919
+ /* c8 ignore next */
920
+ const writeVarString$1 = (utf8TextEncoder$1 && /** @type {any} */ (utf8TextEncoder$1).encodeInto) ? _writeVarStringNative$1 : _writeVarStringPolyfill$1;
921
+
922
+ /**
923
+ * Append fixed-length Uint8Array to the encoder.
924
+ *
925
+ * @function
926
+ * @param {Encoder} encoder
927
+ * @param {Uint8Array} uint8Array
928
+ */
929
+ const writeUint8Array$1 = (encoder, uint8Array) => {
930
+ const bufferLen = encoder.cbuf.length;
931
+ const cpos = encoder.cpos;
932
+ const leftCopyLen = min$1(bufferLen - cpos, uint8Array.length);
933
+ const rightCopyLen = uint8Array.length - leftCopyLen;
934
+ encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
935
+ encoder.cpos += leftCopyLen;
936
+ if (rightCopyLen > 0) {
937
+ // Still something to write, write right half..
938
+ // Append new buffer
939
+ encoder.bufs.push(encoder.cbuf);
940
+ // must have at least size of remaining buffer
941
+ encoder.cbuf = new Uint8Array(max$1(bufferLen * 2, rightCopyLen));
942
+ // copy array
943
+ encoder.cbuf.set(uint8Array.subarray(leftCopyLen));
944
+ encoder.cpos = rightCopyLen;
945
+ }
946
+ };
947
+
948
+ /**
949
+ * Append an Uint8Array to Encoder.
950
+ *
951
+ * @function
952
+ * @param {Encoder} encoder
953
+ * @param {Uint8Array} uint8Array
954
+ */
955
+ const writeVarUint8Array$1 = (encoder, uint8Array) => {
956
+ writeVarUint$1(encoder, uint8Array.byteLength);
957
+ writeUint8Array$1(encoder, uint8Array);
958
+ };
959
+
960
+ /**
961
+ * Error helpers.
962
+ *
963
+ * @module error
964
+ */
965
+
966
+ /**
967
+ * @param {string} s
968
+ * @return {Error}
969
+ */
970
+ /* c8 ignore next */
971
+ const create$3 = s => new Error(s);
972
+
973
+ /**
974
+ * Efficient schema-less binary decoding with support for variable length encoding.
975
+ *
976
+ * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.
977
+ *
978
+ * Encodes numbers in little-endian order (least to most significant byte order)
979
+ * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)
980
+ * which is also used in Protocol Buffers.
981
+ *
982
+ * ```js
983
+ * // encoding step
984
+ * const encoder = encoding.createEncoder()
985
+ * encoding.writeVarUint(encoder, 256)
986
+ * encoding.writeVarString(encoder, 'Hello world!')
987
+ * const buf = encoding.toUint8Array(encoder)
988
+ * ```
989
+ *
990
+ * ```js
991
+ * // decoding step
992
+ * const decoder = decoding.createDecoder(buf)
993
+ * decoding.readVarUint(decoder) // => 256
994
+ * decoding.readVarString(decoder) // => 'Hello world!'
995
+ * decoding.hasContent(decoder) // => false - all data is read
996
+ * ```
997
+ *
998
+ * @module decoding
999
+ */
1000
+
1001
+
1002
+ const errorUnexpectedEndOfArray$1 = create$3('Unexpected end of array');
1003
+ const errorIntegerOutOfRange$1 = create$3('Integer out of Range');
1004
+
1005
+ /**
1006
+ * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.
1007
+ *
1008
+ * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.
1009
+ * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.
1010
+ *
1011
+ * @function
1012
+ * @param {Decoder} decoder The decoder instance
1013
+ * @param {number} len The length of bytes to read
1014
+ * @return {Uint8Array}
1015
+ */
1016
+ const readUint8Array$1 = (decoder, len) => {
1017
+ const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len);
1018
+ decoder.pos += len;
1019
+ return view
1020
+ };
1021
+
1022
+ /**
1023
+ * Read variable length Uint8Array.
1024
+ *
1025
+ * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.
1026
+ * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.
1027
+ *
1028
+ * @function
1029
+ * @param {Decoder} decoder
1030
+ * @return {Uint8Array}
1031
+ */
1032
+ const readVarUint8Array$1 = decoder => readUint8Array$1(decoder, readVarUint$1(decoder));
1033
+
1034
+ /**
1035
+ * Read one byte as unsigned integer.
1036
+ * @function
1037
+ * @param {Decoder} decoder The decoder instance
1038
+ * @return {number} Unsigned 8-bit integer
1039
+ */
1040
+ const readUint8$1 = decoder => decoder.arr[decoder.pos++];
1041
+
1042
+ /**
1043
+ * Read unsigned integer (32bit) with variable length.
1044
+ * 1/8th of the storage is used as encoding overhead.
1045
+ * * numbers < 2^7 is stored in one bytlength
1046
+ * * numbers < 2^14 is stored in two bylength
1047
+ *
1048
+ * @function
1049
+ * @param {Decoder} decoder
1050
+ * @return {number} An unsigned integer.length
1051
+ */
1052
+ const readVarUint$1 = decoder => {
1053
+ let num = 0;
1054
+ let mult = 1;
1055
+ const len = decoder.arr.length;
1056
+ while (decoder.pos < len) {
1057
+ const r = decoder.arr[decoder.pos++];
1058
+ // num = num | ((r & binary.BITS7) << len)
1059
+ num = num + (r & BITS7$1) * mult; // shift $r << (7*#iterations) and add it to num
1060
+ mult *= 128; // next iteration, shift 7 "more" to the left
1061
+ if (r < BIT8$1) {
1062
+ return num
1063
+ }
1064
+ /* c8 ignore start */
1065
+ if (num > MAX_SAFE_INTEGER$1) {
1066
+ throw errorIntegerOutOfRange$1
1067
+ }
1068
+ /* c8 ignore stop */
1069
+ }
1070
+ throw errorUnexpectedEndOfArray$1
1071
+ };
1072
+
1073
+ /**
1074
+ * We don't test this function anymore as we use native decoding/encoding by default now.
1075
+ * Better not modify this anymore..
1076
+ *
1077
+ * Transforming utf8 to a string is pretty expensive. The code performs 10x better
1078
+ * when String.fromCodePoint is fed with all characters as arguments.
1079
+ * But most environments have a maximum number of arguments per functions.
1080
+ * For effiency reasons we apply a maximum of 10000 characters at once.
1081
+ *
1082
+ * @function
1083
+ * @param {Decoder} decoder
1084
+ * @return {String} The read String.
1085
+ */
1086
+ /* c8 ignore start */
1087
+ const _readVarStringPolyfill$1 = decoder => {
1088
+ let remainingLen = readVarUint$1(decoder);
1089
+ if (remainingLen === 0) {
1090
+ return ''
1091
+ } else {
1092
+ let encodedString = String.fromCodePoint(readUint8$1(decoder)); // remember to decrease remainingLen
1093
+ if (--remainingLen < 100) { // do not create a Uint8Array for small strings
1094
+ while (remainingLen--) {
1095
+ encodedString += String.fromCodePoint(readUint8$1(decoder));
1096
+ }
1097
+ } else {
1098
+ while (remainingLen > 0) {
1099
+ const nextLen = remainingLen < 10000 ? remainingLen : 10000;
1100
+ // this is dangerous, we create a fresh array view from the existing buffer
1101
+ const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen);
1102
+ decoder.pos += nextLen;
1103
+ // Starting with ES5.1 we can supply a generic array-like object as arguments
1104
+ encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes));
1105
+ remainingLen -= nextLen;
1106
+ }
1107
+ }
1108
+ return decodeURIComponent(escape(encodedString))
1109
+ }
1110
+ };
1111
+ /* c8 ignore stop */
1112
+
1113
+ /**
1114
+ * @function
1115
+ * @param {Decoder} decoder
1116
+ * @return {String} The read String
1117
+ */
1118
+ const _readVarStringNative$1 = decoder =>
1119
+ /** @type any */ (utf8TextDecoder$1).decode(readVarUint8Array$1(decoder));
1120
+
1121
+ /**
1122
+ * Read string of variable length
1123
+ * * varUint is used to store the length of the string
1124
+ *
1125
+ * @function
1126
+ * @param {Decoder} decoder
1127
+ * @return {String} The read String
1128
+ *
1129
+ */
1130
+ /* c8 ignore next */
1131
+ const readVarString$1 = utf8TextDecoder$1 ? _readVarStringNative$1 : _readVarStringPolyfill$1;
1132
+
1133
+ var AuthMessageType;
1134
+ (function (AuthMessageType) {
1135
+ AuthMessageType[AuthMessageType["Token"] = 0] = "Token";
1136
+ AuthMessageType[AuthMessageType["PermissionDenied"] = 1] = "PermissionDenied";
1137
+ AuthMessageType[AuthMessageType["Authenticated"] = 2] = "Authenticated";
1138
+ })(AuthMessageType || (AuthMessageType = {}));
1139
+ const writeAuthentication = (encoder, auth) => {
1140
+ writeVarUint$1(encoder, AuthMessageType.Token);
1141
+ writeVarString$1(encoder, auth);
1142
+ };
1143
+ const readAuthMessage = (decoder, sendToken, permissionDeniedHandler, authenticatedHandler) => {
1144
+ switch (readVarUint$1(decoder)) {
1145
+ case AuthMessageType.Token: {
1146
+ sendToken();
1147
+ break;
1148
+ }
1149
+ case AuthMessageType.PermissionDenied: {
1150
+ permissionDeniedHandler(readVarString$1(decoder));
1151
+ break;
1152
+ }
1153
+ case AuthMessageType.Authenticated: {
1154
+ authenticatedHandler(readVarString$1(decoder));
1155
+ break;
1156
+ }
1157
+ }
1158
+ };
1159
+
1160
+ const awarenessStatesToArray = (states) => {
1161
+ return Array.from(states.entries()).map(([key, value]) => {
1162
+ return {
1163
+ clientId: key,
1164
+ ...value,
1165
+ };
1166
+ });
1167
+ };
1168
+
1169
+ /**
1170
+ * State of the WebSocket connection.
1171
+ * https://developer.mozilla.org/de/docs/Web/API/WebSocket/readyState
1172
+ */
1173
+ var WsReadyStates;
1174
+ (function (WsReadyStates) {
1175
+ WsReadyStates[WsReadyStates["Connecting"] = 0] = "Connecting";
1176
+ WsReadyStates[WsReadyStates["Open"] = 1] = "Open";
1177
+ WsReadyStates[WsReadyStates["Closing"] = 2] = "Closing";
1178
+ WsReadyStates[WsReadyStates["Closed"] = 3] = "Closed";
1179
+ })(WsReadyStates || (WsReadyStates = {}));
1180
+
1181
+ function applyDefaults(options) {
1182
+ if (!options) {
1183
+ options = {};
1184
+ }
1185
+ return {
1186
+ delay: (options.delay === undefined) ? 200 : options.delay,
1187
+ initialDelay: (options.initialDelay === undefined) ? 0 : options.initialDelay,
1188
+ minDelay: (options.minDelay === undefined) ? 0 : options.minDelay,
1189
+ maxDelay: (options.maxDelay === undefined) ? 0 : options.maxDelay,
1190
+ factor: (options.factor === undefined) ? 0 : options.factor,
1191
+ maxAttempts: (options.maxAttempts === undefined) ? 3 : options.maxAttempts,
1192
+ timeout: (options.timeout === undefined) ? 0 : options.timeout,
1193
+ jitter: (options.jitter === true),
1194
+ initialJitter: (options.initialJitter === true),
1195
+ handleError: (options.handleError === undefined) ? null : options.handleError,
1196
+ handleTimeout: (options.handleTimeout === undefined) ? null : options.handleTimeout,
1197
+ beforeAttempt: (options.beforeAttempt === undefined) ? null : options.beforeAttempt,
1198
+ calculateDelay: (options.calculateDelay === undefined) ? null : options.calculateDelay
1199
+ };
1200
+ }
1201
+ async function sleep(delay) {
1202
+ return new Promise((resolve) => setTimeout(resolve, delay));
1203
+ }
1204
+ function defaultCalculateDelay(context, options) {
1205
+ let delay = options.delay;
1206
+ if (delay === 0) {
1207
+ // no delay between attempts
1208
+ return 0;
1209
+ }
1210
+ if (options.factor) {
1211
+ delay *= Math.pow(options.factor, context.attemptNum - 1);
1212
+ if (options.maxDelay !== 0) {
1213
+ delay = Math.min(delay, options.maxDelay);
1214
+ }
1215
+ }
1216
+ if (options.jitter) {
1217
+ // Jitter will result in a random value between `minDelay` and
1218
+ // calculated delay for a given attempt.
1219
+ // See https://www.awsarchitectureblog.com/2015/03/backoff.html
1220
+ // We're using the "full jitter" strategy.
1221
+ const min = Math.ceil(options.minDelay);
1222
+ const max = Math.floor(delay);
1223
+ delay = Math.floor(Math.random() * (max - min + 1)) + min;
1224
+ }
1225
+ return Math.round(delay);
1226
+ }
1227
+ async function retry(attemptFunc, attemptOptions) {
1228
+ const options = applyDefaults(attemptOptions);
1229
+ for (const prop of [
1230
+ 'delay',
1231
+ 'initialDelay',
1232
+ 'minDelay',
1233
+ 'maxDelay',
1234
+ 'maxAttempts',
1235
+ 'timeout'
1236
+ ]) {
1237
+ const value = options[prop];
1238
+ if (!Number.isInteger(value) || (value < 0)) {
1239
+ throw new Error(`Value for ${prop} must be an integer greater than or equal to 0`);
1240
+ }
1241
+ }
1242
+ if ((options.factor.constructor !== Number) || (options.factor < 0)) {
1243
+ throw new Error(`Value for factor must be a number greater than or equal to 0`);
1244
+ }
1245
+ if (options.delay < options.minDelay) {
1246
+ throw new Error(`delay cannot be less than minDelay (delay: ${options.delay}, minDelay: ${options.minDelay}`);
1247
+ }
1248
+ const context = {
1249
+ attemptNum: 0,
1250
+ attemptsRemaining: options.maxAttempts ? options.maxAttempts : -1,
1251
+ aborted: false,
1252
+ abort() {
1253
+ context.aborted = true;
1254
+ }
1255
+ };
1256
+ const calculateDelay = options.calculateDelay || defaultCalculateDelay;
1257
+ async function makeAttempt() {
1258
+ if (options.beforeAttempt) {
1259
+ options.beforeAttempt(context, options);
1260
+ }
1261
+ if (context.aborted) {
1262
+ const err = new Error(`Attempt aborted`);
1263
+ err.code = 'ATTEMPT_ABORTED';
1264
+ throw err;
1265
+ }
1266
+ const onError = async (err) => {
1267
+ if (options.handleError) {
1268
+ await options.handleError(err, context, options);
1269
+ }
1270
+ if (context.aborted || (context.attemptsRemaining === 0)) {
1271
+ throw err;
1272
+ }
1273
+ // We are about to try again so increment attempt number
1274
+ context.attemptNum++;
1275
+ const delay = calculateDelay(context, options);
1276
+ if (delay) {
1277
+ await sleep(delay);
1278
+ }
1279
+ return makeAttempt();
1280
+ };
1281
+ if (context.attemptsRemaining > 0) {
1282
+ context.attemptsRemaining--;
1283
+ }
1284
+ if (options.timeout) {
1285
+ return new Promise((resolve, reject) => {
1286
+ const timer = setTimeout(() => {
1287
+ if (options.handleTimeout) {
1288
+ // If calling handleTimeout throws an error that is not wrapped in a promise
1289
+ // we want to catch the error and reject.
1290
+ try {
1291
+ resolve(options.handleTimeout(context, options));
1292
+ }
1293
+ catch (e) {
1294
+ reject(e);
1295
+ }
1296
+ }
1297
+ else {
1298
+ const err = new Error(`Retry timeout (attemptNum: ${context.attemptNum}, timeout: ${options.timeout})`);
1299
+ err.code = 'ATTEMPT_TIMEOUT';
1300
+ reject(err);
1301
+ }
1302
+ }, options.timeout);
1303
+ attemptFunc(context, options).then((result) => {
1304
+ clearTimeout(timer);
1305
+ resolve(result);
1306
+ }).catch((err) => {
1307
+ clearTimeout(timer);
1308
+ // Calling resolve with a Promise that rejects here will result
1309
+ // in an unhandled rejection. Calling `reject` with errors
1310
+ // does not result in an unhandled rejection
1311
+ onError(err).then(resolve).catch(reject);
1312
+ });
1313
+ });
1314
+ }
1315
+ else {
1316
+ // No timeout provided so wait indefinitely for the returned promise
1317
+ // to be resolved.
1318
+ return attemptFunc(context, options).catch(onError);
1319
+ }
1320
+ }
1321
+ const initialDelay = options.calculateDelay
1322
+ ? options.calculateDelay(context, options)
1323
+ : options.initialDelay;
1324
+ if (initialDelay) {
1325
+ await sleep(initialDelay);
1326
+ }
1327
+ if (context.attemptNum < 1 && options.initialJitter) {
1328
+ const delay = calculateDelay(context, options);
1329
+ if (delay) {
1330
+ await sleep(delay);
1331
+ }
1332
+ }
1333
+ return makeAttempt();
1334
+ }
1335
+
1336
+ /**
1337
+ * Common Math expressions.
1338
+ *
1339
+ * @module math
1340
+ */
1341
+
1342
+ const floor = Math.floor;
1343
+
1344
+ /**
1345
+ * @function
1346
+ * @param {number} a
1347
+ * @param {number} b
1348
+ * @return {number} The smaller element of a and b
1349
+ */
1350
+ const min = (a, b) => a < b ? a : b;
1351
+
1352
+ /**
1353
+ * @function
1354
+ * @param {number} a
1355
+ * @param {number} b
1356
+ * @return {number} The bigger element of a and b
1357
+ */
1358
+ const max = (a, b) => a > b ? a : b;
1359
+
1360
+ /* eslint-env browser */
1361
+
1362
+ const BIT7 = 64;
1363
+ const BIT8 = 128;
1364
+ const BITS6 = 63;
1365
+ const BITS7 = 127;
1366
+
1367
+ /**
1368
+ * Utility helpers for working with numbers.
1369
+ *
1370
+ * @module number
1371
+ */
1372
+
1373
+
1374
+ const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
1375
+
1376
+ /**
1377
+ * Utility module to work with sets.
1378
+ *
1379
+ * @module set
1380
+ */
1381
+
1382
+ const create$2 = () => new Set();
1383
+
1384
+ /**
1385
+ * Utility module to work with Arrays.
1386
+ *
1387
+ * @module array
1388
+ */
1389
+
1390
+
1391
+ /**
1392
+ * Transforms something array-like to an actual Array.
1393
+ *
1394
+ * @function
1395
+ * @template T
1396
+ * @param {ArrayLike<T>|Iterable<T>} arraylike
1397
+ * @return {T}
1398
+ */
1399
+ const from = Array.from;
1400
+
1401
+ /**
1402
+ * @param {string} str
1403
+ * @return {Uint8Array}
1404
+ */
1405
+ const _encodeUtf8Polyfill = str => {
1406
+ const encodedString = unescape(encodeURIComponent(str));
1407
+ const len = encodedString.length;
1408
+ const buf = new Uint8Array(len);
1409
+ for (let i = 0; i < len; i++) {
1410
+ buf[i] = /** @type {number} */ (encodedString.codePointAt(i));
1411
+ }
1412
+ return buf
1413
+ };
1414
+
1415
+ /* c8 ignore next */
1416
+ const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null);
1417
+
1418
+ /**
1419
+ * @param {string} str
1420
+ * @return {Uint8Array}
1421
+ */
1422
+ const _encodeUtf8Native = str => utf8TextEncoder.encode(str);
1423
+
1424
+ /**
1425
+ * @param {string} str
1426
+ * @return {Uint8Array}
1427
+ */
1428
+ /* c8 ignore next */
1429
+ const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill;
1430
+
1431
+ /* c8 ignore next */
1432
+ let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
1433
+
1434
+ /* c8 ignore start */
1435
+ if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {
1436
+ // Safari doesn't handle BOM correctly.
1437
+ // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.
1438
+ // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and
1439
+ // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call
1440
+ // Another issue is that from then on no BOM chars are recognized anymore
1441
+ /* c8 ignore next */
1442
+ utf8TextDecoder = null;
1443
+ }
1444
+
1445
+ /**
1446
+ * Efficient schema-less binary encoding with support for variable length encoding.
1447
+ *
1448
+ * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.
1449
+ *
1450
+ * Encodes numbers in little-endian order (least to most significant byte order)
1451
+ * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)
1452
+ * which is also used in Protocol Buffers.
1453
+ *
1454
+ * ```js
1455
+ * // encoding step
1456
+ * const encoder = encoding.createEncoder()
1457
+ * encoding.writeVarUint(encoder, 256)
1458
+ * encoding.writeVarString(encoder, 'Hello world!')
1459
+ * const buf = encoding.toUint8Array(encoder)
1460
+ * ```
1461
+ *
1462
+ * ```js
1463
+ * // decoding step
1464
+ * const decoder = decoding.createDecoder(buf)
1465
+ * decoding.readVarUint(decoder) // => 256
1466
+ * decoding.readVarString(decoder) // => 'Hello world!'
1467
+ * decoding.hasContent(decoder) // => false - all data is read
1468
+ * ```
1469
+ *
1470
+ * @module encoding
1471
+ */
1472
+
1473
+
1474
+ /**
1475
+ * A BinaryEncoder handles the encoding to an Uint8Array.
1476
+ */
1477
+ class Encoder {
1478
+ constructor () {
1479
+ this.cpos = 0;
1480
+ this.cbuf = new Uint8Array(100);
1481
+ /**
1482
+ * @type {Array<Uint8Array>}
1483
+ */
1484
+ this.bufs = [];
1485
+ }
1486
+ }
1487
+
1488
+ /**
1489
+ * @function
1490
+ * @return {Encoder}
1491
+ */
1492
+ const createEncoder = () => new Encoder();
1493
+
1494
+ /**
1495
+ * The current length of the encoded data.
1496
+ *
1497
+ * @function
1498
+ * @param {Encoder} encoder
1499
+ * @return {number}
1500
+ */
1501
+ const length$1 = encoder => {
1502
+ let len = encoder.cpos;
1503
+ for (let i = 0; i < encoder.bufs.length; i++) {
1504
+ len += encoder.bufs[i].length;
1505
+ }
1506
+ return len
1507
+ };
1508
+
1509
+ /**
1510
+ * Transform to Uint8Array.
1511
+ *
1512
+ * @function
1513
+ * @param {Encoder} encoder
1514
+ * @return {Uint8Array} The created ArrayBuffer.
1515
+ */
1516
+ const toUint8Array = encoder => {
1517
+ const uint8arr = new Uint8Array(length$1(encoder));
1518
+ let curPos = 0;
1519
+ for (let i = 0; i < encoder.bufs.length; i++) {
1520
+ const d = encoder.bufs[i];
1521
+ uint8arr.set(d, curPos);
1522
+ curPos += d.length;
1523
+ }
1524
+ uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos);
1525
+ return uint8arr
1526
+ };
1527
+
1528
+ /**
1529
+ * Write one byte to the encoder.
1530
+ *
1531
+ * @function
1532
+ * @param {Encoder} encoder
1533
+ * @param {number} num The byte that is to be encoded.
1534
+ */
1535
+ const write = (encoder, num) => {
1536
+ const bufferLen = encoder.cbuf.length;
1537
+ if (encoder.cpos === bufferLen) {
1538
+ encoder.bufs.push(encoder.cbuf);
1539
+ encoder.cbuf = new Uint8Array(bufferLen * 2);
1540
+ encoder.cpos = 0;
1541
+ }
1542
+ encoder.cbuf[encoder.cpos++] = num;
1543
+ };
1544
+
1545
+ /**
1546
+ * Write a variable length unsigned integer. Max encodable integer is 2^53.
1547
+ *
1548
+ * @function
1549
+ * @param {Encoder} encoder
1550
+ * @param {number} num The number that is to be encoded.
1551
+ */
1552
+ const writeVarUint = (encoder, num) => {
1553
+ while (num > BITS7) {
1554
+ write(encoder, BIT8 | (BITS7 & num));
1555
+ num = floor(num / 128); // shift >>> 7
1556
+ }
1557
+ write(encoder, BITS7 & num);
1558
+ };
1559
+
1560
+ /**
1561
+ * A cache to store strings temporarily
1562
+ */
1563
+ const _strBuffer = new Uint8Array(30000);
1564
+ const _maxStrBSize = _strBuffer.length / 3;
1565
+
1566
+ /**
1567
+ * Write a variable length string.
1568
+ *
1569
+ * @function
1570
+ * @param {Encoder} encoder
1571
+ * @param {String} str The string that is to be encoded.
1572
+ */
1573
+ const _writeVarStringNative = (encoder, str) => {
1574
+ if (str.length < _maxStrBSize) {
1575
+ // We can encode the string into the existing buffer
1576
+ /* c8 ignore next */
1577
+ const written = utf8TextEncoder.encodeInto(str, _strBuffer).written || 0;
1578
+ writeVarUint(encoder, written);
1579
+ for (let i = 0; i < written; i++) {
1580
+ write(encoder, _strBuffer[i]);
1581
+ }
1582
+ } else {
1583
+ writeVarUint8Array(encoder, encodeUtf8(str));
1584
+ }
1585
+ };
1586
+
1587
+ /**
1588
+ * Write a variable length string.
1589
+ *
1590
+ * @function
1591
+ * @param {Encoder} encoder
1592
+ * @param {String} str The string that is to be encoded.
1593
+ */
1594
+ const _writeVarStringPolyfill = (encoder, str) => {
1595
+ const encodedString = unescape(encodeURIComponent(str));
1596
+ const len = encodedString.length;
1597
+ writeVarUint(encoder, len);
1598
+ for (let i = 0; i < len; i++) {
1599
+ write(encoder, /** @type {number} */ (encodedString.codePointAt(i)));
1600
+ }
1601
+ };
1602
+
1603
+ /**
1604
+ * Write a variable length string.
1605
+ *
1606
+ * @function
1607
+ * @param {Encoder} encoder
1608
+ * @param {String} str The string that is to be encoded.
1609
+ */
1610
+ /* c8 ignore next */
1611
+ const writeVarString = (utf8TextEncoder && /** @type {any} */ (utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill;
1612
+
1613
+ /**
1614
+ * Append fixed-length Uint8Array to the encoder.
1615
+ *
1616
+ * @function
1617
+ * @param {Encoder} encoder
1618
+ * @param {Uint8Array} uint8Array
1619
+ */
1620
+ const writeUint8Array = (encoder, uint8Array) => {
1621
+ const bufferLen = encoder.cbuf.length;
1622
+ const cpos = encoder.cpos;
1623
+ const leftCopyLen = min(bufferLen - cpos, uint8Array.length);
1624
+ const rightCopyLen = uint8Array.length - leftCopyLen;
1625
+ encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
1626
+ encoder.cpos += leftCopyLen;
1627
+ if (rightCopyLen > 0) {
1628
+ // Still something to write, write right half..
1629
+ // Append new buffer
1630
+ encoder.bufs.push(encoder.cbuf);
1631
+ // must have at least size of remaining buffer
1632
+ encoder.cbuf = new Uint8Array(max(bufferLen * 2, rightCopyLen));
1633
+ // copy array
1634
+ encoder.cbuf.set(uint8Array.subarray(leftCopyLen));
1635
+ encoder.cpos = rightCopyLen;
1636
+ }
1637
+ };
1638
+
1639
+ /**
1640
+ * Append an Uint8Array to Encoder.
1641
+ *
1642
+ * @function
1643
+ * @param {Encoder} encoder
1644
+ * @param {Uint8Array} uint8Array
1645
+ */
1646
+ const writeVarUint8Array = (encoder, uint8Array) => {
1647
+ writeVarUint(encoder, uint8Array.byteLength);
1648
+ writeUint8Array(encoder, uint8Array);
1649
+ };
1650
+
1651
+ /**
1652
+ * Error helpers.
1653
+ *
1654
+ * @module error
1655
+ */
1656
+
1657
+ /**
1658
+ * @param {string} s
1659
+ * @return {Error}
1660
+ */
1661
+ /* c8 ignore next */
1662
+ const create$1 = s => new Error(s);
1663
+
1664
+ /**
1665
+ * Efficient schema-less binary decoding with support for variable length encoding.
1666
+ *
1667
+ * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.
1668
+ *
1669
+ * Encodes numbers in little-endian order (least to most significant byte order)
1670
+ * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)
1671
+ * which is also used in Protocol Buffers.
1672
+ *
1673
+ * ```js
1674
+ * // encoding step
1675
+ * const encoder = encoding.createEncoder()
1676
+ * encoding.writeVarUint(encoder, 256)
1677
+ * encoding.writeVarString(encoder, 'Hello world!')
1678
+ * const buf = encoding.toUint8Array(encoder)
1679
+ * ```
1680
+ *
1681
+ * ```js
1682
+ * // decoding step
1683
+ * const decoder = decoding.createDecoder(buf)
1684
+ * decoding.readVarUint(decoder) // => 256
1685
+ * decoding.readVarString(decoder) // => 'Hello world!'
1686
+ * decoding.hasContent(decoder) // => false - all data is read
1687
+ * ```
1688
+ *
1689
+ * @module decoding
1690
+ */
1691
+
1692
+
1693
+ const errorUnexpectedEndOfArray = create$1('Unexpected end of array');
1694
+ const errorIntegerOutOfRange = create$1('Integer out of Range');
1695
+
1696
+ /**
1697
+ * A Decoder handles the decoding of an Uint8Array.
1698
+ */
1699
+ class Decoder {
1700
+ /**
1701
+ * @param {Uint8Array} uint8Array Binary data to decode
1702
+ */
1703
+ constructor (uint8Array) {
1704
+ /**
1705
+ * Decoding target.
1706
+ *
1707
+ * @type {Uint8Array}
1708
+ */
1709
+ this.arr = uint8Array;
1710
+ /**
1711
+ * Current decoding position.
1712
+ *
1713
+ * @type {number}
1714
+ */
1715
+ this.pos = 0;
1716
+ }
1717
+ }
1718
+
1719
+ /**
1720
+ * @function
1721
+ * @param {Uint8Array} uint8Array
1722
+ * @return {Decoder}
1723
+ */
1724
+ const createDecoder = uint8Array => new Decoder(uint8Array);
1725
+
1726
+ /**
1727
+ * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.
1728
+ *
1729
+ * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.
1730
+ * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.
1731
+ *
1732
+ * @function
1733
+ * @param {Decoder} decoder The decoder instance
1734
+ * @param {number} len The length of bytes to read
1735
+ * @return {Uint8Array}
1736
+ */
1737
+ const readUint8Array = (decoder, len) => {
1738
+ const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len);
1739
+ decoder.pos += len;
1740
+ return view
1741
+ };
1742
+
1743
+ /**
1744
+ * Read variable length Uint8Array.
1745
+ *
1746
+ * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.
1747
+ * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.
1748
+ *
1749
+ * @function
1750
+ * @param {Decoder} decoder
1751
+ * @return {Uint8Array}
1752
+ */
1753
+ const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder));
1754
+
1755
+ /**
1756
+ * Read one byte as unsigned integer.
1757
+ * @function
1758
+ * @param {Decoder} decoder The decoder instance
1759
+ * @return {number} Unsigned 8-bit integer
1760
+ */
1761
+ const readUint8 = decoder => decoder.arr[decoder.pos++];
1762
+
1763
+ /**
1764
+ * Read unsigned integer (32bit) with variable length.
1765
+ * 1/8th of the storage is used as encoding overhead.
1766
+ * * numbers < 2^7 is stored in one bytlength
1767
+ * * numbers < 2^14 is stored in two bylength
1768
+ *
1769
+ * @function
1770
+ * @param {Decoder} decoder
1771
+ * @return {number} An unsigned integer.length
1772
+ */
1773
+ const readVarUint = decoder => {
1774
+ let num = 0;
1775
+ let mult = 1;
1776
+ const len = decoder.arr.length;
1777
+ while (decoder.pos < len) {
1778
+ const r = decoder.arr[decoder.pos++];
1779
+ // num = num | ((r & binary.BITS7) << len)
1780
+ num = num + (r & BITS7) * mult; // shift $r << (7*#iterations) and add it to num
1781
+ mult *= 128; // next iteration, shift 7 "more" to the left
1782
+ if (r < BIT8) {
1783
+ return num
1784
+ }
1785
+ /* c8 ignore start */
1786
+ if (num > MAX_SAFE_INTEGER) {
1787
+ throw errorIntegerOutOfRange
1788
+ }
1789
+ /* c8 ignore stop */
1790
+ }
1791
+ throw errorUnexpectedEndOfArray
1792
+ };
1793
+
1794
+ /**
1795
+ * Read signed integer (32bit) with variable length.
1796
+ * 1/8th of the storage is used as encoding overhead.
1797
+ * * numbers < 2^7 is stored in one bytlength
1798
+ * * numbers < 2^14 is stored in two bylength
1799
+ * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.
1800
+ *
1801
+ * @function
1802
+ * @param {Decoder} decoder
1803
+ * @return {number} An unsigned integer.length
1804
+ */
1805
+ const readVarInt = decoder => {
1806
+ let r = decoder.arr[decoder.pos++];
1807
+ let num = r & BITS6;
1808
+ let mult = 64;
1809
+ const sign = (r & BIT7) > 0 ? -1 : 1;
1810
+ if ((r & BIT8) === 0) {
1811
+ // don't continue reading
1812
+ return sign * num
1813
+ }
1814
+ const len = decoder.arr.length;
1815
+ while (decoder.pos < len) {
1816
+ r = decoder.arr[decoder.pos++];
1817
+ // num = num | ((r & binary.BITS7) << len)
1818
+ num = num + (r & BITS7) * mult;
1819
+ mult *= 128;
1820
+ if (r < BIT8) {
1821
+ return sign * num
1822
+ }
1823
+ /* c8 ignore start */
1824
+ if (num > MAX_SAFE_INTEGER) {
1825
+ throw errorIntegerOutOfRange
1826
+ }
1827
+ /* c8 ignore stop */
1828
+ }
1829
+ throw errorUnexpectedEndOfArray
1830
+ };
1831
+
1832
+ /**
1833
+ * We don't test this function anymore as we use native decoding/encoding by default now.
1834
+ * Better not modify this anymore..
1835
+ *
1836
+ * Transforming utf8 to a string is pretty expensive. The code performs 10x better
1837
+ * when String.fromCodePoint is fed with all characters as arguments.
1838
+ * But most environments have a maximum number of arguments per functions.
1839
+ * For effiency reasons we apply a maximum of 10000 characters at once.
1840
+ *
1841
+ * @function
1842
+ * @param {Decoder} decoder
1843
+ * @return {String} The read String.
1844
+ */
1845
+ /* c8 ignore start */
1846
+ const _readVarStringPolyfill = decoder => {
1847
+ let remainingLen = readVarUint(decoder);
1848
+ if (remainingLen === 0) {
1849
+ return ''
1850
+ } else {
1851
+ let encodedString = String.fromCodePoint(readUint8(decoder)); // remember to decrease remainingLen
1852
+ if (--remainingLen < 100) { // do not create a Uint8Array for small strings
1853
+ while (remainingLen--) {
1854
+ encodedString += String.fromCodePoint(readUint8(decoder));
1855
+ }
1856
+ } else {
1857
+ while (remainingLen > 0) {
1858
+ const nextLen = remainingLen < 10000 ? remainingLen : 10000;
1859
+ // this is dangerous, we create a fresh array view from the existing buffer
1860
+ const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen);
1861
+ decoder.pos += nextLen;
1862
+ // Starting with ES5.1 we can supply a generic array-like object as arguments
1863
+ encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes));
1864
+ remainingLen -= nextLen;
1865
+ }
1866
+ }
1867
+ return decodeURIComponent(escape(encodedString))
1868
+ }
1869
+ };
1870
+ /* c8 ignore stop */
1871
+
1872
+ /**
1873
+ * @function
1874
+ * @param {Decoder} decoder
1875
+ * @return {String} The read String
1876
+ */
1877
+ const _readVarStringNative = decoder =>
1878
+ /** @type any */ (utf8TextDecoder).decode(readVarUint8Array(decoder));
1879
+
1880
+ /**
1881
+ * Read string of variable length
1882
+ * * varUint is used to store the length of the string
1883
+ *
1884
+ * @function
1885
+ * @param {Decoder} decoder
1886
+ * @return {String} The read String
1887
+ *
1888
+ */
1889
+ /* c8 ignore next */
1890
+ const readVarString = utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill;
1891
+
1892
+ /**
1893
+ * Look ahead and read varString without incrementing position
1894
+ *
1895
+ * @function
1896
+ * @param {Decoder} decoder
1897
+ * @return {string}
1898
+ */
1899
+ const peekVarString = decoder => {
1900
+ const pos = decoder.pos;
1901
+ const s = readVarString(decoder);
1902
+ decoder.pos = pos;
1903
+ return s
1904
+ };
1905
+
1906
+ /**
1907
+ * Utility module to work with time.
1908
+ *
1909
+ * @module time
1910
+ */
1911
+
1912
+
1913
+ /**
1914
+ * Return current unix time.
1915
+ *
1916
+ * @return {number}
1917
+ */
1918
+ const getUnixTime = Date.now;
1919
+
1920
+ /**
1921
+ * Utility module to work with key-value stores.
1922
+ *
1923
+ * @module map
1924
+ */
1925
+
1926
+ /**
1927
+ * Creates a new Map instance.
1928
+ *
1929
+ * @function
1930
+ * @return {Map<any, any>}
1931
+ *
1932
+ * @function
1933
+ */
1934
+ const create = () => new Map();
1935
+
1936
+ /**
1937
+ * Get map property. Create T if property is undefined and set T on map.
1938
+ *
1939
+ * ```js
1940
+ * const listeners = map.setIfUndefined(events, 'eventName', set.create)
1941
+ * listeners.add(listener)
1942
+ * ```
1943
+ *
1944
+ * @function
1945
+ * @template {Map<any, any>} MAP
1946
+ * @template {MAP extends Map<any,infer V> ? function():V : unknown} CF
1947
+ * @param {MAP} map
1948
+ * @param {MAP extends Map<infer K,any> ? K : unknown} key
1949
+ * @param {CF} createT
1950
+ * @return {ReturnType<CF>}
1951
+ */
1952
+ const setIfUndefined = (map, key, createT) => {
1953
+ let set = map.get(key);
1954
+ if (set === undefined) {
1955
+ map.set(key, set = createT());
1956
+ }
1957
+ return set
1958
+ };
1959
+
1960
+ /**
1961
+ * Observable class prototype.
1962
+ *
1963
+ * @module observable
1964
+ */
1965
+
1966
+
1967
+ /* c8 ignore start */
1968
+ /**
1969
+ * Handles named events.
1970
+ *
1971
+ * @deprecated
1972
+ * @template N
1973
+ */
1974
+ class Observable {
1975
+ constructor () {
1976
+ /**
1977
+ * Some desc.
1978
+ * @type {Map<N, any>}
1979
+ */
1980
+ this._observers = create();
1981
+ }
1982
+
1983
+ /**
1984
+ * @param {N} name
1985
+ * @param {function} f
1986
+ */
1987
+ on (name, f) {
1988
+ setIfUndefined(this._observers, name, create$2).add(f);
1989
+ }
1990
+
1991
+ /**
1992
+ * @param {N} name
1993
+ * @param {function} f
1994
+ */
1995
+ once (name, f) {
1996
+ /**
1997
+ * @param {...any} args
1998
+ */
1999
+ const _f = (...args) => {
2000
+ this.off(name, _f);
2001
+ f(...args);
2002
+ };
2003
+ this.on(name, _f);
2004
+ }
2005
+
2006
+ /**
2007
+ * @param {N} name
2008
+ * @param {function} f
2009
+ */
2010
+ off (name, f) {
2011
+ const observers = this._observers.get(name);
2012
+ if (observers !== undefined) {
2013
+ observers.delete(f);
2014
+ if (observers.size === 0) {
2015
+ this._observers.delete(name);
2016
+ }
2017
+ }
2018
+ }
2019
+
2020
+ /**
2021
+ * Emit a named event. All registered event listeners that listen to the
2022
+ * specified name will receive the event.
2023
+ *
2024
+ * @todo This should catch exceptions
2025
+ *
2026
+ * @param {N} name The event name.
2027
+ * @param {Array<any>} args The arguments that are applied to the event listener.
2028
+ */
2029
+ emit (name, args) {
2030
+ // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called.
2031
+ return from((this._observers.get(name) || create()).values()).forEach(f => f(...args))
2032
+ }
2033
+
2034
+ destroy () {
2035
+ this._observers = create();
2036
+ }
2037
+ }
2038
+ /* c8 ignore end */
2039
+
2040
+ /**
2041
+ * Utility functions for working with EcmaScript objects.
2042
+ *
2043
+ * @module object
2044
+ */
2045
+
2046
+
2047
+ /**
2048
+ * @param {Object<string,any>} obj
2049
+ */
2050
+ const keys = Object.keys;
2051
+
2052
+ /**
2053
+ * @deprecated use object.size instead
2054
+ * @param {Object<string,any>} obj
2055
+ * @return {number}
2056
+ */
2057
+ const length = obj => keys(obj).length;
2058
+
2059
+ /**
2060
+ * Calls `Object.prototype.hasOwnProperty`.
2061
+ *
2062
+ * @param {any} obj
2063
+ * @param {string|symbol} key
2064
+ * @return {boolean}
2065
+ */
2066
+ const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
2067
+
2068
+ /**
2069
+ * Common functions and function call helpers.
2070
+ *
2071
+ * @module function
2072
+ */
2073
+
2074
+
2075
+ /**
2076
+ * @template T
2077
+ *
2078
+ * @param {T} a
2079
+ * @param {T} b
2080
+ * @return {boolean}
2081
+ */
2082
+ const equalityStrict = (a, b) => a === b;
2083
+
2084
+ /* c8 ignore start */
2085
+
2086
+ /**
2087
+ * @param {any} a
2088
+ * @param {any} b
2089
+ * @return {boolean}
2090
+ */
2091
+ const equalityDeep = (a, b) => {
2092
+ if (a == null || b == null) {
2093
+ return equalityStrict(a, b)
2094
+ }
2095
+ if (a.constructor !== b.constructor) {
2096
+ return false
2097
+ }
2098
+ if (a === b) {
2099
+ return true
2100
+ }
2101
+ switch (a.constructor) {
2102
+ case ArrayBuffer:
2103
+ a = new Uint8Array(a);
2104
+ b = new Uint8Array(b);
2105
+ // eslint-disable-next-line no-fallthrough
2106
+ case Uint8Array: {
2107
+ if (a.byteLength !== b.byteLength) {
2108
+ return false
2109
+ }
2110
+ for (let i = 0; i < a.length; i++) {
2111
+ if (a[i] !== b[i]) {
2112
+ return false
2113
+ }
2114
+ }
2115
+ break
2116
+ }
2117
+ case Set: {
2118
+ if (a.size !== b.size) {
2119
+ return false
2120
+ }
2121
+ for (const value of a) {
2122
+ if (!b.has(value)) {
2123
+ return false
2124
+ }
2125
+ }
2126
+ break
2127
+ }
2128
+ case Map: {
2129
+ if (a.size !== b.size) {
2130
+ return false
2131
+ }
2132
+ for (const key of a.keys()) {
2133
+ if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {
2134
+ return false
2135
+ }
2136
+ }
2137
+ break
2138
+ }
2139
+ case Object:
2140
+ if (length(a) !== length(b)) {
2141
+ return false
2142
+ }
2143
+ for (const key in a) {
2144
+ if (!hasProperty(a, key) || !equalityDeep(a[key], b[key])) {
2145
+ return false
2146
+ }
2147
+ }
2148
+ break
2149
+ case Array:
2150
+ if (a.length !== b.length) {
2151
+ return false
2152
+ }
2153
+ for (let i = 0; i < a.length; i++) {
2154
+ if (!equalityDeep(a[i], b[i])) {
2155
+ return false
2156
+ }
2157
+ }
2158
+ break
2159
+ default:
2160
+ return false
2161
+ }
2162
+ return true
2163
+ };
2164
+
2165
+ /**
2166
+ * @module awareness-protocol
2167
+ */
2168
+
2169
+
2170
+ const outdatedTimeout = 30000;
2171
+
2172
+ /**
2173
+ * @typedef {Object} MetaClientState
2174
+ * @property {number} MetaClientState.clock
2175
+ * @property {number} MetaClientState.lastUpdated unix timestamp
2176
+ */
2177
+
2178
+ /**
2179
+ * The Awareness class implements a simple shared state protocol that can be used for non-persistent data like awareness information
2180
+ * (cursor, username, status, ..). Each client can update its own local state and listen to state changes of
2181
+ * remote clients. Every client may set a state of a remote peer to `null` to mark the client as offline.
2182
+ *
2183
+ * Each client is identified by a unique client id (something we borrow from `doc.clientID`). A client can override
2184
+ * its own state by propagating a message with an increasing timestamp (`clock`). If such a message is received, it is
2185
+ * applied if the known state of that client is older than the new state (`clock < newClock`). If a client thinks that
2186
+ * a remote client is offline, it may propagate a message with
2187
+ * `{ clock: currentClientClock, state: null, client: remoteClient }`. If such a
2188
+ * message is received, and the known clock of that client equals the received clock, it will override the state with `null`.
2189
+ *
2190
+ * Before a client disconnects, it should propagate a `null` state with an updated clock.
2191
+ *
2192
+ * Awareness states must be updated every 30 seconds. Otherwise the Awareness instance will delete the client state.
2193
+ *
2194
+ * @extends {Observable<string>}
2195
+ */
2196
+ class Awareness extends Observable {
2197
+ /**
2198
+ * @param {Y.Doc} doc
2199
+ */
2200
+ constructor (doc) {
2201
+ super();
2202
+ this.doc = doc;
2203
+ /**
2204
+ * @type {number}
2205
+ */
2206
+ this.clientID = doc.clientID;
2207
+ /**
2208
+ * Maps from client id to client state
2209
+ * @type {Map<number, Object<string, any>>}
2210
+ */
2211
+ this.states = new Map();
2212
+ /**
2213
+ * @type {Map<number, MetaClientState>}
2214
+ */
2215
+ this.meta = new Map();
2216
+ this._checkInterval = /** @type {any} */ (setInterval(() => {
2217
+ const now = getUnixTime();
2218
+ if (this.getLocalState() !== null && (outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ (this.meta.get(this.clientID)).lastUpdated)) {
2219
+ // renew local clock
2220
+ this.setLocalState(this.getLocalState());
2221
+ }
2222
+ /**
2223
+ * @type {Array<number>}
2224
+ */
2225
+ const remove = [];
2226
+ this.meta.forEach((meta, clientid) => {
2227
+ if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) {
2228
+ remove.push(clientid);
2229
+ }
2230
+ });
2231
+ if (remove.length > 0) {
2232
+ removeAwarenessStates(this, remove, 'timeout');
2233
+ }
2234
+ }, floor(outdatedTimeout / 10)));
2235
+ doc.on('destroy', () => {
2236
+ this.destroy();
2237
+ });
2238
+ this.setLocalState({});
2239
+ }
2240
+
2241
+ destroy () {
2242
+ this.emit('destroy', [this]);
2243
+ this.setLocalState(null);
2244
+ super.destroy();
2245
+ clearInterval(this._checkInterval);
2246
+ }
2247
+
2248
+ /**
2249
+ * @return {Object<string,any>|null}
2250
+ */
2251
+ getLocalState () {
2252
+ return this.states.get(this.clientID) || null
2253
+ }
2254
+
2255
+ /**
2256
+ * @param {Object<string,any>|null} state
2257
+ */
2258
+ setLocalState (state) {
2259
+ const clientID = this.clientID;
2260
+ const currLocalMeta = this.meta.get(clientID);
2261
+ const clock = currLocalMeta === undefined ? 0 : currLocalMeta.clock + 1;
2262
+ const prevState = this.states.get(clientID);
2263
+ if (state === null) {
2264
+ this.states.delete(clientID);
2265
+ } else {
2266
+ this.states.set(clientID, state);
2267
+ }
2268
+ this.meta.set(clientID, {
2269
+ clock,
2270
+ lastUpdated: getUnixTime()
2271
+ });
2272
+ const added = [];
2273
+ const updated = [];
2274
+ const filteredUpdated = [];
2275
+ const removed = [];
2276
+ if (state === null) {
2277
+ removed.push(clientID);
2278
+ } else if (prevState == null) {
2279
+ if (state != null) {
2280
+ added.push(clientID);
2281
+ }
2282
+ } else {
2283
+ updated.push(clientID);
2284
+ if (!equalityDeep(prevState, state)) {
2285
+ filteredUpdated.push(clientID);
2286
+ }
2287
+ }
2288
+ if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {
2289
+ this.emit('change', [{ added, updated: filteredUpdated, removed }, 'local']);
2290
+ }
2291
+ this.emit('update', [{ added, updated, removed }, 'local']);
2292
+ }
2293
+
2294
+ /**
2295
+ * @param {string} field
2296
+ * @param {any} value
2297
+ */
2298
+ setLocalStateField (field, value) {
2299
+ const state = this.getLocalState();
2300
+ if (state !== null) {
2301
+ this.setLocalState({
2302
+ ...state,
2303
+ [field]: value
2304
+ });
2305
+ }
2306
+ }
2307
+
2308
+ /**
2309
+ * @return {Map<number,Object<string,any>>}
2310
+ */
2311
+ getStates () {
2312
+ return this.states
2313
+ }
2314
+ }
2315
+
2316
+ /**
2317
+ * Mark (remote) clients as inactive and remove them from the list of active peers.
2318
+ * This change will be propagated to remote clients.
2319
+ *
2320
+ * @param {Awareness} awareness
2321
+ * @param {Array<number>} clients
2322
+ * @param {any} origin
2323
+ */
2324
+ const removeAwarenessStates = (awareness, clients, origin) => {
2325
+ const removed = [];
2326
+ for (let i = 0; i < clients.length; i++) {
2327
+ const clientID = clients[i];
2328
+ if (awareness.states.has(clientID)) {
2329
+ awareness.states.delete(clientID);
2330
+ if (clientID === awareness.clientID) {
2331
+ const curMeta = /** @type {MetaClientState} */ (awareness.meta.get(clientID));
2332
+ awareness.meta.set(clientID, {
2333
+ clock: curMeta.clock + 1,
2334
+ lastUpdated: getUnixTime()
2335
+ });
2336
+ }
2337
+ removed.push(clientID);
2338
+ }
2339
+ }
2340
+ if (removed.length > 0) {
2341
+ awareness.emit('change', [{ added: [], updated: [], removed }, origin]);
2342
+ awareness.emit('update', [{ added: [], updated: [], removed }, origin]);
2343
+ }
2344
+ };
2345
+
2346
+ /**
2347
+ * @param {Awareness} awareness
2348
+ * @param {Array<number>} clients
2349
+ * @return {Uint8Array}
2350
+ */
2351
+ const encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {
2352
+ const len = clients.length;
2353
+ const encoder = createEncoder();
2354
+ writeVarUint(encoder, len);
2355
+ for (let i = 0; i < len; i++) {
2356
+ const clientID = clients[i];
2357
+ const state = states.get(clientID) || null;
2358
+ const clock = /** @type {MetaClientState} */ (awareness.meta.get(clientID)).clock;
2359
+ writeVarUint(encoder, clientID);
2360
+ writeVarUint(encoder, clock);
2361
+ writeVarString(encoder, JSON.stringify(state));
2362
+ }
2363
+ return toUint8Array(encoder)
2364
+ };
2365
+
2366
+ /**
2367
+ * @param {Awareness} awareness
2368
+ * @param {Uint8Array} update
2369
+ * @param {any} origin This will be added to the emitted change event
2370
+ */
2371
+ const applyAwarenessUpdate = (awareness, update, origin) => {
2372
+ const decoder = createDecoder(update);
2373
+ const timestamp = getUnixTime();
2374
+ const added = [];
2375
+ const updated = [];
2376
+ const filteredUpdated = [];
2377
+ const removed = [];
2378
+ const len = readVarUint(decoder);
2379
+ for (let i = 0; i < len; i++) {
2380
+ const clientID = readVarUint(decoder);
2381
+ let clock = readVarUint(decoder);
2382
+ const state = JSON.parse(readVarString(decoder));
2383
+ const clientMeta = awareness.meta.get(clientID);
2384
+ const prevState = awareness.states.get(clientID);
2385
+ const currClock = clientMeta === undefined ? 0 : clientMeta.clock;
2386
+ if (currClock < clock || (currClock === clock && state === null && awareness.states.has(clientID))) {
2387
+ if (state === null) {
2388
+ // never let a remote client remove this local state
2389
+ if (clientID === awareness.clientID && awareness.getLocalState() != null) {
2390
+ // remote client removed the local state. Do not remote state. Broadcast a message indicating
2391
+ // that this client still exists by increasing the clock
2392
+ clock++;
2393
+ } else {
2394
+ awareness.states.delete(clientID);
2395
+ }
2396
+ } else {
2397
+ awareness.states.set(clientID, state);
2398
+ }
2399
+ awareness.meta.set(clientID, {
2400
+ clock,
2401
+ lastUpdated: timestamp
2402
+ });
2403
+ if (clientMeta === undefined && state !== null) {
2404
+ added.push(clientID);
2405
+ } else if (clientMeta !== undefined && state === null) {
2406
+ removed.push(clientID);
2407
+ } else if (state !== null) {
2408
+ if (!equalityDeep(state, prevState)) {
2409
+ filteredUpdated.push(clientID);
2410
+ }
2411
+ updated.push(clientID);
2412
+ }
2413
+ }
2414
+ }
2415
+ if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {
2416
+ awareness.emit('change', [{
2417
+ added, updated: filteredUpdated, removed
2418
+ }, origin]);
2419
+ }
2420
+ if (added.length > 0 || updated.length > 0 || removed.length > 0) {
2421
+ awareness.emit('update', [{
2422
+ added, updated, removed
2423
+ }, origin]);
2424
+ }
2425
+ };
2426
+
2427
+ class EventEmitter {
2428
+ constructor() {
2429
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
2430
+ this.callbacks = {};
2431
+ }
2432
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
2433
+ on(event, fn) {
2434
+ if (!this.callbacks[event]) {
2435
+ this.callbacks[event] = [];
2436
+ }
2437
+ this.callbacks[event].push(fn);
2438
+ return this;
2439
+ }
2440
+ emit(event, ...args) {
2441
+ const callbacks = this.callbacks[event];
2442
+ if (callbacks) {
2443
+ callbacks.forEach((callback) => callback.apply(this, args));
2444
+ }
2445
+ return this;
2446
+ }
2447
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
2448
+ off(event, fn) {
2449
+ const callbacks = this.callbacks[event];
2450
+ if (callbacks) {
2451
+ if (fn) {
2452
+ this.callbacks[event] = callbacks.filter((callback) => callback !== fn);
2453
+ }
2454
+ else {
2455
+ delete this.callbacks[event];
2456
+ }
2457
+ }
2458
+ return this;
2459
+ }
2460
+ removeAllListeners() {
2461
+ this.callbacks = {};
2462
+ }
2463
+ }
2464
+
2465
+ class IncomingMessage {
2466
+ constructor(data) {
2467
+ this.data = data;
2468
+ this.encoder = createEncoder();
2469
+ this.decoder = createDecoder(new Uint8Array(this.data));
2470
+ }
2471
+ peekVarString() {
2472
+ return peekVarString(this.decoder);
2473
+ }
2474
+ readVarUint() {
2475
+ return readVarUint(this.decoder);
2476
+ }
2477
+ readVarString() {
2478
+ return readVarString(this.decoder);
2479
+ }
2480
+ readVarUint8Array() {
2481
+ return readVarUint8Array(this.decoder);
2482
+ }
2483
+ writeVarUint(type) {
2484
+ return writeVarUint(this.encoder, type);
2485
+ }
2486
+ writeVarString(string) {
2487
+ return writeVarString(this.encoder, string);
2488
+ }
2489
+ writeVarUint8Array(data) {
2490
+ return writeVarUint8Array(this.encoder, data);
2491
+ }
2492
+ length() {
2493
+ return length$1(this.encoder);
2494
+ }
2495
+ }
2496
+
2497
+ var MessageType;
2498
+ (function (MessageType) {
2499
+ MessageType[MessageType["Sync"] = 0] = "Sync";
2500
+ MessageType[MessageType["Awareness"] = 1] = "Awareness";
2501
+ MessageType[MessageType["Auth"] = 2] = "Auth";
2502
+ MessageType[MessageType["QueryAwareness"] = 3] = "QueryAwareness";
2503
+ MessageType[MessageType["Stateless"] = 5] = "Stateless";
2504
+ MessageType[MessageType["CLOSE"] = 7] = "CLOSE";
2505
+ MessageType[MessageType["SyncStatus"] = 8] = "SyncStatus";
2506
+ })(MessageType || (MessageType = {}));
2507
+ var WebSocketStatus;
2508
+ (function (WebSocketStatus) {
2509
+ WebSocketStatus["Connecting"] = "connecting";
2510
+ WebSocketStatus["Connected"] = "connected";
2511
+ WebSocketStatus["Disconnected"] = "disconnected";
2512
+ })(WebSocketStatus || (WebSocketStatus = {}));
2513
+
2514
+ class OutgoingMessage {
2515
+ constructor() {
2516
+ this.encoder = createEncoder();
2517
+ }
2518
+ get(args) {
2519
+ return args.encoder;
2520
+ }
2521
+ toUint8Array() {
2522
+ return toUint8Array(this.encoder);
2523
+ }
2524
+ }
2525
+
2526
+ class CloseMessage extends OutgoingMessage {
2527
+ constructor() {
2528
+ super(...arguments);
2529
+ this.type = MessageType.CLOSE;
2530
+ this.description = "Ask the server to close the connection";
2531
+ }
2532
+ get(args) {
2533
+ writeVarString(this.encoder, args.documentName);
2534
+ writeVarUint(this.encoder, this.type);
2535
+ return this.encoder;
2536
+ }
2537
+ }
2538
+
2539
+ class HocuspocusProviderWebsocket extends EventEmitter {
2540
+ constructor(configuration) {
2541
+ super();
2542
+ this.messageQueue = [];
2543
+ this.configuration = {
2544
+ url: "",
2545
+ autoConnect: true,
2546
+ preserveTrailingSlash: false,
2547
+ // @ts-ignore
2548
+ document: undefined,
2549
+ WebSocketPolyfill: undefined,
2550
+ // TODO: this should depend on awareness.outdatedTime
2551
+ messageReconnectTimeout: 30000,
2552
+ // 1 second
2553
+ delay: 1000,
2554
+ // instant
2555
+ initialDelay: 0,
2556
+ // double the delay each time
2557
+ factor: 2,
2558
+ // unlimited retries
2559
+ maxAttempts: 0,
2560
+ // wait at least 1 second
2561
+ minDelay: 1000,
2562
+ // at least every 30 seconds
2563
+ maxDelay: 30000,
2564
+ // randomize
2565
+ jitter: true,
2566
+ // retry forever
2567
+ timeout: 0,
2568
+ onOpen: () => null,
2569
+ onConnect: () => null,
2570
+ onMessage: () => null,
2571
+ onOutgoingMessage: () => null,
2572
+ onStatus: () => null,
2573
+ onDisconnect: () => null,
2574
+ onClose: () => null,
2575
+ onDestroy: () => null,
2576
+ onAwarenessUpdate: () => null,
2577
+ onAwarenessChange: () => null,
2578
+ handleTimeout: null,
2579
+ providerMap: new Map(),
2580
+ };
2581
+ this.webSocket = null;
2582
+ this.webSocketHandlers = {};
2583
+ this.shouldConnect = true;
2584
+ this.status = WebSocketStatus.Disconnected;
2585
+ this.lastMessageReceived = 0;
2586
+ this.identifier = 0;
2587
+ this.intervals = {
2588
+ connectionChecker: null,
2589
+ };
2590
+ this.connectionAttempt = null;
2591
+ this.receivedOnOpenPayload = undefined;
2592
+ this.closeTries = 0;
2593
+ this.setConfiguration(configuration);
2594
+ this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill
2595
+ ? configuration.WebSocketPolyfill
2596
+ : WebSocket;
2597
+ this.on("open", this.configuration.onOpen);
2598
+ this.on("open", this.onOpen.bind(this));
2599
+ this.on("connect", this.configuration.onConnect);
2600
+ this.on("message", this.configuration.onMessage);
2601
+ this.on("outgoingMessage", this.configuration.onOutgoingMessage);
2602
+ this.on("status", this.configuration.onStatus);
2603
+ this.on("disconnect", this.configuration.onDisconnect);
2604
+ this.on("close", this.configuration.onClose);
2605
+ this.on("destroy", this.configuration.onDestroy);
2606
+ this.on("awarenessUpdate", this.configuration.onAwarenessUpdate);
2607
+ this.on("awarenessChange", this.configuration.onAwarenessChange);
2608
+ this.on("close", this.onClose.bind(this));
2609
+ this.on("message", this.onMessage.bind(this));
2610
+ this.intervals.connectionChecker = setInterval(this.checkConnection.bind(this), this.configuration.messageReconnectTimeout / 10);
2611
+ if (this.shouldConnect) {
2612
+ this.connect();
2613
+ }
2614
+ }
2615
+ async onOpen(event) {
2616
+ this.status = WebSocketStatus.Connected;
2617
+ this.emit("status", { status: WebSocketStatus.Connected });
2618
+ this.cancelWebsocketRetry = undefined;
2619
+ this.receivedOnOpenPayload = event;
2620
+ }
2621
+ attach(provider) {
2622
+ this.configuration.providerMap.set(provider.configuration.name, provider);
2623
+ if (this.status === WebSocketStatus.Disconnected && this.shouldConnect) {
2624
+ this.connect();
2625
+ }
2626
+ if (this.receivedOnOpenPayload &&
2627
+ this.status === WebSocketStatus.Connected) {
2628
+ provider.onOpen(this.receivedOnOpenPayload);
2629
+ }
2630
+ }
2631
+ detach(provider) {
2632
+ if (this.configuration.providerMap.has(provider.configuration.name)) {
2633
+ provider.send(CloseMessage, {
2634
+ documentName: provider.configuration.name,
2635
+ });
2636
+ this.configuration.providerMap.delete(provider.configuration.name);
2637
+ }
2638
+ }
2639
+ setConfiguration(configuration = {}) {
2640
+ this.configuration = { ...this.configuration, ...configuration };
2641
+ if (!this.configuration.autoConnect) {
2642
+ this.shouldConnect = false;
2643
+ }
2644
+ }
2645
+ async connect() {
2646
+ if (this.status === WebSocketStatus.Connected) {
2647
+ return;
2648
+ }
2649
+ // Always cancel any previously initiated connection retryer instances
2650
+ if (this.cancelWebsocketRetry) {
2651
+ this.cancelWebsocketRetry();
2652
+ this.cancelWebsocketRetry = undefined;
2653
+ }
2654
+ this.receivedOnOpenPayload = undefined;
2655
+ this.shouldConnect = true;
2656
+ const abortableRetry = () => {
2657
+ let cancelAttempt = false;
2658
+ const retryPromise = retry(this.createWebSocketConnection.bind(this), {
2659
+ delay: this.configuration.delay,
2660
+ initialDelay: this.configuration.initialDelay,
2661
+ factor: this.configuration.factor,
2662
+ maxAttempts: this.configuration.maxAttempts,
2663
+ minDelay: this.configuration.minDelay,
2664
+ maxDelay: this.configuration.maxDelay,
2665
+ jitter: this.configuration.jitter,
2666
+ timeout: this.configuration.timeout,
2667
+ handleTimeout: this.configuration.handleTimeout,
2668
+ beforeAttempt: (context) => {
2669
+ if (!this.shouldConnect || cancelAttempt) {
2670
+ context.abort();
2671
+ }
2672
+ },
2673
+ }).catch((error) => {
2674
+ // If we aborted the connection attempt then don’t throw an error
2675
+ // ref: https://github.com/lifeomic/attempt/blob/master/src/index.ts#L136
2676
+ if (error && error.code !== "ATTEMPT_ABORTED") {
2677
+ throw error;
2678
+ }
2679
+ });
2680
+ return {
2681
+ retryPromise,
2682
+ cancelFunc: () => {
2683
+ cancelAttempt = true;
2684
+ },
2685
+ };
2686
+ };
2687
+ const { retryPromise, cancelFunc } = abortableRetry();
2688
+ this.cancelWebsocketRetry = cancelFunc;
2689
+ return retryPromise;
2690
+ }
2691
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
2692
+ attachWebSocketListeners(ws, reject) {
2693
+ const { identifier } = ws;
2694
+ const onMessageHandler = (payload) => this.emit("message", payload);
2695
+ const onCloseHandler = (payload) => this.emit("close", { event: payload });
2696
+ const onOpenHandler = (payload) => this.emit("open", payload);
2697
+ const onErrorHandler = (err) => {
2698
+ reject(err);
2699
+ };
2700
+ this.webSocketHandlers[identifier] = {
2701
+ message: onMessageHandler,
2702
+ close: onCloseHandler,
2703
+ open: onOpenHandler,
2704
+ error: onErrorHandler,
2705
+ };
2706
+ const handlers = this.webSocketHandlers[ws.identifier];
2707
+ Object.keys(handlers).forEach((name) => {
2708
+ ws.addEventListener(name, handlers[name]);
2709
+ });
2710
+ }
2711
+ cleanupWebSocket() {
2712
+ if (!this.webSocket) {
2713
+ return;
2714
+ }
2715
+ const { identifier } = this.webSocket;
2716
+ const handlers = this.webSocketHandlers[identifier];
2717
+ Object.keys(handlers).forEach((name) => {
2718
+ var _a;
2719
+ (_a = this.webSocket) === null || _a === void 0 ? void 0 : _a.removeEventListener(name, handlers[name]);
2720
+ delete this.webSocketHandlers[identifier];
2721
+ });
2722
+ this.webSocket.close();
2723
+ this.webSocket = null;
2724
+ }
2725
+ createWebSocketConnection() {
2726
+ return new Promise((resolve, reject) => {
2727
+ if (this.webSocket) {
2728
+ this.messageQueue = [];
2729
+ this.cleanupWebSocket();
2730
+ }
2731
+ this.lastMessageReceived = 0;
2732
+ this.identifier += 1;
2733
+ // Init the WebSocket connection
2734
+ const ws = new this.configuration.WebSocketPolyfill(this.url);
2735
+ ws.binaryType = "arraybuffer";
2736
+ ws.identifier = this.identifier;
2737
+ this.attachWebSocketListeners(ws, reject);
2738
+ this.webSocket = ws;
2739
+ // Reset the status
2740
+ this.status = WebSocketStatus.Connecting;
2741
+ this.emit("status", { status: WebSocketStatus.Connecting });
2742
+ // Store resolve/reject for later use
2743
+ this.connectionAttempt = {
2744
+ resolve,
2745
+ reject,
2746
+ };
2747
+ });
2748
+ }
2749
+ onMessage(event) {
2750
+ var _a;
2751
+ this.resolveConnectionAttempt();
2752
+ this.lastMessageReceived = getUnixTime();
2753
+ const message = new IncomingMessage(event.data);
2754
+ const documentName = message.peekVarString();
2755
+ (_a = this.configuration.providerMap.get(documentName)) === null || _a === void 0 ? void 0 : _a.onMessage(event);
2756
+ }
2757
+ resolveConnectionAttempt() {
2758
+ if (this.connectionAttempt) {
2759
+ this.connectionAttempt.resolve();
2760
+ this.connectionAttempt = null;
2761
+ this.status = WebSocketStatus.Connected;
2762
+ this.emit("status", { status: WebSocketStatus.Connected });
2763
+ this.emit("connect");
2764
+ this.messageQueue.forEach((message) => this.send(message));
2765
+ this.messageQueue = [];
2766
+ }
2767
+ }
2768
+ stopConnectionAttempt() {
2769
+ this.connectionAttempt = null;
2770
+ }
2771
+ rejectConnectionAttempt() {
2772
+ var _a;
2773
+ (_a = this.connectionAttempt) === null || _a === void 0 ? void 0 : _a.reject();
2774
+ this.connectionAttempt = null;
2775
+ }
2776
+ checkConnection() {
2777
+ var _a;
2778
+ // Don’t check the connection when it’s not even established
2779
+ if (this.status !== WebSocketStatus.Connected) {
2780
+ return;
2781
+ }
2782
+ // Don’t close the connection while waiting for the first message
2783
+ if (!this.lastMessageReceived) {
2784
+ return;
2785
+ }
2786
+ // Don’t close the connection when a message was received recently
2787
+ if (this.configuration.messageReconnectTimeout >=
2788
+ getUnixTime() - this.lastMessageReceived) {
2789
+ return;
2790
+ }
2791
+ // No message received in a long time, not even your own
2792
+ // Awareness updates, which are updated every 15 seconds
2793
+ // if awareness is enabled.
2794
+ this.closeTries += 1;
2795
+ // https://bugs.webkit.org/show_bug.cgi?id=247943
2796
+ if (this.closeTries > 2) {
2797
+ this.onClose({
2798
+ event: {
2799
+ code: 4408,
2800
+ reason: "forced",
2801
+ },
2802
+ });
2803
+ this.closeTries = 0;
2804
+ }
2805
+ else {
2806
+ (_a = this.webSocket) === null || _a === void 0 ? void 0 : _a.close();
2807
+ this.messageQueue = [];
2808
+ }
2809
+ }
2810
+ get serverUrl() {
2811
+ if (this.configuration.preserveTrailingSlash) {
2812
+ return this.configuration.url;
2813
+ }
2814
+ // By default, ensure that the URL never ends with /
2815
+ let url = this.configuration.url;
2816
+ while (url[url.length - 1] === "/") {
2817
+ url = url.slice(0, url.length - 1);
2818
+ }
2819
+ return url;
2820
+ }
2821
+ get url() {
2822
+ return this.serverUrl;
2823
+ }
2824
+ disconnect() {
2825
+ this.shouldConnect = false;
2826
+ if (this.webSocket === null) {
2827
+ return;
2828
+ }
2829
+ try {
2830
+ this.webSocket.close();
2831
+ this.messageQueue = [];
2832
+ }
2833
+ catch (e) {
2834
+ console.error(e);
2835
+ }
2836
+ }
2837
+ send(message) {
2838
+ var _a;
2839
+ if (((_a = this.webSocket) === null || _a === void 0 ? void 0 : _a.readyState) === WsReadyStates.Open) {
2840
+ this.webSocket.send(message);
2841
+ }
2842
+ else {
2843
+ this.messageQueue.push(message);
2844
+ }
2845
+ }
2846
+ onClose({ event }) {
2847
+ this.closeTries = 0;
2848
+ this.cleanupWebSocket();
2849
+ if (this.connectionAttempt) {
2850
+ // That connection attempt failed.
2851
+ this.rejectConnectionAttempt();
2852
+ }
2853
+ // Let’s update the connection status.
2854
+ this.status = WebSocketStatus.Disconnected;
2855
+ this.emit("status", { status: WebSocketStatus.Disconnected });
2856
+ this.emit("disconnect", { event });
2857
+ // trigger connect if no retry is running and we want to have a connection
2858
+ if (!this.cancelWebsocketRetry && this.shouldConnect) {
2859
+ setTimeout(() => {
2860
+ this.connect();
2861
+ }, this.configuration.delay);
2862
+ }
2863
+ }
2864
+ destroy() {
2865
+ this.emit("destroy");
2866
+ clearInterval(this.intervals.connectionChecker);
2867
+ // If there is still a connection attempt outstanding then we should stop
2868
+ // it before calling disconnect, otherwise it will be rejected in the onClose
2869
+ // handler and trigger a retry
2870
+ this.stopConnectionAttempt();
2871
+ this.disconnect();
2872
+ this.removeAllListeners();
2873
+ this.cleanupWebSocket();
2874
+ }
2875
+ }
2876
+
2877
+ /**
2878
+ * @module sync-protocol
2879
+ */
2880
+
2881
+
2882
+ /**
2883
+ * @typedef {Map<number, number>} StateMap
2884
+ */
2885
+
2886
+ /**
2887
+ * Core Yjs defines two message types:
2888
+ * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.
2889
+ * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it
2890
+ * received all information from the remote client.
2891
+ *
2892
+ * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection
2893
+ * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both
2894
+ * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.
2895
+ *
2896
+ * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.
2897
+ * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies
2898
+ * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the
2899
+ * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can
2900
+ * easily be implemented on top of http and websockets. 2. The server should only reply to requests, and not initiate them.
2901
+ * Therefore it is necessary that the client initiates the sync.
2902
+ *
2903
+ * Construction of a message:
2904
+ * [messageType : varUint, message definition..]
2905
+ *
2906
+ * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!
2907
+ *
2908
+ * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)
2909
+ */
2910
+
2911
+ const messageYjsSyncStep1 = 0;
2912
+ const messageYjsSyncStep2 = 1;
2913
+ const messageYjsUpdate = 2;
2914
+
2915
+ /**
2916
+ * Create a sync step 1 message based on the state of the current shared document.
2917
+ *
2918
+ * @param {encoding.Encoder} encoder
2919
+ * @param {Y.Doc} doc
2920
+ */
2921
+ const writeSyncStep1 = (encoder, doc) => {
2922
+ writeVarUint(encoder, messageYjsSyncStep1);
2923
+ const sv = Y.encodeStateVector(doc);
2924
+ writeVarUint8Array(encoder, sv);
2925
+ };
2926
+
2927
+ /**
2928
+ * @param {encoding.Encoder} encoder
2929
+ * @param {Y.Doc} doc
2930
+ * @param {Uint8Array} [encodedStateVector]
2931
+ */
2932
+ const writeSyncStep2 = (encoder, doc, encodedStateVector) => {
2933
+ writeVarUint(encoder, messageYjsSyncStep2);
2934
+ writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector));
2935
+ };
2936
+
2937
+ /**
2938
+ * Read SyncStep1 message and reply with SyncStep2.
2939
+ *
2940
+ * @param {decoding.Decoder} decoder The reply to the received message
2941
+ * @param {encoding.Encoder} encoder The received message
2942
+ * @param {Y.Doc} doc
2943
+ */
2944
+ const readSyncStep1 = (decoder, encoder, doc) =>
2945
+ writeSyncStep2(encoder, doc, readVarUint8Array(decoder));
2946
+
2947
+ /**
2948
+ * Read and apply Structs and then DeleteStore to a y instance.
2949
+ *
2950
+ * @param {decoding.Decoder} decoder
2951
+ * @param {Y.Doc} doc
2952
+ * @param {any} transactionOrigin
2953
+ */
2954
+ const readSyncStep2 = (decoder, doc, transactionOrigin) => {
2955
+ try {
2956
+ Y.applyUpdate(doc, readVarUint8Array(decoder), transactionOrigin);
2957
+ } catch (error) {
2958
+ // This catches errors that are thrown by event handlers
2959
+ console.error('Caught error while handling a Yjs update', error);
2960
+ }
2961
+ };
2962
+
2963
+ /**
2964
+ * @param {encoding.Encoder} encoder
2965
+ * @param {Uint8Array} update
2966
+ */
2967
+ const writeUpdate = (encoder, update) => {
2968
+ writeVarUint(encoder, messageYjsUpdate);
2969
+ writeVarUint8Array(encoder, update);
2970
+ };
2971
+
2972
+ /**
2973
+ * Read and apply Structs and then DeleteStore to a y instance.
2974
+ *
2975
+ * @param {decoding.Decoder} decoder
2976
+ * @param {Y.Doc} doc
2977
+ * @param {any} transactionOrigin
2978
+ */
2979
+ const readUpdate = readSyncStep2;
2980
+
2981
+ /**
2982
+ * @param {decoding.Decoder} decoder A message received from another client
2983
+ * @param {encoding.Encoder} encoder The reply message. Does not need to be sent if empty.
2984
+ * @param {Y.Doc} doc
2985
+ * @param {any} transactionOrigin
2986
+ */
2987
+ const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => {
2988
+ const messageType = readVarUint(decoder);
2989
+ switch (messageType) {
2990
+ case messageYjsSyncStep1:
2991
+ readSyncStep1(decoder, encoder, doc);
2992
+ break
2993
+ case messageYjsSyncStep2:
2994
+ readSyncStep2(decoder, doc, transactionOrigin);
2995
+ break
2996
+ case messageYjsUpdate:
2997
+ readUpdate(decoder, doc, transactionOrigin);
2998
+ break
2999
+ default:
3000
+ throw new Error('Unknown message type')
3001
+ }
3002
+ return messageType
3003
+ };
3004
+
3005
+ class MessageReceiver {
3006
+ constructor(message) {
3007
+ this.message = message;
3008
+ }
3009
+ apply(provider, emitSynced) {
3010
+ const { message } = this;
3011
+ const type = message.readVarUint();
3012
+ const emptyMessageLength = message.length();
3013
+ switch (type) {
3014
+ case MessageType.Sync:
3015
+ this.applySyncMessage(provider, emitSynced);
3016
+ break;
3017
+ case MessageType.Awareness:
3018
+ this.applyAwarenessMessage(provider);
3019
+ break;
3020
+ case MessageType.Auth:
3021
+ this.applyAuthMessage(provider);
3022
+ break;
3023
+ case MessageType.QueryAwareness:
3024
+ this.applyQueryAwarenessMessage(provider);
3025
+ break;
3026
+ case MessageType.Stateless:
3027
+ provider.receiveStateless(readVarString(message.decoder));
3028
+ break;
3029
+ case MessageType.SyncStatus:
3030
+ this.applySyncStatusMessage(provider, readVarInt(message.decoder) === 1);
3031
+ break;
3032
+ case MessageType.CLOSE:
3033
+ // eslint-disable-next-line no-case-declarations
3034
+ const event = {
3035
+ code: 1000,
3036
+ reason: readVarString(message.decoder),
3037
+ // @ts-ignore
3038
+ target: provider.configuration.websocketProvider.webSocket,
3039
+ type: "close",
3040
+ };
3041
+ provider.onClose();
3042
+ provider.configuration.onClose({ event });
3043
+ provider.forwardClose({ event });
3044
+ break;
3045
+ default:
3046
+ throw new Error(`Can’t apply message of unknown type: ${type}`);
3047
+ }
3048
+ // Reply
3049
+ if (message.length() > emptyMessageLength + 1) {
3050
+ // length of documentName (considered in emptyMessageLength plus length of yjs sync type, set in applySyncMessage)
3051
+ // @ts-ignore
3052
+ provider.send(OutgoingMessage, { encoder: message.encoder });
3053
+ }
3054
+ }
3055
+ applySyncMessage(provider, emitSynced) {
3056
+ const { message } = this;
3057
+ message.writeVarUint(MessageType.Sync);
3058
+ // Apply update
3059
+ const syncMessageType = readSyncMessage(message.decoder, message.encoder, provider.document, provider);
3060
+ // Synced once we receive Step2
3061
+ if (emitSynced && syncMessageType === messageYjsSyncStep2) {
3062
+ provider.synced = true;
3063
+ }
3064
+ }
3065
+ applySyncStatusMessage(provider, applied) {
3066
+ if (applied) {
3067
+ provider.decrementUnsyncedChanges();
3068
+ }
3069
+ }
3070
+ applyAwarenessMessage(provider) {
3071
+ if (!provider.awareness)
3072
+ return;
3073
+ const { message } = this;
3074
+ applyAwarenessUpdate(provider.awareness, message.readVarUint8Array(), provider);
3075
+ }
3076
+ applyAuthMessage(provider) {
3077
+ const { message } = this;
3078
+ readAuthMessage(message.decoder, provider.sendToken.bind(provider), provider.permissionDeniedHandler.bind(provider), provider.authenticatedHandler.bind(provider));
3079
+ }
3080
+ applyQueryAwarenessMessage(provider) {
3081
+ if (!provider.awareness)
3082
+ return;
3083
+ const { message } = this;
3084
+ message.writeVarUint(MessageType.Awareness);
3085
+ message.writeVarUint8Array(encodeAwarenessUpdate(provider.awareness, Array.from(provider.awareness.getStates().keys())));
3086
+ }
3087
+ }
3088
+
3089
+ class MessageSender {
3090
+ constructor(Message, args = {}) {
3091
+ this.message = new Message();
3092
+ this.encoder = this.message.get(args);
3093
+ }
3094
+ create() {
3095
+ return toUint8Array(this.encoder);
3096
+ }
3097
+ send(webSocket) {
3098
+ webSocket === null || webSocket === void 0 ? void 0 : webSocket.send(this.create());
3099
+ }
3100
+ }
3101
+
3102
+ class AuthenticationMessage extends OutgoingMessage {
3103
+ constructor() {
3104
+ super(...arguments);
3105
+ this.type = MessageType.Auth;
3106
+ this.description = "Authentication";
3107
+ }
3108
+ get(args) {
3109
+ if (typeof args.token === "undefined") {
3110
+ throw new Error("The authentication message requires `token` as an argument.");
3111
+ }
3112
+ writeVarString(this.encoder, args.documentName);
3113
+ writeVarUint(this.encoder, this.type);
3114
+ writeAuthentication(this.encoder, args.token);
3115
+ return this.encoder;
3116
+ }
3117
+ }
3118
+
3119
+ class AwarenessMessage extends OutgoingMessage {
3120
+ constructor() {
3121
+ super(...arguments);
3122
+ this.type = MessageType.Awareness;
3123
+ this.description = "Awareness states update";
3124
+ }
3125
+ get(args) {
3126
+ if (typeof args.awareness === "undefined") {
3127
+ throw new Error("The awareness message requires awareness as an argument");
3128
+ }
3129
+ if (typeof args.clients === "undefined") {
3130
+ throw new Error("The awareness message requires clients as an argument");
3131
+ }
3132
+ writeVarString(this.encoder, args.documentName);
3133
+ writeVarUint(this.encoder, this.type);
3134
+ let awarenessUpdate;
3135
+ if (args.states === undefined) {
3136
+ awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients);
3137
+ }
3138
+ else {
3139
+ awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients, args.states);
3140
+ }
3141
+ writeVarUint8Array(this.encoder, awarenessUpdate);
3142
+ return this.encoder;
3143
+ }
3144
+ }
3145
+
3146
+ class StatelessMessage extends OutgoingMessage {
3147
+ constructor() {
3148
+ super(...arguments);
3149
+ this.type = MessageType.Stateless;
3150
+ this.description = "A stateless message";
3151
+ }
3152
+ get(args) {
3153
+ var _a;
3154
+ writeVarString(this.encoder, args.documentName);
3155
+ writeVarUint(this.encoder, this.type);
3156
+ writeVarString(this.encoder, (_a = args.payload) !== null && _a !== void 0 ? _a : "");
3157
+ return this.encoder;
3158
+ }
3159
+ }
3160
+
3161
+ class SyncStepOneMessage extends OutgoingMessage {
3162
+ constructor() {
3163
+ super(...arguments);
3164
+ this.type = MessageType.Sync;
3165
+ this.description = "First sync step";
3166
+ }
3167
+ get(args) {
3168
+ if (typeof args.document === "undefined") {
3169
+ throw new Error("The sync step one message requires document as an argument");
3170
+ }
3171
+ writeVarString(this.encoder, args.documentName);
3172
+ writeVarUint(this.encoder, this.type);
3173
+ writeSyncStep1(this.encoder, args.document);
3174
+ return this.encoder;
3175
+ }
3176
+ }
3177
+
3178
+ class UpdateMessage extends OutgoingMessage {
3179
+ constructor() {
3180
+ super(...arguments);
3181
+ this.type = MessageType.Sync;
3182
+ this.description = "A document update";
3183
+ }
3184
+ get(args) {
3185
+ writeVarString(this.encoder, args.documentName);
3186
+ writeVarUint(this.encoder, this.type);
3187
+ writeUpdate(this.encoder, args.update);
3188
+ return this.encoder;
3189
+ }
3190
+ }
3191
+
3192
+ class AwarenessError extends Error {
3193
+ constructor() {
3194
+ super(...arguments);
3195
+ this.code = 1001;
3196
+ }
3197
+ }
3198
+ class HocuspocusProvider extends EventEmitter {
3199
+ constructor(configuration) {
3200
+ var _a, _b, _c;
3201
+ super();
3202
+ this.configuration = {
3203
+ name: "",
3204
+ // @ts-ignore
3205
+ document: undefined,
3206
+ // @ts-ignore
3207
+ awareness: undefined,
3208
+ token: null,
3209
+ forceSyncInterval: false,
3210
+ onAuthenticated: () => null,
3211
+ onAuthenticationFailed: () => null,
3212
+ onOpen: () => null,
3213
+ onConnect: () => null,
3214
+ onMessage: () => null,
3215
+ onOutgoingMessage: () => null,
3216
+ onSynced: () => null,
3217
+ onStatus: () => null,
3218
+ onDisconnect: () => null,
3219
+ onClose: () => null,
3220
+ onDestroy: () => null,
3221
+ onAwarenessUpdate: () => null,
3222
+ onAwarenessChange: () => null,
3223
+ onStateless: () => null,
3224
+ onUnsyncedChanges: () => null,
3225
+ };
3226
+ this.isSynced = false;
3227
+ this.unsyncedChanges = 0;
3228
+ this.isAuthenticated = false;
3229
+ this.authorizedScope = undefined;
3230
+ // @internal
3231
+ this.manageSocket = false;
3232
+ this._isAttached = false;
3233
+ this.intervals = {
3234
+ forceSync: null,
3235
+ };
3236
+ this.boundDocumentUpdateHandler = this.documentUpdateHandler.bind(this);
3237
+ this.boundAwarenessUpdateHandler = this.awarenessUpdateHandler.bind(this);
3238
+ this.boundPageHide = this.pageHide.bind(this);
3239
+ this.boundOnOpen = this.onOpen.bind(this);
3240
+ this.boundOnClose = this.onClose.bind(this);
3241
+ this.forwardConnect = () => this.emit("connect");
3242
+ this.forwardStatus = (e) => this.emit("status", e);
3243
+ this.forwardClose = (e) => this.emit("close", e);
3244
+ this.forwardDisconnect = (e) => this.emit("disconnect", e);
3245
+ this.forwardDestroy = () => this.emit("destroy");
3246
+ this.setConfiguration(configuration);
3247
+ this.configuration.document = configuration.document
3248
+ ? configuration.document
3249
+ : new Y.Doc();
3250
+ this.configuration.awareness =
3251
+ configuration.awareness !== undefined
3252
+ ? configuration.awareness
3253
+ : new Awareness(this.document);
3254
+ this.on("open", this.configuration.onOpen);
3255
+ this.on("message", this.configuration.onMessage);
3256
+ this.on("outgoingMessage", this.configuration.onOutgoingMessage);
3257
+ this.on("synced", this.configuration.onSynced);
3258
+ this.on("destroy", this.configuration.onDestroy);
3259
+ this.on("awarenessUpdate", this.configuration.onAwarenessUpdate);
3260
+ this.on("awarenessChange", this.configuration.onAwarenessChange);
3261
+ this.on("stateless", this.configuration.onStateless);
3262
+ this.on("unsyncedChanges", this.configuration.onUnsyncedChanges);
3263
+ this.on("authenticated", this.configuration.onAuthenticated);
3264
+ this.on("authenticationFailed", this.configuration.onAuthenticationFailed);
3265
+ (_a = this.awareness) === null || _a === void 0 ? void 0 : _a.on("update", () => {
3266
+ this.emit("awarenessUpdate", {
3267
+ states: awarenessStatesToArray(this.awareness.getStates()),
3268
+ });
3269
+ });
3270
+ (_b = this.awareness) === null || _b === void 0 ? void 0 : _b.on("change", () => {
3271
+ this.emit("awarenessChange", {
3272
+ states: awarenessStatesToArray(this.awareness.getStates()),
3273
+ });
3274
+ });
3275
+ this.document.on("update", this.boundDocumentUpdateHandler);
3276
+ (_c = this.awareness) === null || _c === void 0 ? void 0 : _c.on("update", this.boundAwarenessUpdateHandler);
3277
+ this.registerEventListeners();
3278
+ if (this.configuration.forceSyncInterval &&
3279
+ typeof this.configuration.forceSyncInterval === "number") {
3280
+ this.intervals.forceSync = setInterval(this.forceSync.bind(this), this.configuration.forceSyncInterval);
3281
+ }
3282
+ if (this.manageSocket) {
3283
+ this.attach();
3284
+ }
3285
+ }
3286
+ setConfiguration(configuration = {}) {
3287
+ if (!configuration.websocketProvider) {
3288
+ this.manageSocket = true;
3289
+ this.configuration.websocketProvider = new HocuspocusProviderWebsocket(configuration);
3290
+ }
3291
+ this.configuration = { ...this.configuration, ...configuration };
3292
+ }
3293
+ get document() {
3294
+ return this.configuration.document;
3295
+ }
3296
+ get isAttached() {
3297
+ return this._isAttached;
3298
+ }
3299
+ get awareness() {
3300
+ return this.configuration.awareness;
3301
+ }
3302
+ get hasUnsyncedChanges() {
3303
+ return this.unsyncedChanges > 0;
3304
+ }
3305
+ resetUnsyncedChanges() {
3306
+ this.unsyncedChanges = 1;
3307
+ this.emit("unsyncedChanges", { number: this.unsyncedChanges });
3308
+ }
3309
+ incrementUnsyncedChanges() {
3310
+ this.unsyncedChanges += 1;
3311
+ this.emit("unsyncedChanges", { number: this.unsyncedChanges });
3312
+ }
3313
+ decrementUnsyncedChanges() {
3314
+ if (this.unsyncedChanges > 0) {
3315
+ this.unsyncedChanges -= 1;
3316
+ }
3317
+ if (this.unsyncedChanges === 0) {
3318
+ this.synced = true;
3319
+ }
3320
+ this.emit("unsyncedChanges", { number: this.unsyncedChanges });
3321
+ }
3322
+ forceSync() {
3323
+ this.resetUnsyncedChanges();
3324
+ this.send(SyncStepOneMessage, {
3325
+ document: this.document,
3326
+ documentName: this.configuration.name,
3327
+ });
3328
+ }
3329
+ pageHide() {
3330
+ if (this.awareness) {
3331
+ removeAwarenessStates(this.awareness, [this.document.clientID], "page hide");
3332
+ }
3333
+ }
3334
+ registerEventListeners() {
3335
+ if (typeof window === "undefined" || !("addEventListener" in window)) {
3336
+ return;
3337
+ }
3338
+ window.addEventListener("pagehide", this.boundPageHide);
3339
+ }
3340
+ sendStateless(payload) {
3341
+ this.send(StatelessMessage, {
3342
+ documentName: this.configuration.name,
3343
+ payload,
3344
+ });
3345
+ }
3346
+ async sendToken() {
3347
+ let token;
3348
+ try {
3349
+ token = await this.getToken();
3350
+ }
3351
+ catch (error) {
3352
+ this.permissionDeniedHandler(`Failed to get token during sendToken(): ${error}`);
3353
+ return;
3354
+ }
3355
+ this.send(AuthenticationMessage, {
3356
+ token: token !== null && token !== void 0 ? token : "",
3357
+ documentName: this.configuration.name,
3358
+ });
3359
+ }
3360
+ documentUpdateHandler(update, origin) {
3361
+ if (origin === this) {
3362
+ return;
3363
+ }
3364
+ this.incrementUnsyncedChanges();
3365
+ this.send(UpdateMessage, { update, documentName: this.configuration.name });
3366
+ }
3367
+ awarenessUpdateHandler({ added, updated, removed }, origin) {
3368
+ const changedClients = added.concat(updated).concat(removed);
3369
+ this.send(AwarenessMessage, {
3370
+ awareness: this.awareness,
3371
+ clients: changedClients,
3372
+ documentName: this.configuration.name,
3373
+ });
3374
+ }
3375
+ /**
3376
+ * Indicates whether a first handshake with the server has been established
3377
+ *
3378
+ * Note: this does not mean all updates from the client have been persisted to the backend. For this,
3379
+ * use `hasUnsyncedChanges`.
3380
+ */
3381
+ get synced() {
3382
+ return this.isSynced;
3383
+ }
3384
+ set synced(state) {
3385
+ if (this.isSynced === state) {
3386
+ return;
3387
+ }
3388
+ this.isSynced = state;
3389
+ if (state) {
3390
+ this.emit("synced", { state });
3391
+ }
3392
+ }
3393
+ receiveStateless(payload) {
3394
+ this.emit("stateless", { payload });
3395
+ }
3396
+ // not needed, but provides backward compatibility with e.g. lexical/yjs
3397
+ async connect() {
3398
+ if (this.manageSocket) {
3399
+ return this.configuration.websocketProvider.connect();
3400
+ }
3401
+ console.warn("HocuspocusProvider::connect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.");
3402
+ }
3403
+ disconnect() {
3404
+ if (this.manageSocket) {
3405
+ return this.configuration.websocketProvider.disconnect();
3406
+ }
3407
+ console.warn("HocuspocusProvider::disconnect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.");
3408
+ }
3409
+ async onOpen(event) {
3410
+ this.isAuthenticated = false;
3411
+ this.emit("open", { event });
3412
+ await this.sendToken();
3413
+ this.startSync();
3414
+ }
3415
+ async getToken() {
3416
+ if (typeof this.configuration.token === "function") {
3417
+ const token = await this.configuration.token();
3418
+ return token;
3419
+ }
3420
+ return this.configuration.token;
3421
+ }
3422
+ startSync() {
3423
+ this.resetUnsyncedChanges();
3424
+ this.send(SyncStepOneMessage, {
3425
+ document: this.document,
3426
+ documentName: this.configuration.name,
3427
+ });
3428
+ if (this.awareness && this.awareness.getLocalState() !== null) {
3429
+ this.send(AwarenessMessage, {
3430
+ awareness: this.awareness,
3431
+ clients: [this.document.clientID],
3432
+ documentName: this.configuration.name,
3433
+ });
3434
+ }
3435
+ }
3436
+ send(message, args) {
3437
+ if (!this._isAttached)
3438
+ return;
3439
+ const messageSender = new MessageSender(message, args);
3440
+ this.emit("outgoingMessage", { message: messageSender.message });
3441
+ messageSender.send(this.configuration.websocketProvider);
3442
+ }
3443
+ onMessage(event) {
3444
+ const message = new IncomingMessage(event.data);
3445
+ const documentName = message.readVarString();
3446
+ message.writeVarString(documentName);
3447
+ this.emit("message", { event, message: new IncomingMessage(event.data) });
3448
+ new MessageReceiver(message).apply(this, true);
3449
+ }
3450
+ onClose() {
3451
+ this.isAuthenticated = false;
3452
+ this.synced = false;
3453
+ // update awareness (all users except local left)
3454
+ if (this.awareness) {
3455
+ removeAwarenessStates(this.awareness, Array.from(this.awareness.getStates().keys()).filter((client) => client !== this.document.clientID), this);
3456
+ }
3457
+ }
3458
+ destroy() {
3459
+ this.emit("destroy");
3460
+ if (this.intervals.forceSync) {
3461
+ clearInterval(this.intervals.forceSync);
3462
+ }
3463
+ if (this.awareness) {
3464
+ removeAwarenessStates(this.awareness, [this.document.clientID], "provider destroy");
3465
+ this.awareness.off("update", this.boundAwarenessUpdateHandler);
3466
+ this.awareness.destroy();
3467
+ }
3468
+ this.document.off("update", this.boundDocumentUpdateHandler);
3469
+ this.removeAllListeners();
3470
+ this.detach();
3471
+ if (this.manageSocket) {
3472
+ this.configuration.websocketProvider.destroy();
3473
+ }
3474
+ if (typeof window === "undefined" || !("removeEventListener" in window)) {
3475
+ return;
3476
+ }
3477
+ window.removeEventListener("pagehide", this.boundPageHide);
3478
+ }
3479
+ detach() {
3480
+ this.configuration.websocketProvider.off("connect", this.configuration.onConnect);
3481
+ this.configuration.websocketProvider.off("connect", this.forwardConnect);
3482
+ this.configuration.websocketProvider.off("status", this.forwardStatus);
3483
+ this.configuration.websocketProvider.off("status", this.configuration.onStatus);
3484
+ this.configuration.websocketProvider.off("open", this.boundOnOpen);
3485
+ this.configuration.websocketProvider.off("close", this.boundOnClose);
3486
+ this.configuration.websocketProvider.off("close", this.configuration.onClose);
3487
+ this.configuration.websocketProvider.off("close", this.forwardClose);
3488
+ this.configuration.websocketProvider.off("disconnect", this.configuration.onDisconnect);
3489
+ this.configuration.websocketProvider.off("disconnect", this.forwardDisconnect);
3490
+ this.configuration.websocketProvider.off("destroy", this.configuration.onDestroy);
3491
+ this.configuration.websocketProvider.off("destroy", this.forwardDestroy);
3492
+ this.configuration.websocketProvider.detach(this);
3493
+ this._isAttached = false;
3494
+ }
3495
+ attach() {
3496
+ if (this._isAttached)
3497
+ return;
3498
+ this.configuration.websocketProvider.on("connect", this.configuration.onConnect);
3499
+ this.configuration.websocketProvider.on("connect", this.forwardConnect);
3500
+ this.configuration.websocketProvider.on("status", this.configuration.onStatus);
3501
+ this.configuration.websocketProvider.on("status", this.forwardStatus);
3502
+ this.configuration.websocketProvider.on("open", this.boundOnOpen);
3503
+ this.configuration.websocketProvider.on("close", this.boundOnClose);
3504
+ this.configuration.websocketProvider.on("close", this.configuration.onClose);
3505
+ this.configuration.websocketProvider.on("close", this.forwardClose);
3506
+ this.configuration.websocketProvider.on("disconnect", this.configuration.onDisconnect);
3507
+ this.configuration.websocketProvider.on("disconnect", this.forwardDisconnect);
3508
+ this.configuration.websocketProvider.on("destroy", this.configuration.onDestroy);
3509
+ this.configuration.websocketProvider.on("destroy", this.forwardDestroy);
3510
+ this.configuration.websocketProvider.attach(this);
3511
+ this._isAttached = true;
3512
+ }
3513
+ permissionDeniedHandler(reason) {
3514
+ this.emit("authenticationFailed", { reason });
3515
+ this.isAuthenticated = false;
3516
+ }
3517
+ authenticatedHandler(scope) {
3518
+ this.isAuthenticated = true;
3519
+ this.authorizedScope = scope;
3520
+ this.emit("authenticated", { scope });
3521
+ }
3522
+ setAwarenessField(key, value) {
3523
+ if (!this.awareness) {
3524
+ throw new AwarenessError(`Cannot set awareness field "${key}" to ${JSON.stringify(value)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`);
3525
+ }
3526
+ this.awareness.setLocalStateField(key, value);
3527
+ }
3528
+ }
3529
+
3530
+ /**
3531
+ * Hocuspocus sync provider for real-time collaboration
3532
+ * Supports multiplexing - multiple documents can share the same WebSocket connection
3533
+ */
3534
+ class HocuspocusSyncProvider {
3535
+ static type = 'network';
3536
+ type = 'network';
3537
+ provider;
3538
+ isConnected = false;
3539
+ isSynced = false;
3540
+ usesSharedSocket = false;
3541
+ isDestroyed = false;
3542
+ connectTimeout = null;
3543
+ pendingConnectReject = null;
3544
+ connectionTimeoutMs;
3545
+ _connectionStatus = 'disconnected';
3546
+ visibilityHandler = null;
3547
+ onlineHandler = null;
3548
+ get awareness() {
3549
+ return this.provider.awareness;
3550
+ }
3551
+ get rawProvider() {
3552
+ return this.provider;
3553
+ }
3554
+ get connectionStatus() {
3555
+ return this._connectionStatus;
3556
+ }
3557
+ // Static shared WebSocket instance for multiplexing
3558
+ static sharedWebSocketProvider = null;
3559
+ constructor(docName, doc, options) {
3560
+ const name = options?.name || docName;
3561
+ const url = options?.url || 'ws://localhost:1234';
3562
+ this.connectionTimeoutMs = options?.connectionTimeout ?? 10000;
3563
+ // Use provided websocketProvider or the static shared one
3564
+ const websocketProvider = options?.websocketProvider || HocuspocusSyncProvider.sharedWebSocketProvider;
3565
+ // Build reconnect config from options
3566
+ const reconnectConfig = {};
3567
+ if (options?.delay !== undefined)
3568
+ reconnectConfig.delay = options.delay;
3569
+ if (options?.factor !== undefined)
3570
+ reconnectConfig.factor = options.factor;
3571
+ if (options?.maxAttempts !== undefined)
3572
+ reconnectConfig.maxAttempts = options.maxAttempts;
3573
+ if (options?.minDelay !== undefined)
3574
+ reconnectConfig.minDelay = options.minDelay;
3575
+ if (options?.maxDelay !== undefined)
3576
+ reconnectConfig.maxDelay = options.maxDelay;
3577
+ const onConnect = () => {
3578
+ if (this.isDestroyed) {
3579
+ return;
3580
+ }
3581
+ this.isConnected = true;
3582
+ this._connectionStatus = 'connected';
3583
+ if (!options?.quiet) {
3584
+ console.info(`Hocuspocus connected: ${name}`);
3585
+ }
3586
+ if (options?.onConnect) {
3587
+ options.onConnect();
3588
+ }
3589
+ };
3590
+ const onDisconnect = () => {
3591
+ if (this.isDestroyed) {
3592
+ return;
3593
+ }
3594
+ this.isConnected = false;
3595
+ this.isSynced = false;
3596
+ this._connectionStatus = 'disconnected';
3597
+ if (!options?.quiet) {
3598
+ console.info(`Hocuspocus disconnected: ${name}`);
3599
+ }
3600
+ if (options?.onDisconnect) {
3601
+ options.onDisconnect();
3602
+ }
3603
+ };
3604
+ const onSynced = () => {
3605
+ if (this.isDestroyed) {
3606
+ return;
3607
+ }
3608
+ this.isSynced = true;
3609
+ this._connectionStatus = 'synced';
3610
+ if (!options?.quiet) {
3611
+ console.info(`Hocuspocus synced: ${name}`);
3612
+ }
3613
+ if (options?.onSynced) {
3614
+ options.onSynced();
3615
+ }
3616
+ };
3617
+ const onStatus = (data) => {
3618
+ if (this.isDestroyed) {
3619
+ return;
3620
+ }
3621
+ if (data.status === 'connecting') {
3622
+ this._connectionStatus = 'connecting';
3623
+ }
3624
+ if (options?.onStatus) {
3625
+ options.onStatus(data);
3626
+ }
3627
+ };
3628
+ if (websocketProvider) {
3629
+ // Multiplexing mode - use shared WebSocket connection
3630
+ this.usesSharedSocket = true;
3631
+ const config = {
3632
+ websocketProvider,
3633
+ name,
3634
+ document: doc,
3635
+ token: options?.token || null,
3636
+ onStatus,
3637
+ onConnect,
3638
+ onDisconnect,
3639
+ onSynced,
3640
+ ...reconnectConfig,
3641
+ };
3642
+ // Add optional settings
3643
+ if (options?.forceSyncInterval !== undefined) {
3644
+ config.forceSyncInterval = options.forceSyncInterval;
3645
+ }
3646
+ if (options?.onAuthenticationFailed) {
3647
+ config.onAuthenticationFailed = options.onAuthenticationFailed;
3648
+ }
3649
+ this.provider = new HocuspocusProvider(config);
3650
+ // Must call attach() explicitly when using shared socket
3651
+ this.provider.attach();
3652
+ if (!options?.quiet) {
3653
+ console.info(`Hocuspocus Provider initialized (multiplexed): ${name}`);
3654
+ }
3655
+ }
3656
+ else {
3657
+ // Standalone mode - create own WebSocket connection
3658
+ this.usesSharedSocket = false;
3659
+ const config = {
3660
+ url,
3661
+ name,
3662
+ document: doc,
3663
+ token: options?.token || null,
3664
+ autoConnect: false,
3665
+ onStatus,
3666
+ onConnect,
3667
+ onDisconnect,
3668
+ onSynced,
3669
+ ...reconnectConfig,
3670
+ };
3671
+ // Add optional settings
3672
+ if (options?.forceSyncInterval !== undefined) {
3673
+ config.forceSyncInterval = options.forceSyncInterval;
3674
+ }
3675
+ if (options?.onAuthenticationFailed) {
3676
+ config.onAuthenticationFailed = options.onAuthenticationFailed;
3677
+ }
3678
+ if (options?.WebSocketPolyfill) {
3679
+ config.WebSocketPolyfill = options.WebSocketPolyfill;
3680
+ }
3681
+ this.provider = new HocuspocusProvider(config);
3682
+ if (!options?.quiet) {
3683
+ console.info(`Hocuspocus Provider initialized: ${url}/${name}`);
3684
+ }
3685
+ }
3686
+ this.setupBrowserEventListeners();
3687
+ }
3688
+ setupBrowserEventListeners() {
3689
+ if (typeof document !== 'undefined') {
3690
+ this.visibilityHandler = () => {
3691
+ if (document.visibilityState === 'visible' && !this.isConnected && !this.isDestroyed) {
3692
+ this.provider.connect();
3693
+ }
3694
+ };
3695
+ document.addEventListener('visibilitychange', this.visibilityHandler);
3696
+ }
3697
+ if (typeof window !== 'undefined') {
3698
+ this.onlineHandler = () => {
3699
+ if (!this.isConnected && !this.isDestroyed) {
3700
+ this.provider.connect();
3701
+ }
3702
+ };
3703
+ window.addEventListener('online', this.onlineHandler);
3704
+ }
3705
+ }
3706
+ removeBrowserEventListeners() {
3707
+ if (this.visibilityHandler && typeof document !== 'undefined') {
3708
+ document.removeEventListener('visibilitychange', this.visibilityHandler);
3709
+ this.visibilityHandler = null;
3710
+ }
3711
+ if (this.onlineHandler && typeof window !== 'undefined') {
3712
+ window.removeEventListener('online', this.onlineHandler);
3713
+ this.onlineHandler = null;
3714
+ }
3715
+ }
3716
+ /**
3717
+ * Create a shared WebSocket connection for multiplexing
3718
+ * Call this once to create a shared connection that multiple providers can use
3719
+ */
3720
+ static createSharedWebSocket(options) {
3721
+ if (HocuspocusSyncProvider.sharedWebSocketProvider) {
3722
+ console.warn('Shared WebSocket already exists. Returning existing instance.');
3723
+ return HocuspocusSyncProvider.sharedWebSocketProvider;
3724
+ }
3725
+ const config = {
3726
+ url: options.url,
3727
+ };
3728
+ if (options.WebSocketPolyfill) {
3729
+ config.WebSocketPolyfill = options.WebSocketPolyfill;
3730
+ }
3731
+ if (options.onConnect) {
3732
+ config.onConnect = options.onConnect;
3733
+ }
3734
+ if (options.onDisconnect) {
3735
+ config.onDisconnect = options.onDisconnect;
3736
+ }
3737
+ if (options.onStatus) {
3738
+ config.onStatus = options.onStatus;
3739
+ }
3740
+ HocuspocusSyncProvider.sharedWebSocketProvider = new HocuspocusProviderWebsocket(config);
3741
+ console.info(`Shared Hocuspocus WebSocket created: ${options.url}`);
3742
+ return HocuspocusSyncProvider.sharedWebSocketProvider;
3743
+ }
3744
+ /**
3745
+ * Destroy the shared WebSocket connection
3746
+ * Call this when you're done with all multiplexed providers
3747
+ */
3748
+ static destroySharedWebSocket() {
3749
+ if (HocuspocusSyncProvider.sharedWebSocketProvider) {
3750
+ HocuspocusSyncProvider.sharedWebSocketProvider.destroy();
3751
+ HocuspocusSyncProvider.sharedWebSocketProvider = null;
3752
+ console.info('Shared Hocuspocus WebSocket destroyed');
3753
+ }
3754
+ }
3755
+ /**
3756
+ * Get the shared WebSocket provider instance (if it exists)
3757
+ */
3758
+ static getSharedWebSocket() {
3759
+ return HocuspocusSyncProvider.sharedWebSocketProvider;
3760
+ }
3761
+ /**
3762
+ * Static factory method for creating HocuspocusSyncProvider with configuration options
3763
+ * Returns a ProviderFactory that can be used in sync configuration
3764
+ */
3765
+ static with(options) {
3766
+ return {
3767
+ type: 'network',
3768
+ create: (docName, doc, runtimeOptions) => {
3769
+ const mergedOptions = runtimeOptions ? { ...options, ...runtimeOptions } : options;
3770
+ return new HocuspocusSyncProvider(docName, doc, mergedOptions);
3771
+ },
3772
+ };
3773
+ }
3774
+ async connect() {
3775
+ if (this.isSynced || this.isDestroyed) {
3776
+ return;
3777
+ }
3778
+ this._connectionStatus = 'connecting';
3779
+ return new Promise((resolve, reject) => {
3780
+ // Store reject function so we can cancel the connection if destroyed
3781
+ this.pendingConnectReject = reject;
3782
+ this.connectTimeout = setTimeout(() => {
3783
+ this.pendingConnectReject = null;
3784
+ this.connectTimeout = null;
3785
+ reject(new Error('Hocuspocus connection timeout'));
3786
+ }, this.connectionTimeoutMs);
3787
+ const syncHandler = () => {
3788
+ if (this.connectTimeout) {
3789
+ clearTimeout(this.connectTimeout);
3790
+ this.connectTimeout = null;
3791
+ }
3792
+ this.pendingConnectReject = null;
3793
+ this.provider.off('synced', syncHandler);
3794
+ if (!this.isDestroyed) {
3795
+ resolve();
3796
+ }
3797
+ };
3798
+ this.provider.on('synced', syncHandler);
3799
+ // If already synced, resolve immediately
3800
+ if (this.provider.isSynced) {
3801
+ if (this.connectTimeout) {
3802
+ clearTimeout(this.connectTimeout);
3803
+ this.connectTimeout = null;
3804
+ }
3805
+ this.pendingConnectReject = null;
3806
+ this.provider.off('synced', syncHandler);
3807
+ resolve();
3808
+ return;
3809
+ }
3810
+ // Connect if not already connected (standalone mode only)
3811
+ if (!this.isConnected && !this.usesSharedSocket) {
3812
+ this.provider.connect();
3813
+ }
3814
+ });
3815
+ }
3816
+ async reconnect() {
3817
+ this.disconnect();
3818
+ return this.connect();
3819
+ }
3820
+ disconnect() {
3821
+ // Cancel any pending connection attempt
3822
+ if (this.connectTimeout) {
3823
+ clearTimeout(this.connectTimeout);
3824
+ this.connectTimeout = null;
3825
+ }
3826
+ if (this.pendingConnectReject) {
3827
+ this.pendingConnectReject = null; // Don't reject, just abandon the promise
3828
+ }
3829
+ if (this.provider) {
3830
+ if (this.usesSharedSocket) {
3831
+ // Detach from shared socket instead of disconnecting
3832
+ this.provider.detach();
3833
+ }
3834
+ else {
3835
+ this.provider.disconnect();
3836
+ }
3837
+ }
3838
+ this.isConnected = false;
3839
+ this.isSynced = false;
3840
+ this._connectionStatus = 'disconnected';
3841
+ }
3842
+ destroy() {
3843
+ // Mark as destroyed first to prevent any callbacks from doing work
3844
+ this.isDestroyed = true;
3845
+ // Cancel any pending connection attempt
3846
+ if (this.connectTimeout) {
3847
+ clearTimeout(this.connectTimeout);
3848
+ this.connectTimeout = null;
3849
+ }
3850
+ if (this.pendingConnectReject) {
3851
+ this.pendingConnectReject = null; // Don't reject, just abandon the promise
3852
+ }
3853
+ this.removeBrowserEventListeners();
3854
+ if (this.provider) {
3855
+ this.provider.destroy();
3856
+ }
3857
+ this.isConnected = false;
3858
+ this.isSynced = false;
3859
+ this._connectionStatus = 'disconnected';
3860
+ }
3861
+ }
3862
+
3863
+ /**
3864
+ * Remote asset storage provider backed by a plain HTTP endpoint.
3865
+ *
3866
+ * The host application is responsible for exposing a REST-ish backend
3867
+ * that accepts a multipart upload and serves the stored asset at a
3868
+ * stable URL. Authentication is injected via `headers`.
3869
+ */
3870
+ class HttpAssetProvider {
3871
+ type = 'remote';
3872
+ name = 'HttpAssetProvider';
3873
+ _options;
3874
+ constructor(options) {
3875
+ this._options = options;
3876
+ }
3877
+ /**
3878
+ * Factory helper enabling use as `HttpAssetProvider.with({ ... })` inside
3879
+ * a `KritzelAssetStorageConfig.providers` array.
3880
+ */
3881
+ static with(options) {
3882
+ return { create: () => new HttpAssetProvider(options) };
3883
+ }
3884
+ async init() {
3885
+ if (!this._options.quiet) {
3886
+ console.info('HttpAssetProvider initialized');
3887
+ }
3888
+ }
3889
+ destroy() {
3890
+ // No-op; no resources to release.
3891
+ }
3892
+ canResolve(_id) {
3893
+ // Remote providers don't know without a round-trip; assume yes.
3894
+ return true;
3895
+ }
3896
+ async put(blob, metadata) {
3897
+ const id = metadata.id ?? this.generateUuid();
3898
+ const fullMetadata = { ...metadata, id };
3899
+ const headers = (await this._options.headers?.()) ?? {};
3900
+ const url = await this._options.uploadUrl(fullMetadata);
3901
+ const uploader = this._options.upload ?? this.defaultUpload;
3902
+ const response = await uploader(url, blob, fullMetadata, headers);
3903
+ return {
3904
+ id: response.id ?? id,
3905
+ kind: metadata.kind ?? 'file',
3906
+ mimeType: metadata.mimeType,
3907
+ size: blob.size,
3908
+ createdAt: Date.now(),
3909
+ width: metadata.width,
3910
+ height: metadata.height,
3911
+ durationMs: metadata.durationMs,
3912
+ originalFilename: metadata.originalFilename,
3913
+ };
3914
+ }
3915
+ async resolve(id) {
3916
+ return this._options.resolveUrl(id);
3917
+ }
3918
+ async fetch(id) {
3919
+ const url = await this._options.resolveUrl(id);
3920
+ const headers = (await this._options.headers?.()) ?? {};
3921
+ const res = await fetch(url, { headers });
3922
+ if (!res.ok) {
3923
+ throw new Error(`[HttpAssetProvider] Failed to fetch asset ${id}: ${res.status} ${res.statusText}`);
3924
+ }
3925
+ return res.blob();
3926
+ }
3927
+ async delete(id) {
3928
+ if (!this._options.deleteUrl)
3929
+ return;
3930
+ const url = await this._options.deleteUrl(id);
3931
+ const headers = (await this._options.headers?.()) ?? {};
3932
+ const res = await fetch(url, { method: 'DELETE', headers });
3933
+ if (!res.ok) {
3934
+ throw new Error(`[HttpAssetProvider] Failed to delete asset ${id}: ${res.status} ${res.statusText}`);
3935
+ }
3936
+ if (!this._options.quiet) {
3937
+ console.info(`HttpAssetProvider: deleted asset ${id}`);
3938
+ }
3939
+ }
3940
+ defaultUpload = async (url, blob, metadata, headers) => {
3941
+ const form = new FormData();
3942
+ form.append('metadata', JSON.stringify(metadata));
3943
+ form.append('file', blob, metadata.originalFilename || `${metadata.id}.${this.extensionFromMime(metadata.mimeType)}`);
3944
+ const res = await fetch(url, {
3945
+ method: 'POST',
3946
+ headers,
3947
+ body: form,
3948
+ });
3949
+ if (!res.ok) {
3950
+ throw new Error(`[HttpAssetProvider] Upload failed: ${res.status} ${res.statusText}`);
3951
+ }
3952
+ // Try to parse a JSON response; tolerate empty/plain-text bodies.
3953
+ const contentType = res.headers.get('content-type') || '';
3954
+ if (contentType.includes('application/json')) {
3955
+ return (await res.json());
3956
+ }
3957
+ return {};
3958
+ };
3959
+ extensionFromMime(mime) {
3960
+ const slash = mime.indexOf('/');
3961
+ return slash >= 0 ? mime.slice(slash + 1) : 'bin';
3962
+ }
3963
+ generateUuid() {
3964
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
3965
+ return crypto.randomUUID();
3966
+ }
3967
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
3968
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
3969
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
3970
+ const hex = Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
3971
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
3972
+ }
3973
+ }
3974
+
3975
+ /**
3976
+ * Remote asset storage provider for pre-signed URL uploads (S3, GCS, ...).
3977
+ *
3978
+ * All auth and URL signing is performed by the host application via the
3979
+ * callbacks in {@link PresignedAssetProviderOptions}. The library simply
3980
+ * PUTs/POSTs bytes to the provided URL.
3981
+ */
3982
+ class PresignedAssetProvider {
3983
+ type = 'remote';
3984
+ name = 'PresignedAssetProvider';
3985
+ _options;
3986
+ constructor(options) {
3987
+ this._options = options;
3988
+ }
3989
+ static with(options) {
3990
+ return { create: () => new PresignedAssetProvider(options) };
3991
+ }
3992
+ async init() {
3993
+ if (!this._options.quiet) {
3994
+ console.info('PresignedAssetProvider initialized');
3995
+ }
3996
+ }
3997
+ destroy() {
3998
+ // No-op.
3999
+ }
4000
+ canResolve(_id) {
4001
+ return true;
4002
+ }
4003
+ async put(blob, metadata) {
4004
+ const descriptor = await this._options.getUploadDescriptor(metadata);
4005
+ const method = descriptor.method ?? 'PUT';
4006
+ const headers = { ...(descriptor.headers ?? {}) };
4007
+ if (!headers['Content-Type'] && !headers['content-type']) {
4008
+ headers['Content-Type'] = metadata.mimeType;
4009
+ }
4010
+ let body;
4011
+ if (method === 'POST' && descriptor.fields) {
4012
+ const form = new FormData();
4013
+ for (const [key, value] of Object.entries(descriptor.fields)) {
4014
+ form.append(key, value);
4015
+ }
4016
+ form.append('file', blob);
4017
+ body = form;
4018
+ // Browser sets multipart boundary; avoid forcing content-type.
4019
+ delete headers['Content-Type'];
4020
+ delete headers['content-type'];
4021
+ }
4022
+ else {
4023
+ body = blob;
4024
+ }
4025
+ const res = await fetch(descriptor.url, { method, headers, body });
4026
+ if (!res.ok) {
4027
+ throw new Error(`[PresignedAssetProvider] Upload failed: ${res.status} ${res.statusText}`);
4028
+ }
4029
+ return {
4030
+ id: descriptor.id,
4031
+ kind: metadata.kind ?? 'file',
4032
+ mimeType: metadata.mimeType,
4033
+ size: blob.size,
4034
+ createdAt: Date.now(),
4035
+ width: metadata.width,
4036
+ height: metadata.height,
4037
+ durationMs: metadata.durationMs,
4038
+ originalFilename: metadata.originalFilename,
4039
+ };
4040
+ }
4041
+ async resolve(id) {
4042
+ return this._options.getDownloadUrl(id);
4043
+ }
4044
+ async fetch(id) {
4045
+ const url = await this._options.getDownloadUrl(id);
4046
+ const res = await fetch(url);
4047
+ if (!res.ok) {
4048
+ throw new Error(`[PresignedAssetProvider] Failed to fetch asset ${id}: ${res.status} ${res.statusText}`);
4049
+ }
4050
+ return res.blob();
4051
+ }
4052
+ async delete(id) {
4053
+ if (!this._options.deleteAsset)
4054
+ return;
4055
+ await this._options.deleteAsset(id);
4056
+ if (!this._options.quiet) {
4057
+ console.info(`PresignedAssetProvider: deleted asset ${id}`);
4058
+ }
4059
+ }
4060
+ }
4061
+
4062
+ /**
4063
+ * Returns the provider type (`'local'` or `'network'`) for a given provider config entry.
4064
+ * Works for both class constructors (via a static `type` property) and
4065
+ * factory objects (via an optional `type` property on the factory).
4066
+ */
4067
+ function getProviderConfigType(config) {
4068
+ if (typeof config === 'function') {
4069
+ return config.type;
4070
+ }
4071
+ return config.type;
4072
+ }
4073
+ /**
4074
+ * Returns `true` when the given sync configuration contains at least one remote
4075
+ * (network) provider, meaning the share option should be available in the UI.
4076
+ */
4077
+ function hasRemoteSyncProvider(syncConfig) {
4078
+ if (!syncConfig?.providers?.length) {
4079
+ return false;
4080
+ }
4081
+ return syncConfig.providers.some(p => getProviderConfigType(p) === 'network');
4082
+ }
4083
+
4084
+ const DEFAULT_BRUSH_CONFIG = {
4085
+ color: DEFAULT_COLOR_PALETTE[0],
4086
+ size: 16,
4087
+ opacity: 1,
4088
+ palette: [...DEFAULT_COLOR_PALETTE],
4089
+ sizes: [...DEFAULT_STROKE_SIZES],
4090
+ };
4091
+
4092
+ const DEFAULT_TEXT_CONFIG = {
4093
+ color: DEFAULT_COLOR_PALETTE[0],
4094
+ size: 8,
4095
+ opacity: 1,
4096
+ fontFamily: 'Arial',
4097
+ availableFonts: [...DEFAULT_TEXT_TOOL_AVAILABLE_FONTS],
4098
+ palette: [...DEFAULT_COLOR_PALETTE],
4099
+ sizes: [...DEFAULT_FONT_SIZES],
4100
+ };
4101
+
4102
+ const DEFAULT_LINE_TOOL_CONFIG = {
4103
+ color: DEFAULT_COLOR_PALETTE[0],
4104
+ size: 4,
4105
+ opacity: 1,
4106
+ palette: [...DEFAULT_COLOR_PALETTE],
4107
+ sizes: [...DEFAULT_STROKE_SIZES],
4108
+ arrows: {
4109
+ end: { enabled: true, style: 'triangle' },
4110
+ },
4111
+ };
4112
+
4113
+ const DEFAULT_SHAPE_CONFIG = {
4114
+ shapeType: ShapeType.Rectangle,
4115
+ fillColor: { light: 'transparent', dark: 'transparent' },
4116
+ strokeColor: DEFAULT_COLOR_PALETTE[0],
4117
+ strokeWidth: 4,
4118
+ opacity: 1,
4119
+ fontColor: DEFAULT_COLOR_PALETTE[0],
4120
+ fontSize: 16,
4121
+ fontFamily: 'Arial',
4122
+ palette: [...DEFAULT_COLOR_PALETTE],
4123
+ sizes: [...DEFAULT_STROKE_SIZES],
4124
+ };
4125
+
4126
+ /**
4127
+ * Default asset storage configuration. Stores bytes in IndexedDB only,
4128
+ * which provides offline-friendly behavior out of the box. Applications
4129
+ * that sync Yjs over the network should also configure a remote provider
4130
+ * (e.g. HttpAssetProvider) so images are available across devices.
4131
+ */
4132
+ const DEFAULT_ASSET_STORAGE_CONFIG = {
4133
+ providers: [],
4134
+ };
4135
+
4136
+ /**
4137
+ * The current version of the Kritzel library.
4138
+ * This file is auto-generated by the version bump scripts.
4139
+ * Do not modify manually.
4140
+ */
4141
+ const KRITZEL_VERSION = '0.4.31';
4142
+
4143
+ export { BroadcastSyncProvider, DEFAULT_ASSET_STORAGE_CONFIG, DEFAULT_BRUSH_CONFIG, DEFAULT_COLOR_PALETTE, DEFAULT_LINE_TOOL_CONFIG, DEFAULT_SHAPE_CONFIG, DEFAULT_TEXT_CONFIG, DEFAULT_TEXT_TOOL_AVAILABLE_FONTS, HocuspocusSyncProvider, HttpAssetProvider, InMemorySyncProvider, IndexedDBSyncProvider, KRITZEL_VERSION, KritzelToolConfigHelper, PresignedAssetProvider, ShapeType, WebSocketSyncProvider, hasRemoteSyncProvider };