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