diff --git a/package-lock.json b/package-lock.json index 9d6030a36..41c50940f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3503,45 +3503,45 @@ } }, "node_modules/@hocuspocus/extension-database": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@hocuspocus/extension-database/-/extension-database-2.1.0.tgz", - "integrity": "sha512-V4Dazj9GE5Mt3V8EE2r8AcbW3mMLC/nI/vizLVkp2b0I+A9dg7mI2fcOCerDgD79DY1c0gWrsxg4w06V2rVLVg==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@hocuspocus/extension-database/-/extension-database-2.4.0.tgz", + "integrity": "sha512-7xx551LbhZUR1BYnit+tceQWhtW9l+/jvYracyaYfWc6R8PD2IRHkkJ0ADQnl+4lEIUi6geWO0Ec8O/0yDHKuA==", "dependencies": { - "@hocuspocus/server": "^2.1.0" + "@hocuspocus/server": "^2.4.0" }, "peerDependencies": { - "yjs": "^13.5.29" + "yjs": "^13.6.4" } }, "node_modules/@hocuspocus/extension-logger": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@hocuspocus/extension-logger/-/extension-logger-2.1.0.tgz", - "integrity": "sha512-FoI/FHGJ5H5JJ1Sc9STaFjlV1RLFBxoqNzErBx/OLq7XrsLxmgBCPUIn4Q9/jSQE43pxXFWtPHDTb9xxFzz0/g==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@hocuspocus/extension-logger/-/extension-logger-2.4.0.tgz", + "integrity": "sha512-i6bpHLFJE4oxJ+yW/oIMjiRY2J7/2crWErQNEoAgmog9hJrTAmBtsjCgtH9auVBE0Vh4NJyFyUvD9KPOwK3BEQ==", "dependencies": { - "@hocuspocus/server": "^2.1.0" + "@hocuspocus/server": "^2.4.0" } }, "node_modules/@hocuspocus/provider": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@hocuspocus/provider/-/provider-2.1.0.tgz", - "integrity": "sha512-Hg6OLlxt0RFrZ7pS6p2pnqWhxeqq4tRVcbyA34E8/Braj40S+q+H5+0UIYyXTLGknRrChcjIN/P51C8gGAA9sQ==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@hocuspocus/provider/-/provider-2.4.0.tgz", + "integrity": "sha512-cEbL94LTd8nTRMSZu/oX4zK3owEwyjQ1n6SgthzfkTqa0XCELCTTyDoCYeialTzJiCfAaJk1Lb2oqnQT73AhGQ==", "dependencies": { - "@hocuspocus/common": "^2.1.0", + "@hocuspocus/common": "^2.4.0", "@lifeomic/attempt": "^3.0.2", "lib0": "^0.2.47", "ws": "^7.5.9" }, "peerDependencies": { "y-protocols": "^1.0.5", - "yjs": "^13.5.29" + "yjs": "^13.6.4" } }, "node_modules/@hocuspocus/server": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@hocuspocus/server/-/server-2.1.0.tgz", - "integrity": "sha512-JcabFDBqETxm3Hbs46P5Px/IgnaOn7lCtiT14dp/JzYxE34nHinGY3A1hDu5kpjghE6SpkjyIK2n8HGiA/bZSw==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@hocuspocus/server/-/server-2.4.0.tgz", + "integrity": "sha512-aKBTRh4HnHu1/uzPjGacDRsKtmL7M3m7XlDD/KkY1oY/u3b06eH8yqKD5h1jTy8XP55z0M/YeYcwSX2hfP9wRQ==", "dependencies": { - "@hocuspocus/common": "^2.1.0", + "@hocuspocus/common": "^2.4.0", "async-lock": "^1.3.1", "kleur": "^4.1.4", "lib0": "^0.2.47", @@ -3550,7 +3550,7 @@ }, "peerDependencies": { "y-protocols": "^1.0.5", - "yjs": "^13.5.29" + "yjs": "^13.6.4" } }, "node_modules/@hocuspocus/server/node_modules/uuid": { @@ -15972,7 +15972,7 @@ "@atlaskit/tree": "^8.8.5", "@blocknote/core": "^0.9.2", "@emotion/react": "^11.4.0", - "@hocuspocus/provider": "2.1.0", + "@hocuspocus/provider": "^2.4.0", "@supabase/auth-ui-react": "^0.4.2", "@supabase/auth-ui-shared": "^0.1.6", "@supabase/supabase-js": "^2.26.0", @@ -16482,9 +16482,9 @@ "name": "@typecell-org/server", "version": "0.0.3", "dependencies": { - "@hocuspocus/extension-database": "2.1.0", - "@hocuspocus/extension-logger": "2.1.0", - "@hocuspocus/server": "2.1.0", + "@hocuspocus/extension-database": "^2.4.0", + "@hocuspocus/extension-logger": "^2.4.0", + "@hocuspocus/server": "^2.4.0", "@supabase/supabase-js": "^2.12.1", "@typecell-org/shared": "^0.0.3", "@typecell-org/shared-test": "^0.0.3", @@ -16493,7 +16493,7 @@ "vscode-lib": "^0.1.2" }, "devDependencies": { - "@hocuspocus/provider": "2.1.0", + "@hocuspocus/provider": "^2.4.0", "@playwright/test": "^1.33.0", "@vitest/coverage-v8": "^0.33.0", "jsdom": "^20.0.0", @@ -16548,7 +16548,7 @@ "name": "@typecell-org/shared-test", "version": "0.0.3", "devDependencies": { - "@hocuspocus/provider": "2.1.0", + "@hocuspocus/provider": "^2.4.0", "@supabase/supabase-js": "^2.12.1", "@typecell-org/shared": "*", "@typecell-org/util": "*", diff --git a/packages/editor/package.json b/packages/editor/package.json index ae763a1d3..65e227400 100644 --- a/packages/editor/package.json +++ b/packages/editor/package.json @@ -3,7 +3,7 @@ "version": "0.0.3", "private": true, "dependencies": { - "@hocuspocus/provider": "2.1.0", + "@hocuspocus/provider": "^2.4.0", "@atlaskit/atlassian-navigation": "^2.6.13", "@atlaskit/avatar": "^21.3.7", "@atlaskit/breadcrumbs": "^11.10.5", diff --git a/packages/editor/src/store/yjs-sync/remote/TypeCellRemote.ts b/packages/editor/src/store/yjs-sync/remote/TypeCellRemote.ts index 8b1c3a770..ee1085c31 100644 --- a/packages/editor/src/store/yjs-sync/remote/TypeCellRemote.ts +++ b/packages/editor/src/store/yjs-sync/remote/TypeCellRemote.ts @@ -88,7 +88,7 @@ export class TypeCellRemote extends Remote { public get awareness(): awarenessProtocol.Awareness | undefined { this._awarenessAtom.reportObserved(); - return this.hocuspocusProvider?.awareness; + return this.hocuspocusProvider?.awareness || undefined; } // TODO: "canWrite" isn't a great name, because it's actually "hasNoChanges Or CanWriteAndWaitingForSync". We should probably split "pending messages" and "access" into two separate properties. diff --git a/packages/server/package.json b/packages/server/package.json index 18b6debe4..2eab53b84 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -6,15 +6,15 @@ "@typecell-org/shared": "^0.0.3", "@typecell-org/shared-test": "^0.0.3", "@typecell-org/util": "^0.0.3", - "@hocuspocus/extension-database": "2.1.0", - "@hocuspocus/extension-logger": "2.1.0", - "@hocuspocus/server": "2.1.0", + "@hocuspocus/extension-database": "^2.4.0", + "@hocuspocus/extension-logger": "^2.4.0", + "@hocuspocus/server": "^2.4.0", "@supabase/supabase-js": "^2.12.1", "vscode-lib": "^0.1.2", "dotenv": "^16.3.1" }, "devDependencies": { - "@hocuspocus/provider": "2.1.0", + "@hocuspocus/provider": "^2.4.0", "@playwright/test": "^1.33.0", "@vitest/coverage-v8": "^0.33.0", "jsdom": "^20.0.0", diff --git a/packages/shared-test/package.json b/packages/shared-test/package.json index b94bc0c20..7ca8d188a 100644 --- a/packages/shared-test/package.json +++ b/packages/shared-test/package.json @@ -4,7 +4,7 @@ "private": true, "dependencies": {}, "devDependencies": { - "@hocuspocus/provider": "2.1.0", + "@hocuspocus/provider": "^2.4.0", "@typecell-org/shared": "*", "@typecell-org/util": "*", "typescript": "5.0.4", diff --git a/patches/@hocuspocus+provider+2.1.0.patch b/patches/@hocuspocus+provider+2.1.0.patch deleted file mode 100644 index f1ce24bd1..000000000 --- a/patches/@hocuspocus+provider+2.1.0.patch +++ /dev/null @@ -1,4459 +0,0 @@ -diff --git a/node_modules/@hocuspocus/provider/CHANGELOG.md b/node_modules/@hocuspocus/provider/CHANGELOG.md -new file mode 100644 -index 0000000..a7f7115 ---- /dev/null -+++ b/node_modules/@hocuspocus/provider/CHANGELOG.md -@@ -0,0 +1,508 @@ -+# Change Log -+ -+All notable changes to this project will be documented in this file. -+See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. -+ -+# [2.1.0](https://github.com/ueberdosis/hocuspocus/compare/v2.0.6...v2.1.0) (2023-06-03) -+ -+ -+### Bug Fixes -+ -+* export typings for recent typescript ([#602](https://github.com/ueberdosis/hocuspocus/issues/602)) ([551d27f](https://github.com/ueberdosis/hocuspocus/commit/551d27fa6de9c746c67bf0f1e3bb56167aebbca5)), closes [/github.com/artalar/reatom/issues/560#issuecomment-1528997739](https://github.com//github.com/artalar/reatom/issues/560/issues/issuecomment-1528997739) -+ -+ -+ -+ -+ -+## [2.0.6](https://github.com/ueberdosis/hocuspocus/compare/v2.0.5...v2.0.6) (2023-04-25) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+## [2.0.5](https://github.com/ueberdosis/hocuspocus/compare/v2.0.4...v2.0.5) (2023-04-24) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+## [2.0.4](https://github.com/ueberdosis/hocuspocus/compare/v2.0.3...v2.0.4) (2023-04-23) -+ -+ -+### Bug Fixes -+ -+* Do not retry connection if data is too large ([#586](https://github.com/ueberdosis/hocuspocus/issues/586)) ([462a87f](https://github.com/ueberdosis/hocuspocus/commit/462a87f08bfdcaece4adb1ef8dca25ae42b3cb36)) -+ -+ -+ -+ -+ -+## [2.0.3](https://github.com/ueberdosis/hocuspocus/compare/v2.0.2...v2.0.3) (2023-04-05) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+## [2.0.2](https://github.com/ueberdosis/hocuspocus/compare/v2.0.1...v2.0.2) (2023-04-04) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+## [2.0.1](https://github.com/ueberdosis/hocuspocus/compare/v2.0.0...v2.0.1) (2023-03-30) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [2.0.0](https://github.com/ueberdosis/hocuspocus/compare/v1.1.3...v2.0.0) (2023-03-29) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [2.0.0-beta.0](https://github.com/ueberdosis/hocuspocus/compare/v1.1.1...v2.0.0-beta.0) (2023-03-28) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [2.0.0-alpha.1](https://github.com/ueberdosis/hocuspocus/compare/v2.0.0-alpha.0...v2.0.0-alpha.1) (2023-03-23) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [2.0.0-alpha.0](https://github.com/ueberdosis/hocuspocus/compare/v1.1.0...v2.0.0-alpha.0) (2023-02-28) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.1.0](https://github.com/ueberdosis/hocuspocus/compare/v1.0.2...v1.1.0) (2023-02-24) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+## [1.0.2](https://github.com/ueberdosis/hocuspocus/compare/v1.0.1...v1.0.2) (2023-02-16) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+## [1.0.1](https://github.com/ueberdosis/hocuspocus/compare/v1.0.0...v1.0.1) (2023-01-30) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0](https://github.com/ueberdosis/hocuspocus/compare/v1.0.0-beta.7...v1.0.0) (2023-01-18) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-beta.7](https://github.com/ueberdosis/hocuspocus/compare/v1.0.0-beta.6...v1.0.0-beta.7) (2023-01-11) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-beta.6](https://github.com/ueberdosis/hocuspocus/compare/v1.0.0-beta.5...v1.0.0-beta.6) (2022-12-03) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-beta.5](https://github.com/ueberdosis/hocuspocus/compare/v1.0.0-beta.3...v1.0.0-beta.5) (2022-11-25) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-beta.3](https://github.com/ueberdosis/hocuspocus/compare/v1.0.0-beta.2...v1.0.0-beta.3) (2022-11-03) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-beta.2](https://github.com/ueberdosis/hocuspocus/compare/v1.0.0-beta.1...v1.0.0-beta.2) (2022-09-28) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# 1.0.0-beta.111 (2022-09-28) -+ -+ -+### Bug Fixes -+ -+* Account for this.webSocket being null ([#235](https://github.com/ueberdosis/hocuspocus/issues/235)) ([b1476b6](https://github.com/ueberdosis/hocuspocus/commit/b1476b60f0eceb83d70c1ded2b3139e4f865a869)) -+* Empty sync message causes error in client MessageReceiver ([#174](https://github.com/ueberdosis/hocuspocus/issues/174)) ([f9dca69](https://github.com/ueberdosis/hocuspocus/commit/f9dca69eb96d1ede37a0709bd3b7735bf1ff57ba)) -+* Remote client awareness not immediately available ([37703f6](https://github.com/ueberdosis/hocuspocus/commit/37703f695f6bf3b0508c287294c5d26d2e888c37)) -+ -+ -+### Features -+ -+* Message Authentication ([#163](https://github.com/ueberdosis/hocuspocus/issues/163)) ([a1e68d5](https://github.com/ueberdosis/hocuspocus/commit/a1e68d5a272742bd17dd92522dfc908277343849)) -+ -+ -+ -+ -+ -+# [1.0.0-alpha.40](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.39...@hocuspocus/provider@1.0.0-alpha.40) (2022-08-28) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.39](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.38...@hocuspocus/provider@1.0.0-alpha.39) (2022-07-13) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.38](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.37...@hocuspocus/provider@1.0.0-alpha.38) (2022-06-13) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.37](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.36...@hocuspocus/provider@1.0.0-alpha.37) (2022-06-08) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.36](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.35...@hocuspocus/provider@1.0.0-alpha.36) (2022-04-05) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.35](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.34...@hocuspocus/provider@1.0.0-alpha.35) (2022-03-21) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.34](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.33...@hocuspocus/provider@1.0.0-alpha.34) (2022-03-11) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.33](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.32...@hocuspocus/provider@1.0.0-alpha.33) (2022-03-02) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.32](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.31...@hocuspocus/provider@1.0.0-alpha.32) (2022-02-24) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.31](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.30...@hocuspocus/provider@1.0.0-alpha.31) (2022-02-22) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.30](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.29...@hocuspocus/provider@1.0.0-alpha.30) (2022-02-18) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.29](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.28...@hocuspocus/provider@1.0.0-alpha.29) (2021-12-09) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.28](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.27...@hocuspocus/provider@1.0.0-alpha.28) (2021-12-07) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.27](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.26...@hocuspocus/provider@1.0.0-alpha.27) (2021-12-03) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.26](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.25...@hocuspocus/provider@1.0.0-alpha.26) (2021-11-30) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.25](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.24...@hocuspocus/provider@1.0.0-alpha.25) (2021-11-30) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.24](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.23...@hocuspocus/provider@1.0.0-alpha.24) (2021-11-26) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.23](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.22...@hocuspocus/provider@1.0.0-alpha.23) (2021-11-24) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.22](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.21...@hocuspocus/provider@1.0.0-alpha.22) (2021-11-22) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.21](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.20...@hocuspocus/provider@1.0.0-alpha.21) (2021-10-31) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.20](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.19...@hocuspocus/provider@1.0.0-alpha.20) (2021-10-28) -+ -+ -+### Bug Fixes -+ -+* Account for this.webSocket being null ([#235](https://github.com/ueberdosis/hocuspocus/issues/235)) ([b1476b6](https://github.com/ueberdosis/hocuspocus/commit/b1476b60f0eceb83d70c1ded2b3139e4f865a869)) -+ -+ -+ -+ -+ -+# [1.0.0-alpha.19](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.18...@hocuspocus/provider@1.0.0-alpha.19) (2021-10-15) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.18](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.17...@hocuspocus/provider@1.0.0-alpha.18) (2021-10-06) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.17](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.16...@hocuspocus/provider@1.0.0-alpha.17) (2021-10-05) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.16](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.15...@hocuspocus/provider@1.0.0-alpha.16) (2021-09-17) -+ -+ -+### Bug Fixes -+ -+* Remote client awareness not immediately available ([37703f6](https://github.com/ueberdosis/hocuspocus/commit/37703f695f6bf3b0508c287294c5d26d2e888c37)) -+ -+ -+ -+ -+ -+# [1.0.0-alpha.15](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.14...@hocuspocus/provider@1.0.0-alpha.15) (2021-09-14) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.14](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.13...@hocuspocus/provider@1.0.0-alpha.14) (2021-09-03) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.13](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.12...@hocuspocus/provider@1.0.0-alpha.13) (2021-09-01) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.12](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.11...@hocuspocus/provider@1.0.0-alpha.12) (2021-08-31) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.11](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.10...@hocuspocus/provider@1.0.0-alpha.11) (2021-08-27) -+ -+ -+### Bug Fixes -+ -+* Empty sync message causes error in client MessageReceiver ([#174](https://github.com/ueberdosis/hocuspocus/issues/174)) ([f9dca69](https://github.com/ueberdosis/hocuspocus/commit/f9dca69eb96d1ede37a0709bd3b7735bf1ff57ba)) -+ -+ -+ -+ -+ -+# [1.0.0-alpha.10](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.9...@hocuspocus/provider@1.0.0-alpha.10) (2021-08-19) -+ -+ -+### Features -+ -+* Message Authentication ([#163](https://github.com/ueberdosis/hocuspocus/issues/163)) ([a1e68d5](https://github.com/ueberdosis/hocuspocus/commit/a1e68d5a272742bd17dd92522dfc908277343849)) -+ -+ -+ -+ -+ -+# [1.0.0-alpha.9](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.8...@hocuspocus/provider@1.0.0-alpha.9) (2021-08-19) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.8](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.7...@hocuspocus/provider@1.0.0-alpha.8) (2021-06-23) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.7](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.6...@hocuspocus/provider@1.0.0-alpha.7) (2021-06-22) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.6](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.5...@hocuspocus/provider@1.0.0-alpha.6) (2021-06-11) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.5](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.4...@hocuspocus/provider@1.0.0-alpha.5) (2021-06-11) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.4](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.3...@hocuspocus/provider@1.0.0-alpha.4) (2021-06-09) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# [1.0.0-alpha.3](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/provider@1.0.0-alpha.2...@hocuspocus/provider@1.0.0-alpha.3) (2021-06-09) -+ -+**Note:** Version bump only for package @hocuspocus/provider -+ -+ -+ -+ -+ -+# 1.0.0-alpha.2 (2021-06-08) -+ -+**Note:** Version bump only for package @hocuspocus/provider -diff --git a/node_modules/@hocuspocus/provider/dist/hocuspocus-provider.cjs b/node_modules/@hocuspocus/provider/dist/hocuspocus-provider.cjs -index c00693b..fc67b7c 100644 ---- a/node_modules/@hocuspocus/provider/dist/hocuspocus-provider.cjs -+++ b/node_modules/@hocuspocus/provider/dist/hocuspocus-provider.cjs -@@ -2,8 +2,8 @@ - - Object.defineProperty(exports, '__esModule', { value: true }); - --var Y = require('yjs'); - var common = require('@hocuspocus/common'); -+var Y = require('yjs'); - var attempt = require('@lifeomic/attempt'); - - function _interopNamespace(e) { -@@ -74,6 +74,22 @@ const setIfUndefined = (map, key, createT) => { - - const create$1 = () => new Set(); - -+/** -+ * Utility module to work with Arrays. -+ * -+ * @module array -+ */ -+ -+/** -+ * Transforms something array-like to an actual Array. -+ * -+ * @function -+ * @template T -+ * @param {ArrayLike|Iterable} arraylike -+ * @return {T} -+ */ -+const from = Array.from; -+ - /** - * Utility module to work with strings. - * -@@ -236,22 +252,6 @@ const onChange = eventHandler => usePolyfill || addEventListener('storage', /** - /* c8 ignore next */ - const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler)); - --/** -- * Utility module to work with Arrays. -- * -- * @module array -- */ -- --/** -- * Transforms something array-like to an actual Array. -- * -- * @function -- * @template T -- * @param {ArrayLike|Iterable} arraylike -- * @return {T} -- */ --const from = Array.from; -- - /** - * Utility functions for working with EcmaScript objects. - * -@@ -399,7 +399,6 @@ const equalityDeep = (a, b) => { - */ - // @ts-ignore - const isOneOf = (value, options) => options.includes(value); --/* c8 ignore stop */ - - /** - * Isomorphic module to work access the environment (query params, env variables). -@@ -531,7 +530,9 @@ const min = (a, b) => a < b ? a : b; - const max = (a, b) => a > b ? a : b; - - /* eslint-env browser */ -+const BIT7 = 64; - const BIT8 = 128; -+const BITS6 = 63; - const BITS7 = 127; - - /** -@@ -889,6 +890,44 @@ const readVarUint = decoder => { - throw errorUnexpectedEndOfArray - }; - -+/** -+ * Read signed integer (32bit) with variable length. -+ * 1/8th of the storage is used as encoding overhead. -+ * * numbers < 2^7 is stored in one bytlength -+ * * numbers < 2^14 is stored in two bylength -+ * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change. -+ * -+ * @function -+ * @param {Decoder} decoder -+ * @return {number} An unsigned integer.length -+ */ -+const readVarInt = decoder => { -+ let r = decoder.arr[decoder.pos++]; -+ let num = r & BITS6; -+ let mult = 64; -+ const sign = (r & BIT7) > 0 ? -1 : 1; -+ if ((r & BIT8) === 0) { -+ // don't continue reading -+ return sign * num -+ } -+ const len = decoder.arr.length; -+ while (decoder.pos < len) { -+ r = decoder.arr[decoder.pos++]; -+ // num = num | ((r & binary.BITS7) << len) -+ num = num + (r & BITS7) * mult; -+ mult *= 128; -+ if (r < BIT8) { -+ return sign * num -+ } -+ /* c8 ignore start */ -+ if (num > MAX_SAFE_INTEGER) { -+ throw errorIntegerOutOfRange -+ } -+ /* c8 ignore stop */ -+ } -+ throw errorUnexpectedEndOfArray -+}; -+ - /** - * We don't test this function anymore as we use native decoding/encoding by default now. - * Better not modify this anymore.. -@@ -1136,6 +1175,50 @@ const publish = (room, data, origin = null) => { - c.subs.forEach(sub => sub(data, origin)); - }; - -+/** -+ * Mutual exclude for JavaScript. -+ * -+ * @module mutex -+ */ -+ -+/** -+ * @callback mutex -+ * @param {function():void} cb Only executed when this mutex is not in the current stack -+ * @param {function():void} [elseCb] Executed when this mutex is in the current stack -+ */ -+ -+/** -+ * Creates a mutual exclude function with the following property: -+ * -+ * ```js -+ * const mutex = createMutex() -+ * mutex(() => { -+ * // This function is immediately executed -+ * mutex(() => { -+ * // This function is not executed, as the mutex is already active. -+ * }) -+ * }) -+ * ``` -+ * -+ * @return {mutex} A mutual exclude function -+ * @public -+ */ -+const createMutex = () => { -+ let token = true; -+ return (f, g) => { -+ if (token) { -+ token = false; -+ try { -+ f(); -+ } finally { -+ token = true; -+ } -+ } else if (g !== undefined) { -+ g(); -+ } -+ } -+}; -+ - /** - * Utility module to work with time. - * -@@ -1486,50 +1569,6 @@ const applyAwarenessUpdate = (awareness, update, origin) => { - } - }; - --/** -- * Mutual exclude for JavaScript. -- * -- * @module mutex -- */ -- --/** -- * @callback mutex -- * @param {function():void} cb Only executed when this mutex is not in the current stack -- * @param {function():void} [elseCb] Executed when this mutex is in the current stack -- */ -- --/** -- * Creates a mutual exclude function with the following property: -- * -- * ```js -- * const mutex = createMutex() -- * mutex(() => { -- * // This function is immediately executed -- * mutex(() => { -- * // This function is not executed, as the mutex is already active. -- * }) -- * }) -- * ``` -- * -- * @return {mutex} A mutual exclude function -- * @public -- */ --const createMutex = () => { -- let token = true; -- return (f, g) => { -- if (token) { -- token = false; -- try { -- f(); -- } finally { -- token = true; -- } -- } else if (g !== undefined) { -- g(); -- } -- } --}; -- - class EventEmitter { - constructor() { - this.callbacks = {}; -@@ -1565,712 +1604,690 @@ class EventEmitter { - } - } - --class IncomingMessage { -- constructor(data) { -- this.data = data; -- this.encoder = createEncoder(); -- this.decoder = createDecoder(new Uint8Array(this.data)); -- } -- readVarUint() { -- return readVarUint(this.decoder); -- } -- readVarString() { -- return readVarString(this.decoder); -- } -- readVarUint8Array() { -- return readVarUint8Array(this.decoder); -- } -- writeVarUint(type) { -- return writeVarUint(this.encoder, type); -- } -- writeVarString(string) { -- return writeVarString(this.encoder, string); -- } -- writeVarUint8Array(data) { -- return writeVarUint8Array(this.encoder, data); -- } -- length() { -- return length(this.encoder); -- } --} -- - /** -- * @module sync-protocol -- */ -- --/** -- * @typedef {Map} StateMap -- */ -- --/** -- * Core Yjs defines two message types: -- * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2. -- * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it -- * received all information from the remote client. -- * -- * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection -- * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both -- * SyncStep2 and SyncDone, it is assured that it is synced to the remote client. -- * -- * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1. -- * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies -- * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the -- * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can -- * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them. -- * Therefore it is necesarry that the client initiates the sync. -- * -- * Construction of a message: -- * [messageType : varUint, message definition..] -- * -- * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol! -+ * Utility module to work with urls. - * -- * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer) -+ * @module url - */ - --const messageYjsSyncStep1 = 0; --const messageYjsSyncStep2 = 1; --const messageYjsUpdate = 2; -- - /** -- * Create a sync step 1 message based on the state of the current shared document. -- * -- * @param {encoding.Encoder} encoder -- * @param {Y.Doc} doc -+ * @param {Object} params -+ * @return {string} - */ --const writeSyncStep1 = (encoder, doc) => { -- writeVarUint(encoder, messageYjsSyncStep1); -- const sv = Y__namespace.encodeStateVector(doc); -- writeVarUint8Array(encoder, sv); --}; -+const encodeQueryParams = params => -+ map(params, (val, key) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&'); - --/** -- * @param {encoding.Encoder} encoder -- * @param {Y.Doc} doc -- * @param {Uint8Array} [encodedStateVector] -- */ --const writeSyncStep2 = (encoder, doc, encodedStateVector) => { -- writeVarUint(encoder, messageYjsSyncStep2); -- writeVarUint8Array(encoder, Y__namespace.encodeStateAsUpdate(doc, encodedStateVector)); --}; -+exports.MessageType = void 0; -+(function (MessageType) { -+ MessageType[MessageType["Sync"] = 0] = "Sync"; -+ MessageType[MessageType["Awareness"] = 1] = "Awareness"; -+ MessageType[MessageType["Auth"] = 2] = "Auth"; -+ MessageType[MessageType["QueryAwareness"] = 3] = "QueryAwareness"; -+ MessageType[MessageType["Stateless"] = 5] = "Stateless"; -+ MessageType[MessageType["CLOSE"] = 7] = "CLOSE"; -+ MessageType[MessageType["SyncStatus"] = 8] = "SyncStatus"; -+})(exports.MessageType || (exports.MessageType = {})); -+exports.WebSocketStatus = void 0; -+(function (WebSocketStatus) { -+ WebSocketStatus["Connecting"] = "connecting"; -+ WebSocketStatus["Connected"] = "connected"; -+ WebSocketStatus["Disconnected"] = "disconnected"; -+})(exports.WebSocketStatus || (exports.WebSocketStatus = {})); - --/** -- * Read SyncStep1 message and reply with SyncStep2. -- * -- * @param {decoding.Decoder} decoder The reply to the received message -- * @param {encoding.Encoder} encoder The received message -- * @param {Y.Doc} doc -- */ --const readSyncStep1 = (decoder, encoder, doc) => -- writeSyncStep2(encoder, doc, readVarUint8Array(decoder)); -- --/** -- * Read and apply Structs and then DeleteStore to a y instance. -- * -- * @param {decoding.Decoder} decoder -- * @param {Y.Doc} doc -- * @param {any} transactionOrigin -- */ --const readSyncStep2 = (decoder, doc, transactionOrigin) => { -- try { -- Y__namespace.applyUpdate(doc, readVarUint8Array(decoder), transactionOrigin); -- } catch (error) { -- // This catches errors that are thrown by event handlers -- console.error('Caught error while handling a Yjs update', error); -- } --}; -- --/** -- * @param {encoding.Encoder} encoder -- * @param {Uint8Array} update -- */ --const writeUpdate = (encoder, update) => { -- writeVarUint(encoder, messageYjsUpdate); -- writeVarUint8Array(encoder, update); --}; -- --/** -- * Read and apply Structs and then DeleteStore to a y instance. -- * -- * @param {decoding.Decoder} decoder -- * @param {Y.Doc} doc -- * @param {any} transactionOrigin -- */ --const readUpdate = readSyncStep2; -- --/** -- * @param {decoding.Decoder} decoder A message received from another client -- * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty. -- * @param {Y.Doc} doc -- * @param {any} transactionOrigin -- */ --const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => { -- const messageType = readVarUint(decoder); -- switch (messageType) { -- case messageYjsSyncStep1: -- readSyncStep1(decoder, encoder, doc); -- break -- case messageYjsSyncStep2: -- readSyncStep2(decoder, doc, transactionOrigin); -- break -- case messageYjsUpdate: -- readUpdate(decoder, doc, transactionOrigin); -- break -- default: -- throw new Error('Unknown message type') -- } -- return messageType --}; -- --exports.MessageType = void 0; --(function (MessageType) { -- MessageType[MessageType["Sync"] = 0] = "Sync"; -- MessageType[MessageType["Awareness"] = 1] = "Awareness"; -- MessageType[MessageType["Auth"] = 2] = "Auth"; -- MessageType[MessageType["QueryAwareness"] = 3] = "QueryAwareness"; -- MessageType[MessageType["Stateless"] = 5] = "Stateless"; -- MessageType[MessageType["CLOSE"] = 7] = "CLOSE"; --})(exports.MessageType || (exports.MessageType = {})); --exports.WebSocketStatus = void 0; --(function (WebSocketStatus) { -- WebSocketStatus["Connecting"] = "connecting"; -- WebSocketStatus["Connected"] = "connected"; -- WebSocketStatus["Disconnected"] = "disconnected"; --})(exports.WebSocketStatus || (exports.WebSocketStatus = {})); -- --class OutgoingMessage { -- constructor() { -- this.encoder = createEncoder(); -+class HocuspocusProviderWebsocket extends EventEmitter { -+ constructor(configuration) { -+ super(); -+ this.messageQueue = []; -+ this.configuration = { -+ url: '', -+ // @ts-ignore -+ document: undefined, -+ // @ts-ignore -+ awareness: undefined, -+ WebSocketPolyfill: undefined, -+ parameters: {}, -+ connect: true, -+ broadcast: true, -+ forceSyncInterval: false, -+ // TODO: this should depend on awareness.outdatedTime -+ messageReconnectTimeout: 30000, -+ // 1 second -+ delay: 1000, -+ // instant -+ initialDelay: 0, -+ // double the delay each time -+ factor: 2, -+ // unlimited retries -+ maxAttempts: 0, -+ // wait at least 1 second -+ minDelay: 1000, -+ // at least every 30 seconds -+ maxDelay: 30000, -+ // randomize -+ jitter: true, -+ // retry forever -+ timeout: 0, -+ onOpen: () => null, -+ onConnect: () => null, -+ onMessage: () => null, -+ onOutgoingMessage: () => null, -+ onStatus: () => null, -+ onDisconnect: () => null, -+ onClose: () => null, -+ onDestroy: () => null, -+ onAwarenessUpdate: () => null, -+ onAwarenessChange: () => null, -+ quiet: false, -+ }; -+ this.subscribedToBroadcastChannel = false; -+ this.webSocket = null; -+ this.shouldConnect = true; -+ this.status = exports.WebSocketStatus.Disconnected; -+ this.lastMessageReceived = 0; -+ this.mux = createMutex(); -+ this.intervals = { -+ forceSync: null, -+ connectionChecker: null, -+ }; -+ this.connectionAttempt = null; -+ this.receivedOnOpenPayload = undefined; -+ this.receivedOnStatusPayload = undefined; -+ this.boundConnect = this.connect.bind(this); -+ this.setConfiguration(configuration); -+ this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill ? configuration.WebSocketPolyfill : WebSocket; -+ this.on('open', this.configuration.onOpen); -+ this.on('open', this.onOpen.bind(this)); -+ this.on('connect', this.configuration.onConnect); -+ this.on('message', this.configuration.onMessage); -+ this.on('outgoingMessage', this.configuration.onOutgoingMessage); -+ this.on('status', this.configuration.onStatus); -+ this.on('status', this.onStatus.bind(this)); -+ this.on('disconnect', this.configuration.onDisconnect); -+ this.on('close', this.configuration.onClose); -+ this.on('destroy', this.configuration.onDestroy); -+ this.on('awarenessUpdate', this.configuration.onAwarenessUpdate); -+ this.on('awarenessChange', this.configuration.onAwarenessChange); -+ this.on('close', this.onClose.bind(this)); -+ this.on('message', this.onMessage.bind(this)); -+ this.registerEventListeners(); -+ this.intervals.connectionChecker = setInterval(this.checkConnection.bind(this), this.configuration.messageReconnectTimeout / 10); -+ if (typeof configuration.connect !== 'undefined') { -+ this.shouldConnect = configuration.connect; -+ } -+ if (!this.shouldConnect) { -+ return; -+ } -+ this.connect(); - } -- get(args) { -- return args.encoder; -+ async onOpen(event) { -+ this.receivedOnOpenPayload = event; - } -- toUint8Array() { -- return toUint8Array(this.encoder); -+ async onStatus(data) { -+ this.receivedOnStatusPayload = data; - } --} -- --class MessageReceiver { -- constructor(message) { -- this.broadcasted = false; -- this.message = message; -+ attach(provider) { -+ if (this.receivedOnOpenPayload) { -+ provider.onOpen(this.receivedOnOpenPayload); -+ } -+ if (this.receivedOnStatusPayload) { -+ provider.onStatus(this.receivedOnStatusPayload); -+ } - } -- setBroadcasted(value) { -- this.broadcasted = value; -- return this; -+ detach(provider) { -+ // tell the server to remove the listener - } -- apply(provider, emitSynced = true) { -- const { message } = this; -- const type = message.readVarUint(); -- const emptyMessageLength = message.length(); -- switch (type) { -- case exports.MessageType.Sync: -- this.applySyncMessage(provider, emitSynced); -- break; -- case exports.MessageType.Awareness: -- this.applyAwarenessMessage(provider); -- break; -- case exports.MessageType.Auth: -- this.applyAuthMessage(provider); -- break; -- case exports.MessageType.QueryAwareness: -- this.applyQueryAwarenessMessage(provider); -- break; -- case exports.MessageType.Stateless: -- provider.receiveStateless(readVarString(message.decoder)); -- break; -- default: -- throw new Error(`Can’t apply message of unknown type: ${type}`); -+ setConfiguration(configuration = {}) { -+ this.configuration = { ...this.configuration, ...configuration }; -+ } -+ async connect() { -+ if (this.status === exports.WebSocketStatus.Connected) { -+ return; - } -- // Reply -- if (message.length() > emptyMessageLength + 1) { // length of documentName (considered in emptyMessageLength plus length of yjs sync type, set in applySyncMessage) -- if (this.broadcasted) { -- // TODO: Some weird TypeScript error -- // @ts-ignore -- provider.broadcast(OutgoingMessage, { encoder: message.encoder }); -+ // Always cancel any previously initiated connection retryer instances -+ if (this.cancelWebsocketRetry) { -+ this.cancelWebsocketRetry(); -+ this.cancelWebsocketRetry = undefined; -+ } -+ this.shouldConnect = true; -+ const abortableRetry = () => { -+ let cancelAttempt = false; -+ const retryPromise = attempt.retry(this.createWebSocketConnection.bind(this), { -+ delay: this.configuration.delay, -+ initialDelay: this.configuration.initialDelay, -+ factor: this.configuration.factor, -+ maxAttempts: this.configuration.maxAttempts, -+ minDelay: this.configuration.minDelay, -+ maxDelay: this.configuration.maxDelay, -+ jitter: this.configuration.jitter, -+ timeout: this.configuration.timeout, -+ beforeAttempt: context => { -+ if (!this.shouldConnect || cancelAttempt) { -+ context.abort(); -+ } -+ }, -+ }).catch((error) => { -+ // If we aborted the connection attempt then don’t throw an error -+ // ref: https://github.com/lifeomic/attempt/blob/master/src/index.ts#L136 -+ if (error && error.code !== 'ATTEMPT_ABORTED') { -+ throw error; -+ } -+ }); -+ return { -+ retryPromise, -+ cancelFunc: () => { -+ cancelAttempt = true; -+ }, -+ }; -+ }; -+ const { retryPromise, cancelFunc } = abortableRetry(); -+ this.cancelWebsocketRetry = cancelFunc; -+ return retryPromise; -+ } -+ createWebSocketConnection() { -+ return new Promise((resolve, reject) => { -+ if (this.webSocket) { -+ this.messageQueue = []; -+ this.webSocket.close(); -+ this.webSocket = null; -+ } -+ // Init the WebSocket connection -+ const ws = new this.configuration.WebSocketPolyfill(this.url); -+ ws.binaryType = 'arraybuffer'; -+ ws.onmessage = (payload) => this.emit('message', payload); -+ ws.onclose = (payload) => this.emit('close', { event: payload }); -+ ws.onopen = (payload) => this.emit('open', payload); -+ ws.onerror = (err) => { -+ reject(err); -+ }; -+ this.webSocket = ws; -+ // Reset the status -+ this.status = exports.WebSocketStatus.Connecting; -+ this.emit('status', { status: exports.WebSocketStatus.Connecting }); -+ // Store resolve/reject for later use -+ this.connectionAttempt = { -+ resolve, -+ reject, -+ }; -+ }); -+ } -+ onMessage(event) { -+ this.resolveConnectionAttempt(); -+ } -+ resolveConnectionAttempt() { -+ if (this.connectionAttempt) { -+ this.connectionAttempt.resolve(); -+ this.connectionAttempt = null; -+ this.status = exports.WebSocketStatus.Connected; -+ this.emit('status', { status: exports.WebSocketStatus.Connected }); -+ this.emit('connect'); -+ this.messageQueue.forEach(message => this.send(message)); -+ this.messageQueue = []; -+ } -+ } -+ stopConnectionAttempt() { -+ this.connectionAttempt = null; -+ } -+ rejectConnectionAttempt() { -+ var _a; -+ (_a = this.connectionAttempt) === null || _a === void 0 ? void 0 : _a.reject(); -+ this.connectionAttempt = null; -+ } -+ checkConnection() { -+ var _a; -+ // Don’t check the connection when it’s not even established -+ if (this.status !== exports.WebSocketStatus.Connected) { -+ return; -+ } -+ // Don’t close then connection while waiting for the first message -+ if (!this.lastMessageReceived) { -+ return; -+ } -+ // Don’t close the connection when a message was received recently -+ if (this.configuration.messageReconnectTimeout >= getUnixTime() - this.lastMessageReceived) { -+ return; -+ } -+ // No message received in a long time, not even your own -+ // Awareness updates, which are updated every 15 seconds. -+ (_a = this.webSocket) === null || _a === void 0 ? void 0 : _a.close(); -+ this.messageQueue = []; -+ } -+ registerEventListeners() { -+ if (typeof window === 'undefined') { -+ return; -+ } -+ window.addEventListener('online', this.boundConnect); -+ } -+ // Ensure that the URL always ends with / -+ get serverUrl() { -+ while (this.configuration.url[this.configuration.url.length - 1] === '/') { -+ return this.configuration.url.slice(0, this.configuration.url.length - 1); -+ } -+ return this.configuration.url; -+ } -+ get url() { -+ const encodedParams = encodeQueryParams(this.configuration.parameters); -+ return `${this.serverUrl}${encodedParams.length === 0 ? '' : `?${encodedParams}`}`; -+ } -+ disconnect() { -+ this.shouldConnect = false; -+ if (this.webSocket === null) { -+ return; -+ } -+ try { -+ this.webSocket.close(); -+ this.messageQueue = []; -+ } -+ catch { -+ // -+ } -+ } -+ send(message) { -+ var _a; -+ if (((_a = this.webSocket) === null || _a === void 0 ? void 0 : _a.readyState) === common.WsReadyStates.Open) { -+ this.webSocket.send(message); -+ } -+ else { -+ this.messageQueue.push(message); -+ } -+ } -+ onClose({ event }) { -+ this.webSocket = null; -+ if (this.status === exports.WebSocketStatus.Connected) { -+ this.status = exports.WebSocketStatus.Disconnected; -+ this.emit('status', { status: exports.WebSocketStatus.Disconnected }); -+ this.emit('disconnect', { event }); -+ } -+ if (event.code === common.Unauthorized.code) { -+ if (event.reason === common.Unauthorized.reason) { -+ console.warn('[HocuspocusProvider] An authentication token is required, but you didn’t send one. Try adding a `token` to your HocuspocusProvider configuration. Won’t try again.'); - } - else { -- // TODO: Some weird TypeScript error -- // @ts-ignore -- provider.send(OutgoingMessage, { encoder: message.encoder }); -+ console.warn(`[HocuspocusProvider] Connection closed with status Unauthorized: ${event.reason}`); - } -+ this.shouldConnect = false; -+ } -+ if (event.code === common.Forbidden.code) { -+ if (!this.configuration.quiet) { -+ console.warn('[HocuspocusProvider] The provided authentication token isn’t allowed to connect to this server. Will try again.'); -+ return; // TODO REMOVE ME -+ } -+ } -+ if (event.code === common.MessageTooBig.code) { -+ console.warn(`[HocuspocusProvider] Connection closed with status MessageTooBig: ${event.reason}`); -+ this.shouldConnect = false; -+ } -+ if (this.connectionAttempt) { -+ // That connection attempt failed. -+ this.rejectConnectionAttempt(); -+ } -+ else if (this.shouldConnect) { -+ // The connection was closed by the server. Let’s just try again. -+ this.connect(); -+ } -+ // If we’ll reconnect, we’re done for now. -+ if (this.shouldConnect) { -+ return; -+ } -+ // The status is set correctly already. -+ if (this.status === exports.WebSocketStatus.Disconnected) { -+ return; - } -+ // Let’s update the connection status. -+ this.status = exports.WebSocketStatus.Disconnected; -+ this.emit('status', { status: exports.WebSocketStatus.Disconnected }); -+ this.emit('disconnect', { event }); - } -- applySyncMessage(provider, emitSynced) { -- const { message } = this; -- message.writeVarUint(exports.MessageType.Sync); -- // Apply update -- const syncMessageType = readSyncMessage(message.decoder, message.encoder, provider.document, provider); -- // Synced once we receive Step2 -- if (emitSynced && syncMessageType === messageYjsSyncStep2) { -- provider.synced = true; -+ destroy() { -+ this.emit('destroy'); -+ if (this.intervals.forceSync) { -+ clearInterval(this.intervals.forceSync); - } -- if (syncMessageType === messageYjsUpdate || syncMessageType === messageYjsSyncStep2) { -- if (provider.unsyncedChanges > 0) { -- provider.updateUnsyncedChanges(-1); -- } -+ clearInterval(this.intervals.connectionChecker); -+ // If there is still a connection attempt outstanding then we should stop -+ // it before calling disconnect, otherwise it will be rejected in the onClose -+ // handler and trigger a retry -+ this.stopConnectionAttempt(); -+ this.disconnect(); -+ this.removeAllListeners(); -+ if (typeof window === 'undefined') { -+ return; - } -- } -- applyAwarenessMessage(provider) { -- const { message } = this; -- applyAwarenessUpdate(provider.awareness, message.readVarUint8Array(), provider); -- } -- applyAuthMessage(provider) { -- const { message } = this; -- common.readAuthMessage(message.decoder, provider.permissionDeniedHandler.bind(provider), provider.authenticatedHandler.bind(provider)); -- } -- applyQueryAwarenessMessage(provider) { -- const { message } = this; -- message.writeVarUint(exports.MessageType.Awareness); -- message.writeVarUint8Array(encodeAwarenessUpdate(provider.awareness, Array.from(provider.awareness.getStates().keys()))); -+ window.removeEventListener('online', this.boundConnect); - } - } - --class MessageSender { -- constructor(Message, args = {}) { -- this.message = new Message(); -- this.encoder = this.message.get(args); -+class IncomingMessage { -+ constructor(data) { -+ this.data = data; -+ this.encoder = createEncoder(); -+ this.decoder = createDecoder(new Uint8Array(this.data)); - } -- create() { -- return toUint8Array(this.encoder); -+ readVarUint() { -+ return readVarUint(this.decoder); - } -- send(webSocket) { -- webSocket === null || webSocket === void 0 ? void 0 : webSocket.send(this.create()); -+ readVarString() { -+ return readVarString(this.decoder); - } -- broadcast(channel) { -- publish(channel, this.create()); -+ readVarUint8Array() { -+ return readVarUint8Array(this.decoder); - } --} -- --class SyncStepOneMessage extends OutgoingMessage { -- constructor() { -- super(...arguments); -- this.type = exports.MessageType.Sync; -- this.description = 'First sync step'; -+ writeVarUint(type) { -+ return writeVarUint(this.encoder, type); - } -- get(args) { -- if (typeof args.document === 'undefined') { -- throw new Error('The sync step one message requires document as an argument'); -- } -- writeVarString(this.encoder, args.documentName); -- writeVarUint(this.encoder, this.type); -- writeSyncStep1(this.encoder, args.document); -- return this.encoder; -+ writeVarString(string) { -+ return writeVarString(this.encoder, string); - } --} -- --class SyncStepTwoMessage extends OutgoingMessage { -- constructor() { -- super(...arguments); -- this.type = exports.MessageType.Sync; -- this.description = 'Second sync step'; -+ writeVarUint8Array(data) { -+ return writeVarUint8Array(this.encoder, data); - } -- get(args) { -- if (typeof args.document === 'undefined') { -- throw new Error('The sync step two message requires document as an argument'); -- } -- writeVarString(this.encoder, args.documentName); -- writeVarUint(this.encoder, this.type); -- writeSyncStep2(this.encoder, args.document); -- return this.encoder; -+ length() { -+ return length(this.encoder); - } - } - --class QueryAwarenessMessage extends OutgoingMessage { -- constructor() { -- super(...arguments); -- this.type = exports.MessageType.QueryAwareness; -- this.description = 'Queries awareness states'; -- } -- get(args) { -- console.log('queryAwareness: writing string docName', args.documentName); -- console.log(this.encoder.cpos); -- writeVarString(this.encoder, args.documentName); -- writeVarUint(this.encoder, this.type); -- return this.encoder; -- } --} -+/** -+ * @module sync-protocol -+ */ - --class AuthenticationMessage extends OutgoingMessage { -- constructor() { -- super(...arguments); -- this.type = exports.MessageType.Auth; -- this.description = 'Authentication'; -- } -- get(args) { -- if (typeof args.token === 'undefined') { -- throw new Error('The authentication message requires `token` as an argument.'); -- } -- writeVarString(this.encoder, args.documentName); -- writeVarUint(this.encoder, this.type); -- common.writeAuthentication(this.encoder, args.token); -- return this.encoder; -- } --} -+/** -+ * @typedef {Map} StateMap -+ */ - --class AwarenessMessage extends OutgoingMessage { -- constructor() { -- super(...arguments); -- this.type = exports.MessageType.Awareness; -- this.description = 'Awareness states update'; -- } -- get(args) { -- if (typeof args.awareness === 'undefined') { -- throw new Error('The awareness message requires awareness as an argument'); -- } -- if (typeof args.clients === 'undefined') { -- throw new Error('The awareness message requires clients as an argument'); -- } -- writeVarString(this.encoder, args.documentName); -- writeVarUint(this.encoder, this.type); -- let awarenessUpdate; -- if (args.states === undefined) { -- awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients); -- } -- else { -- awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients, args.states); -- } -- writeVarUint8Array(this.encoder, awarenessUpdate); -- return this.encoder; -- } --} -+/** -+ * Core Yjs defines two message types: -+ * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2. -+ * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it -+ * received all information from the remote client. -+ * -+ * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection -+ * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both -+ * SyncStep2 and SyncDone, it is assured that it is synced to the remote client. -+ * -+ * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1. -+ * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies -+ * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the -+ * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can -+ * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them. -+ * Therefore it is necesarry that the client initiates the sync. -+ * -+ * Construction of a message: -+ * [messageType : varUint, message definition..] -+ * -+ * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol! -+ * -+ * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer) -+ */ - --class UpdateMessage extends OutgoingMessage { -- constructor() { -- super(...arguments); -- this.type = exports.MessageType.Sync; -- this.description = 'A document update'; -- } -- get(args) { -- writeVarString(this.encoder, args.documentName); -- writeVarUint(this.encoder, this.type); -- writeUpdate(this.encoder, args.update); -- return this.encoder; -- } --} -+const messageYjsSyncStep1 = 0; -+const messageYjsSyncStep2 = 1; -+const messageYjsUpdate = 2; -+ -+/** -+ * Create a sync step 1 message based on the state of the current shared document. -+ * -+ * @param {encoding.Encoder} encoder -+ * @param {Y.Doc} doc -+ */ -+const writeSyncStep1 = (encoder, doc) => { -+ writeVarUint(encoder, messageYjsSyncStep1); -+ const sv = Y__namespace.encodeStateVector(doc); -+ writeVarUint8Array(encoder, sv); -+}; -+ -+/** -+ * @param {encoding.Encoder} encoder -+ * @param {Y.Doc} doc -+ * @param {Uint8Array} [encodedStateVector] -+ */ -+const writeSyncStep2 = (encoder, doc, encodedStateVector) => { -+ writeVarUint(encoder, messageYjsSyncStep2); -+ writeVarUint8Array(encoder, Y__namespace.encodeStateAsUpdate(doc, encodedStateVector)); -+}; -+ -+/** -+ * Read SyncStep1 message and reply with SyncStep2. -+ * -+ * @param {decoding.Decoder} decoder The reply to the received message -+ * @param {encoding.Encoder} encoder The received message -+ * @param {Y.Doc} doc -+ */ -+const readSyncStep1 = (decoder, encoder, doc) => -+ writeSyncStep2(encoder, doc, readVarUint8Array(decoder)); -+ -+/** -+ * Read and apply Structs and then DeleteStore to a y instance. -+ * -+ * @param {decoding.Decoder} decoder -+ * @param {Y.Doc} doc -+ * @param {any} transactionOrigin -+ */ -+const readSyncStep2 = (decoder, doc, transactionOrigin) => { -+ try { -+ Y__namespace.applyUpdate(doc, readVarUint8Array(decoder), transactionOrigin); -+ } catch (error) { -+ // This catches errors that are thrown by event handlers -+ console.error('Caught error while handling a Yjs update', error); -+ } -+}; -+ -+/** -+ * @param {encoding.Encoder} encoder -+ * @param {Uint8Array} update -+ */ -+const writeUpdate = (encoder, update) => { -+ writeVarUint(encoder, messageYjsUpdate); -+ writeVarUint8Array(encoder, update); -+}; - - /** -- * Utility module to work with urls. -+ * Read and apply Structs and then DeleteStore to a y instance. - * -- * @module url -+ * @param {decoding.Decoder} decoder -+ * @param {Y.Doc} doc -+ * @param {any} transactionOrigin - */ -+const readUpdate = readSyncStep2; - - /** -- * @param {Object} params -- * @return {string} -+ * @param {decoding.Decoder} decoder A message received from another client -+ * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty. -+ * @param {Y.Doc} doc -+ * @param {any} transactionOrigin - */ --const encodeQueryParams = params => -- map(params, (val, key) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&'); -+const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => { -+ const messageType = readVarUint(decoder); -+ switch (messageType) { -+ case messageYjsSyncStep1: -+ readSyncStep1(decoder, encoder, doc); -+ break -+ case messageYjsSyncStep2: -+ readSyncStep2(decoder, doc, transactionOrigin); -+ break -+ case messageYjsUpdate: -+ readUpdate(decoder, doc, transactionOrigin); -+ break -+ default: -+ throw new Error('Unknown message type') -+ } -+ return messageType -+}; - --class HocuspocusProviderWebsocket extends EventEmitter { -- constructor(configuration) { -- super(); -- this.configuration = { -- url: '', -- // @ts-ignore -- document: undefined, -- // @ts-ignore -- awareness: undefined, -- WebSocketPolyfill: undefined, -- parameters: {}, -- connect: true, -- broadcast: true, -- forceSyncInterval: false, -- // TODO: this should depend on awareness.outdatedTime -- messageReconnectTimeout: 30000, -- // 1 second -- delay: 1000, -- // instant -- initialDelay: 0, -- // double the delay each time -- factor: 2, -- // unlimited retries -- maxAttempts: 0, -- // wait at least 1 second -- minDelay: 1000, -- // at least every 30 seconds -- maxDelay: 30000, -- // randomize -- jitter: true, -- // retry forever -- timeout: 0, -- onOpen: () => null, -- onConnect: () => null, -- onMessage: () => null, -- onOutgoingMessage: () => null, -- onStatus: () => null, -- onDisconnect: () => null, -- onClose: () => null, -- onDestroy: () => null, -- onAwarenessUpdate: () => null, -- onAwarenessChange: () => null, -- quiet: false, -- }; -- this.subscribedToBroadcastChannel = false; -- this.webSocket = null; -- this.shouldConnect = true; -- this.status = exports.WebSocketStatus.Disconnected; -- this.lastMessageReceived = 0; -- this.mux = createMutex(); -- this.intervals = { -- forceSync: null, -- connectionChecker: null, -- }; -- this.connectionAttempt = null; -- this.receivedOnOpenPayload = undefined; -- this.receivedOnStatusPayload = undefined; -- this.boundConnect = this.connect.bind(this); -- this.setConfiguration(configuration); -- this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill ? configuration.WebSocketPolyfill : WebSocket; -- this.on('open', this.configuration.onOpen); -- this.on('open', this.onOpen.bind(this)); -- this.on('connect', this.configuration.onConnect); -- this.on('message', this.configuration.onMessage); -- this.on('outgoingMessage', this.configuration.onOutgoingMessage); -- this.on('status', this.configuration.onStatus); -- this.on('status', this.onStatus.bind(this)); -- this.on('disconnect', this.configuration.onDisconnect); -- this.on('close', this.configuration.onClose); -- this.on('destroy', this.configuration.onDestroy); -- this.on('awarenessUpdate', this.configuration.onAwarenessUpdate); -- this.on('awarenessChange', this.configuration.onAwarenessChange); -- this.on('close', this.onClose.bind(this)); -- this.on('message', this.onMessage.bind(this)); -- this.registerEventListeners(); -- this.intervals.connectionChecker = setInterval(this.checkConnection.bind(this), this.configuration.messageReconnectTimeout / 10); -- if (typeof configuration.connect !== 'undefined') { -- this.shouldConnect = configuration.connect; -- } -- if (!this.shouldConnect) { -- return; -- } -- this.connect(); -- } -- async onOpen(event) { -- this.receivedOnOpenPayload = event; -+class OutgoingMessage { -+ constructor() { -+ this.encoder = createEncoder(); - } -- async onStatus(data) { -- this.receivedOnStatusPayload = data; -+ get(args) { -+ return args.encoder; - } -- attach(provider) { -- if (this.receivedOnOpenPayload) { -- provider.onOpen(this.receivedOnOpenPayload); -- } -- if (this.receivedOnStatusPayload) { -- provider.onStatus(this.receivedOnStatusPayload); -- } -+ toUint8Array() { -+ return toUint8Array(this.encoder); - } -- detach(provider) { -- // tell the server to remove the listener -+} -+ -+class MessageReceiver { -+ constructor(message) { -+ this.broadcasted = false; -+ this.message = message; - } -- setConfiguration(configuration = {}) { -- this.configuration = { ...this.configuration, ...configuration }; -+ setBroadcasted(value) { -+ this.broadcasted = value; -+ return this; - } -- async connect() { -- if (this.status === exports.WebSocketStatus.Connected) { -- return; -- } -- // Always cancel any previously initiated connection retryer instances -- if (this.cancelWebsocketRetry) { -- this.cancelWebsocketRetry(); -- this.cancelWebsocketRetry = undefined; -+ apply(provider, emitSynced) { -+ const { message } = this; -+ const type = message.readVarUint(); -+ const emptyMessageLength = message.length(); -+ switch (type) { -+ case exports.MessageType.Sync: -+ this.applySyncMessage(provider, emitSynced); -+ break; -+ case exports.MessageType.Awareness: -+ this.applyAwarenessMessage(provider); -+ break; -+ case exports.MessageType.Auth: -+ this.applyAuthMessage(provider); -+ break; -+ case exports.MessageType.QueryAwareness: -+ this.applyQueryAwarenessMessage(provider); -+ break; -+ case exports.MessageType.Stateless: -+ provider.receiveStateless(readVarString(message.decoder)); -+ break; -+ case exports.MessageType.SyncStatus: -+ this.applySyncStatusMessage(provider, readVarInt(message.decoder) === 1); -+ break; -+ default: -+ throw new Error(`Can’t apply message of unknown type: ${type}`); - } -- this.shouldConnect = true; -- const abortableRetry = () => { -- let cancelAttempt = false; -- const retryPromise = attempt.retry(this.createWebSocketConnection.bind(this), { -- delay: this.configuration.delay, -- initialDelay: this.configuration.initialDelay, -- factor: this.configuration.factor, -- maxAttempts: this.configuration.maxAttempts, -- minDelay: this.configuration.minDelay, -- maxDelay: this.configuration.maxDelay, -- jitter: this.configuration.jitter, -- timeout: this.configuration.timeout, -- beforeAttempt: context => { -- if (!this.shouldConnect || cancelAttempt) { -- context.abort(); -- } -- }, -- }).catch((error) => { -- // If we aborted the connection attempt then don’t throw an error -- // ref: https://github.com/lifeomic/attempt/blob/master/src/index.ts#L136 -- if (error && error.code !== 'ATTEMPT_ABORTED') { -- throw error; -- } -- }); -- return { -- retryPromise, -- cancelFunc: () => { -- cancelAttempt = true; -- }, -- }; -- }; -- const { retryPromise, cancelFunc } = abortableRetry(); -- this.cancelWebsocketRetry = cancelFunc; -- return retryPromise; -- } -- createWebSocketConnection() { -- return new Promise((resolve, reject) => { -- if (this.webSocket) { -- this.webSocket.close(); -- this.webSocket = null; -+ // Reply -+ if (message.length() > emptyMessageLength + 1) { // length of documentName (considered in emptyMessageLength plus length of yjs sync type, set in applySyncMessage) -+ if (this.broadcasted) { -+ // TODO: Some weird TypeScript error -+ // @ts-ignore -+ provider.broadcast(OutgoingMessage, { encoder: message.encoder }); - } -- // Init the WebSocket connection -- const ws = new this.configuration.WebSocketPolyfill(this.url); -- ws.binaryType = 'arraybuffer'; -- ws.onmessage = (payload) => this.emit('message', payload); -- ws.onclose = (payload) => this.emit('close', { event: payload }); -- ws.onopen = (payload) => this.emit('open', payload); -- ws.onerror = (err) => { -- reject(err); -- }; -- this.webSocket = ws; -- // Reset the status -- this.status = exports.WebSocketStatus.Connecting; -- this.emit('status', { status: exports.WebSocketStatus.Connecting }); -- // Store resolve/reject for later use -- this.connectionAttempt = { -- resolve, -- reject, -- }; -- }); -+ else { -+ // TODO: Some weird TypeScript error -+ // @ts-ignore -+ provider.send(OutgoingMessage, { encoder: message.encoder }); -+ } -+ } - } -- onMessage(event) { -- this.resolveConnectionAttempt(); -+ applySyncMessage(provider, emitSynced) { -+ const { message } = this; -+ message.writeVarUint(exports.MessageType.Sync); -+ // Apply update -+ const syncMessageType = readSyncMessage(message.decoder, message.encoder, provider.document, provider); -+ // Synced once we receive Step2 -+ if (emitSynced && syncMessageType === messageYjsSyncStep2) { -+ provider.synced = true; -+ } - } -- resolveConnectionAttempt() { -- if (this.connectionAttempt) { -- this.connectionAttempt.resolve(); -- this.connectionAttempt = null; -- this.status = exports.WebSocketStatus.Connected; -- this.emit('status', { status: exports.WebSocketStatus.Connected }); -- this.emit('connect'); -+ applySyncStatusMessage(provider, applied) { -+ if (applied) { -+ provider.decrementUnsyncedChanges(); - } - } -- stopConnectionAttempt() { -- this.connectionAttempt = null; -+ applyAwarenessMessage(provider) { -+ const { message } = this; -+ applyAwarenessUpdate(provider.awareness, message.readVarUint8Array(), provider); - } -- rejectConnectionAttempt() { -- var _a; -- (_a = this.connectionAttempt) === null || _a === void 0 ? void 0 : _a.reject(); -- this.connectionAttempt = null; -+ applyAuthMessage(provider) { -+ const { message } = this; -+ common.readAuthMessage(message.decoder, provider.permissionDeniedHandler.bind(provider), provider.authenticatedHandler.bind(provider)); - } -- checkConnection() { -- var _a; -- // Don’t check the connection when it’s not even established -- if (this.status !== exports.WebSocketStatus.Connected) { -- return; -- } -- // Don’t close then connection while waiting for the first message -- if (!this.lastMessageReceived) { -- return; -- } -- // Don’t close the connection when a message was received recently -- if (this.configuration.messageReconnectTimeout >= getUnixTime() - this.lastMessageReceived) { -- return; -- } -- // No message received in a long time, not even your own -- // Awareness updates, which are updated every 15 seconds. -- (_a = this.webSocket) === null || _a === void 0 ? void 0 : _a.close(); -+ applyQueryAwarenessMessage(provider) { -+ const { message } = this; -+ message.writeVarUint(exports.MessageType.Awareness); -+ message.writeVarUint8Array(encodeAwarenessUpdate(provider.awareness, Array.from(provider.awareness.getStates().keys()))); - } -- registerEventListeners() { -- if (typeof window === 'undefined') { -- return; -- } -- window.addEventListener('online', this.boundConnect); -+} -+ -+class MessageSender { -+ constructor(Message, args = {}) { -+ this.message = new Message(); -+ this.encoder = this.message.get(args); - } -- // Ensure that the URL always ends with / -- get serverUrl() { -- while (this.configuration.url[this.configuration.url.length - 1] === '/') { -- return this.configuration.url.slice(0, this.configuration.url.length - 1); -- } -- return this.configuration.url; -+ create() { -+ return toUint8Array(this.encoder); - } -- get url() { -- const encodedParams = encodeQueryParams(this.configuration.parameters); -- return `${this.serverUrl}${encodedParams.length === 0 ? '' : `?${encodedParams}`}`; -+ send(webSocket) { -+ webSocket === null || webSocket === void 0 ? void 0 : webSocket.send(this.create()); - } -- disconnect() { -- this.shouldConnect = false; -- if (this.webSocket === null) { -- return; -- } -- try { -- this.webSocket.close(); -- } -- catch { -- // -- } -+ broadcast(channel) { -+ publish(channel, this.create()); - } -- send(message) { -- var _a; -- if (((_a = this.webSocket) === null || _a === void 0 ? void 0 : _a.readyState) === common.WsReadyStates.Open) { -- this.webSocket.send(message); -- } -+} -+ -+class AuthenticationMessage extends OutgoingMessage { -+ constructor() { -+ super(...arguments); -+ this.type = exports.MessageType.Auth; -+ this.description = 'Authentication'; - } -- onClose({ event }) { -- this.webSocket = null; -- if (this.status === exports.WebSocketStatus.Connected) { -- this.status = exports.WebSocketStatus.Disconnected; -- this.emit('status', { status: exports.WebSocketStatus.Disconnected }); -- this.emit('disconnect', { event }); -- } -- if (event.code === common.Unauthorized.code) { -- if (event.reason === common.Unauthorized.reason) { -- console.warn('[HocuspocusProvider] An authentication token is required, but you didn’t send one. Try adding a `token` to your HocuspocusProvider configuration. Won’t try again.'); -- } -- else { -- console.warn(`[HocuspocusProvider] Connection closed with status Unauthorized: ${event.reason}`); -- } -- this.shouldConnect = false; -- } -- if (event.code === common.Forbidden.code) { -- if (!this.configuration.quiet) { -- console.warn('[HocuspocusProvider] The provided authentication token isn’t allowed to connect to this server. Will try again.'); -- return; // TODO REMOVE ME -- } -- } -- if (event.code === common.MessageTooBig.code) { -- console.warn(`[HocuspocusProvider] Connection closed with status MessageTooBig: ${event.reason}`); -- this.shouldConnect = false; -+ get(args) { -+ if (typeof args.token === 'undefined') { -+ throw new Error('The authentication message requires `token` as an argument.'); - } -- if (this.connectionAttempt) { -- // That connection attempt failed. -- this.rejectConnectionAttempt(); -+ writeVarString(this.encoder, args.documentName); -+ writeVarUint(this.encoder, this.type); -+ common.writeAuthentication(this.encoder, args.token); -+ return this.encoder; -+ } -+} -+ -+class AwarenessMessage extends OutgoingMessage { -+ constructor() { -+ super(...arguments); -+ this.type = exports.MessageType.Awareness; -+ this.description = 'Awareness states update'; -+ } -+ get(args) { -+ if (typeof args.awareness === 'undefined') { -+ throw new Error('The awareness message requires awareness as an argument'); - } -- else if (this.shouldConnect) { -- // The connection was closed by the server. Let’s just try again. -- this.connect(); -+ if (typeof args.clients === 'undefined') { -+ throw new Error('The awareness message requires clients as an argument'); - } -- // If we’ll reconnect, we’re done for now. -- if (this.shouldConnect) { -- return; -+ writeVarString(this.encoder, args.documentName); -+ writeVarUint(this.encoder, this.type); -+ let awarenessUpdate; -+ if (args.states === undefined) { -+ awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients); - } -- // The status is set correctly already. -- if (this.status === exports.WebSocketStatus.Disconnected) { -- return; -+ else { -+ awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients, args.states); - } -- // Let’s update the connection status. -- this.status = exports.WebSocketStatus.Disconnected; -- this.emit('status', { status: exports.WebSocketStatus.Disconnected }); -- this.emit('disconnect', { event }); -+ writeVarUint8Array(this.encoder, awarenessUpdate); -+ return this.encoder; - } -- destroy() { -- this.emit('destroy'); -- if (this.intervals.forceSync) { -- clearInterval(this.intervals.forceSync); -- } -- clearInterval(this.intervals.connectionChecker); -- // If there is still a connection attempt outstanding then we should stop -- // it before calling disconnect, otherwise it will be rejected in the onClose -- // handler and trigger a retry -- this.stopConnectionAttempt(); -- this.disconnect(); -- this.removeAllListeners(); -- if (typeof window === 'undefined') { -- return; -- } -- window.removeEventListener('online', this.boundConnect); -+} -+ -+class CloseMessage extends OutgoingMessage { -+ constructor() { -+ super(...arguments); -+ this.type = exports.MessageType.CLOSE; -+ this.description = 'Ask the server to close the connection'; -+ } -+ get(args) { -+ writeVarString(this.encoder, args.documentName); -+ writeVarUint(this.encoder, this.type); -+ return this.encoder; -+ } -+} -+ -+class QueryAwarenessMessage extends OutgoingMessage { -+ constructor() { -+ super(...arguments); -+ this.type = exports.MessageType.QueryAwareness; -+ this.description = 'Queries awareness states'; -+ } -+ get(args) { -+ console.log('queryAwareness: writing string docName', args.documentName); -+ console.log(this.encoder.cpos); -+ writeVarString(this.encoder, args.documentName); -+ writeVarUint(this.encoder, this.type); -+ return this.encoder; - } - } - -@@ -2289,15 +2306,50 @@ class StatelessMessage extends OutgoingMessage { - } - } - --class CloseMessage extends OutgoingMessage { -+class SyncStepOneMessage extends OutgoingMessage { - constructor() { - super(...arguments); -- this.type = exports.MessageType.CLOSE; -- this.description = 'Ask the server to close the connection'; -+ this.type = exports.MessageType.Sync; -+ this.description = 'First sync step'; -+ } -+ get(args) { -+ if (typeof args.document === 'undefined') { -+ throw new Error('The sync step one message requires document as an argument'); -+ } -+ writeVarString(this.encoder, args.documentName); -+ writeVarUint(this.encoder, this.type); -+ writeSyncStep1(this.encoder, args.document); -+ return this.encoder; -+ } -+} -+ -+class SyncStepTwoMessage extends OutgoingMessage { -+ constructor() { -+ super(...arguments); -+ this.type = exports.MessageType.Sync; -+ this.description = 'Second sync step'; -+ } -+ get(args) { -+ if (typeof args.document === 'undefined') { -+ throw new Error('The sync step two message requires document as an argument'); -+ } -+ writeVarString(this.encoder, args.documentName); -+ writeVarUint(this.encoder, this.type); -+ writeSyncStep2(this.encoder, args.document); -+ return this.encoder; -+ } -+} -+ -+class UpdateMessage extends OutgoingMessage { -+ constructor() { -+ super(...arguments); -+ this.type = exports.MessageType.Sync; -+ this.description = 'A document update'; - } - get(args) { - writeVarString(this.encoder, args.documentName); - writeVarUint(this.encoder, this.type); -+ writeUpdate(this.encoder, args.update); - return this.encoder; - } - } -@@ -2408,8 +2460,15 @@ class HocuspocusProvider extends EventEmitter { - get hasUnsyncedChanges() { - return this.unsyncedChanges > 0; - } -- updateUnsyncedChanges(unsyncedChanges = 0) { -- this.unsyncedChanges += unsyncedChanges; -+ incrementUnsyncedChanges() { -+ this.unsyncedChanges += 1; -+ this.emit('unsyncedChanges', this.unsyncedChanges); -+ } -+ decrementUnsyncedChanges() { -+ this.unsyncedChanges -= 1; -+ if (this.unsyncedChanges === 0) { -+ this.synced = true; -+ } - this.emit('unsyncedChanges', this.unsyncedChanges); - } - forceSync() { -@@ -2431,7 +2490,7 @@ class HocuspocusProvider extends EventEmitter { - if (origin === this) { - return; - } -- this.updateUnsyncedChanges(1); -+ this.incrementUnsyncedChanges(); - this.send(UpdateMessage, { update, documentName: this.configuration.name }, true); - } - awarenessUpdateHandler({ added, updated, removed }, origin) { -@@ -2449,9 +2508,6 @@ class HocuspocusProvider extends EventEmitter { - if (this.isSynced === state) { - return; - } -- if (state && this.unsyncedChanges > 0) { -- this.updateUnsyncedChanges(-1 * this.unsyncedChanges); -- } - this.isSynced = state; - this.emit('synced', { state }); - this.emit('sync', { state }); -@@ -2489,6 +2545,7 @@ class HocuspocusProvider extends EventEmitter { - return this.configuration.token; - } - startSync() { -+ this.incrementUnsyncedChanges(); - this.send(SyncStepOneMessage, { document: this.document, documentName: this.configuration.name }); - if (this.awareness.getLocalState() !== null) { - this.send(AwarenessMessage, { -@@ -2499,8 +2556,9 @@ class HocuspocusProvider extends EventEmitter { - } - } - send(message, args, broadcast = false) { -- if (!this.isConnected) -+ if (!this.isConnected) { - return; -+ } - if (broadcast) { - this.mux(() => { this.broadcast(message, args); }); - } -@@ -2516,7 +2574,7 @@ class HocuspocusProvider extends EventEmitter { - } - message.writeVarString(documentName); - this.emit('message', { event, message: new IncomingMessage(event.data) }); -- new MessageReceiver(message).apply(this); -+ new MessageReceiver(message).apply(this, true); - } - onClose(event) { - this.isAuthenticated = false; -diff --git a/node_modules/@hocuspocus/provider/dist/hocuspocus-provider.cjs.map b/node_modules/@hocuspocus/provider/dist/hocuspocus-provider.cjs.map -index 1f1c0d8..0a4f5b5 100644 ---- a/node_modules/@hocuspocus/provider/dist/hocuspocus-provider.cjs.map -+++ b/node_modules/@hocuspocus/provider/dist/hocuspocus-provider.cjs.map -@@ -1 +1 @@ --{"version":3,"file":"hocuspocus-provider.cjs","sources":["../../../node_modules/lib0/map.js","../../../node_modules/lib0/set.js","../../../node_modules/lib0/string.js","../../../node_modules/lib0/conditions.js","../../../node_modules/lib0/storage.js","../../../node_modules/lib0/array.js","../../../node_modules/lib0/object.js","../../../node_modules/lib0/function.js","../../../node_modules/lib0/environment.js","../../../node_modules/lib0/math.js","../../../node_modules/lib0/binary.js","../../../node_modules/lib0/number.js","../../../node_modules/lib0/encoding.js","../../../node_modules/lib0/error.js","../../../node_modules/lib0/decoding.js","../../../node_modules/lib0/buffer.js","../../../node_modules/lib0/broadcastchannel.js","../../../node_modules/lib0/time.js","../../../node_modules/lib0/observable.js","../../../node_modules/y-protocols/awareness.js","../../../node_modules/lib0/mutex.js","../src/EventEmitter.ts","../src/IncomingMessage.ts","../../../node_modules/y-protocols/sync.js","../src/types.ts","../src/OutgoingMessage.ts","../src/MessageReceiver.ts","../src/MessageSender.ts","../src/OutgoingMessages/SyncStepOneMessage.ts","../src/OutgoingMessages/SyncStepTwoMessage.ts","../src/OutgoingMessages/QueryAwarenessMessage.ts","../src/OutgoingMessages/AuthenticationMessage.ts","../src/OutgoingMessages/AwarenessMessage.ts","../src/OutgoingMessages/UpdateMessage.ts","../../../node_modules/lib0/url.js","../src/HocuspocusProviderWebsocket.ts","../src/OutgoingMessages/StatelessMessage.ts","../src/OutgoingMessages/CloseMessage.ts","../src/HocuspocusProvider.ts","../src/TiptapCollabProviderWebsocket.ts","../src/TiptapCollabProvider.ts"],"sourcesContent":["/**\n * Utility module to work with key-value stores.\n *\n * @module map\n */\n\n/**\n * Creates a new Map instance.\n *\n * @function\n * @return {Map}\n *\n * @function\n */\nexport const create = () => new Map()\n\n/**\n * Copy a Map object into a fresh Map object.\n *\n * @function\n * @template X,Y\n * @param {Map} m\n * @return {Map}\n */\nexport const copy = m => {\n const r = create()\n m.forEach((v, k) => { r.set(k, v) })\n return r\n}\n\n/**\n * Get map property. Create T if property is undefined and set T on map.\n *\n * ```js\n * const listeners = map.setIfUndefined(events, 'eventName', set.create)\n * listeners.add(listener)\n * ```\n *\n * @function\n * @template V,K\n * @template {Map} MAP\n * @param {MAP} map\n * @param {K} key\n * @param {function():V} createT\n * @return {V}\n */\nexport const setIfUndefined = (map, key, createT) => {\n let set = map.get(key)\n if (set === undefined) {\n map.set(key, set = createT())\n }\n return set\n}\n\n/**\n * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function.\n *\n * @function\n * @template K\n * @template V\n * @template R\n * @param {Map} m\n * @param {function(V,K):R} f\n * @return {Array}\n */\nexport const map = (m, f) => {\n const res = []\n for (const [key, value] of m) {\n res.push(f(value, key))\n }\n return res\n}\n\n/**\n * Tests whether any key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @todo should rename to some - similarly to Array.some\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const any = (m, f) => {\n for (const [key, value] of m) {\n if (f(value, key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * Tests whether all key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const all = (m, f) => {\n for (const [key, value] of m) {\n if (!f(value, key)) {\n return false\n }\n }\n return true\n}\n","/**\n * Utility module to work with sets.\n *\n * @module set\n */\n\nexport const create = () => new Set()\n\n/**\n * @template T\n * @param {Set} set\n * @return {Array}\n */\nexport const toArray = set => Array.from(set)\n\n/**\n * @template T\n * @param {Set} set\n * @return {T}\n */\nexport const first = set =>\n set.values().next().value || undefined\n\n/**\n * @template T\n * @param {Iterable} entries\n * @return {Set}\n */\nexport const from = entries => new Set(entries)\n","/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* c8 ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* c8 ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* c8 ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* c8 ignore start */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* c8 ignore next */\n utf8TextDecoder = null\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* c8 ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n","/**\n * Often used conditions.\n *\n * @module conditions\n */\n\n/**\n * @template T\n * @param {T|null|undefined} v\n * @return {T|null}\n */\n/* c8 ignore next */\nexport const undefinedToNull = v => v === undefined ? null : v\n","/* eslint-env browser */\n\n/**\n * Isomorphic variable storage.\n *\n * Uses LocalStorage in the browser and falls back to in-memory storage.\n *\n * @module storage\n */\n\n/* c8 ignore start */\nclass VarStoragePolyfill {\n constructor () {\n this.map = new Map()\n }\n\n /**\n * @param {string} key\n * @param {any} newValue\n */\n setItem (key, newValue) {\n this.map.set(key, newValue)\n }\n\n /**\n * @param {string} key\n */\n getItem (key) {\n return this.map.get(key)\n }\n}\n/* c8 ignore stop */\n\n/**\n * @type {any}\n */\nlet _localStorage = new VarStoragePolyfill()\nlet usePolyfill = true\n\n/* c8 ignore start */\ntry {\n // if the same-origin rule is violated, accessing localStorage might thrown an error\n if (typeof localStorage !== 'undefined') {\n _localStorage = localStorage\n usePolyfill = false\n }\n} catch (e) { }\n/* c8 ignore stop */\n\n/**\n * This is basically localStorage in browser, or a polyfill in nodejs\n */\n/* c8 ignore next */\nexport const varStorage = _localStorage\n\n/**\n * A polyfill for `addEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler))\n\n/**\n * A polyfill for `removeEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler))\n","/**\n * Utility module to work with Arrays.\n *\n * @module array\n */\n\nimport * as set from './set.js'\n\n/**\n * Return the last element of an array. The element must exist\n *\n * @template L\n * @param {ArrayLike} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array}\n */\nexport const create = () => /** @type {Array} */ ([])\n\n/**\n * @template D\n * @param {Array} a\n * @return {Array}\n */\nexport const copy = a => /** @type {Array} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array} dest\n * @param {Array} src\n */\nexport const appendTo = (dest, src) => {\n for (let i = 0; i < src.length; i++) {\n dest.push(src[i])\n }\n}\n\n/**\n * Transforms something array-like to an actual Array.\n *\n * @function\n * @template T\n * @param {ArrayLike|Iterable} arraylike\n * @return {T}\n */\nexport const from = Array.from\n\n/**\n * True iff condition holds on every element in the Array.\n *\n * @function\n * @template ITEM\n * @template {ArrayLike} ARR\n *\n * @param {ARR} arr\n * @param {function(ITEM, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const every = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (!f(arr[i], i, arr)) {\n return false\n }\n }\n return true\n}\n\n/**\n * True iff condition holds on some element in the Array.\n *\n * @function\n * @template S\n * @template {ArrayLike} ARR\n * @param {ARR} arr\n * @param {function(S, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const some = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (f(arr[i], i, arr)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @template ELEM\n *\n * @param {ArrayLike} a\n * @param {ArrayLike} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a.length === b.length && every(a, (item, index) => item === b[index])\n\n/**\n * @template ELEM\n * @param {Array>} arr\n * @return {Array}\n */\nexport const flatten = arr => arr.reduce((acc, val) => acc.concat(val), [])\n\nexport const isArray = Array.isArray\n\n/**\n * @template T\n * @param {Array} arr\n * @return {Array}\n */\nexport const unique = arr => from(set.from(arr))\n\n/**\n * @template T\n * @template M\n * @param {ArrayLike} arr\n * @param {function(T):M} mapper\n * @return {Array}\n */\nexport const uniqueBy = (arr, mapper) => {\n /**\n * @type {Set}\n */\n const happened = set.create()\n /**\n * @type {Array}\n */\n const result = []\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i]\n const mapped = mapper(el)\n if (!happened.has(mapped)) {\n happened.add(mapped)\n result.push(el)\n }\n }\n return result\n}\n","/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object} obj\n */\nexport const keys = Object.keys\n\n/**\n * @template V\n * @param {{[k:string]:V}} obj\n * @param {function(V,string):any} f\n */\nexport const forEach = (obj, f) => {\n for (const key in obj) {\n f(obj[key], key)\n }\n}\n\n/**\n * @todo implement mapToArray & map\n *\n * @template R\n * @param {Object} obj\n * @param {function(any,string):R} f\n * @return {Array}\n */\nexport const map = (obj, f) => {\n const results = []\n for (const key in obj) {\n results.push(f(obj[key], key))\n }\n return results\n}\n\n/**\n * @param {Object} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n for (const key in obj) {\n if (f(obj[key], key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {Object|undefined} obj\n */\nexport const isEmpty = obj => {\n for (const _k in obj) {\n return false\n }\n return true\n}\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n for (const key in obj) {\n if (!f(obj[key], key)) {\n return false\n }\n }\n return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object} a\n * @param {Object} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val))\n","/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array} fs\n * @param {Array} args\n */\nexport const callAll = (fs, args, i = 0) => {\n try {\n for (; i < fs.length; i++) {\n fs[i](...args)\n }\n } finally {\n if (i < fs.length) {\n callAll(fs, args, i + 1)\n }\n }\n}\n\nexport const nop = () => {}\n\n/**\n * @template T\n * @param {function():T} f\n * @return {T}\n */\nexport const apply = f => f()\n\n/**\n * @template A\n *\n * @param {A} a\n * @return {A}\n */\nexport const id = a => a\n\n/**\n * @template T\n *\n * @param {T} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equalityStrict = (a, b) => a === b\n\n/**\n * @template T\n *\n * @param {Array|object} a\n * @param {Array|object} b\n * @return {boolean}\n */\nexport const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((a instanceof Array && array.equalFlat(a, /** @type {Array} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/* c8 ignore start */\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a == null || b == null) {\n return equalityStrict(a, b)\n }\n if (a.constructor !== b.constructor) {\n return false\n }\n if (a === b) {\n return true\n }\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n break\n }\n case Map: {\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n return false\n }\n }\n break\n }\n case Object:\n if (object.length(a) !== object.length(b)) {\n return false\n }\n for (const key in a) {\n if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n return false\n }\n }\n break\n case Array:\n if (a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!equalityDeep(a[i], b[i])) {\n return false\n }\n }\n break\n default:\n return false\n }\n return true\n}\n\n/**\n * @template V\n * @template {V} OPTS\n *\n * @param {V} value\n * @param {Array} options\n */\n// @ts-ignore\nexport const isOneOf = (value, options) => options.includes(value)\n/* c8 ignore stop */\n","/**\n * Isomorphic module to work access the environment (query params, env variables).\n *\n * @module map\n */\n\nimport * as map from './map.js'\nimport * as string from './string.js'\nimport * as conditions from './conditions.js'\nimport * as storage from './storage.js'\nimport * as f from './function.js'\n\n/* c8 ignore next */\n// @ts-ignore\nexport const isNode = typeof process !== 'undefined' && process.release &&\n /node|io\\.js/.test(process.release.name)\n/* c8 ignore next */\nexport const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && !isNode\n/* c8 ignore next 3 */\nexport const isMac = typeof navigator !== 'undefined'\n ? /Mac/.test(navigator.platform)\n : false\n\n/**\n * @type {Map}\n */\nlet params\nconst args = []\n\n/* c8 ignore start */\nconst computeParams = () => {\n if (params === undefined) {\n if (isNode) {\n params = map.create()\n const pargs = process.argv\n let currParamName = null\n for (let i = 0; i < pargs.length; i++) {\n const parg = pargs[i]\n if (parg[0] === '-') {\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n currParamName = parg\n } else {\n if (currParamName !== null) {\n params.set(currParamName, parg)\n currParamName = null\n } else {\n args.push(parg)\n }\n }\n }\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n // in ReactNative for example this would not be true (unless connected to the Remote Debugger)\n } else if (typeof location === 'object') {\n params = map.create(); // eslint-disable-next-line no-undef\n (location.search || '?').slice(1).split('&').forEach((kv) => {\n if (kv.length !== 0) {\n const [key, value] = kv.split('=')\n params.set(`--${string.fromCamelCase(key, '-')}`, value)\n params.set(`-${string.fromCamelCase(key, '-')}`, value)\n }\n })\n } else {\n params = map.create()\n }\n }\n return params\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next */\nexport const hasParam = (name) => computeParams().has(name)\n\n/**\n * @param {string} name\n * @param {string} defaultVal\n * @return {string}\n */\n/* c8 ignore next 2 */\nexport const getParam = (name, defaultVal) =>\n computeParams().get(name) || defaultVal\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 4 */\nexport const getVariable = (name) =>\n isNode\n ? conditions.undefinedToNull(process.env[name.toUpperCase()])\n : conditions.undefinedToNull(storage.varStorage.getItem(name))\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 2 */\nexport const getConf = (name) =>\n computeParams().get('--' + name) || getVariable(name)\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next 2 */\nexport const hasConf = (name) =>\n hasParam('--' + name) || getVariable(name) !== null\n\n/* c8 ignore next */\nexport const production = hasConf('production')\n\n/* c8 ignore next 2 */\nconst forceColor = isNode &&\n f.isOneOf(process.env.FORCE_COLOR, ['true', '1', '2'])\n\n/* c8 ignore start */\nexport const supportsColor = !hasParam('no-colors') &&\n (!isNode || process.stdout.isTTY || forceColor) && (\n !isNode || hasParam('color') || forceColor ||\n getVariable('COLORTERM') !== null ||\n (getVariable('TERM') || '').includes('color')\n)\n/* c8 ignore stop */\n","/**\n * Common Math expressions.\n *\n * @module math\n */\n\nexport const floor = Math.floor\nexport const ceil = Math.ceil\nexport const abs = Math.abs\nexport const imul = Math.imul\nexport const round = Math.round\nexport const log10 = Math.log10\nexport const log2 = Math.log2\nexport const log = Math.log\nexport const sqrt = Math.sqrt\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The sum of a and b\n */\nexport const add = (a, b) => a + b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The smaller element of a and b\n */\nexport const min = (a, b) => a < b ? a : b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The bigger element of a and b\n */\nexport const max = (a, b) => a > b ? a : b\n\nexport const isNaN = Number.isNaN\n\nexport const pow = Math.pow\n/**\n * Base 10 exponential function. Returns the value of 10 raised to the power of pow.\n *\n * @param {number} exp\n * @return {number}\n */\nexport const exp10 = exp => Math.pow(10, exp)\n\nexport const sign = Math.sign\n\n/**\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\n/**\n * @type {number}\n */\nexport const HIGHEST_INT32 = binary.BITS31\n\n/**\n * @module number\n */\n\n/* c8 ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n","/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\nimport * as string from './string.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nexport const verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer. Max encodable integer is 2^53.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num = math.floor(num / 64) // shift >>> 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n}\n\n/**\n * A cache to store strings temporarily\n */\nconst _strBuffer = new Uint8Array(30000)\nconst _maxStrBSize = _strBuffer.length / 3\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringNative = (encoder, str) => {\n if (str.length < _maxStrBSize) {\n // We can encode the string into the existing buffer\n /* c8 ignore next */\n const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0\n writeVarUint(encoder, written)\n for (let i = 0; i < written; i++) {\n write(encoder, _strBuffer[i])\n }\n } else {\n writeVarUint8Array(encoder, string.encodeUtf8(str))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringPolyfill = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\n/* c8 ignore next */\nexport const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && math.abs(data) <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (data instanceof Array) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n","/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* c8 ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n","/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as binary from './binary.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as string from './string.js'\nimport * as error from './error.js'\n\nconst errorUnexpectedEndOfArray = error.create('Unexpected end of array')\nconst errorIntegerOutOfRange = error.create('Integer out of Range')\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n */\nexport class Decoder {\n /**\n * @param {Uint8Array} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @param {Uint8Array} uint8Array\n * @return {Decoder}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = buffer.createUint8ArrayViewFromArrayBuffer(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let mult = 1\n const len = decoder.arr.length\n while (decoder.pos < len) {\n const r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num\n mult *= 128 // next iteration, shift 7 \"more\" to the left\n if (r < binary.BIT8) {\n return num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let mult = 64\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n const len = decoder.arr.length\n while (decoder.pos < len) {\n r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult\n mult *= 128\n if (r < binary.BIT8) {\n return sign * num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * We don't test this function anymore as we use native decoding/encoding by default now.\n * Better not modify this anymore..\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\n/* c8 ignore start */\nexport const _readVarStringPolyfill = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n/* c8 ignore stop */\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n */\nexport const _readVarStringNative = decoder =>\n /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder))\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n *\n */\n/* c8 ignore next */\nexport const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object\n const len = readVarUint(decoder)\n /**\n * @type {Object}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = math.floor(diff / 2) // shift >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n","/**\n * Utility functions to work with buffers (Uint8Array).\n *\n * @module buffer\n */\n\nimport * as string from './string.js'\nimport * as env from './environment.js'\nimport * as encoding from './encoding.js'\nimport * as decoding from './decoding.js'\n\n/**\n * @param {number} len\n */\nexport const createUint8ArrayFromLen = len => new Uint8Array(len)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n * @param {number} byteOffset\n * @param {number} length\n */\nexport const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n */\nexport const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer)\n\n/* c8 ignore start */\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Browser = bytes => {\n let s = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n s += string.fromCharCode(bytes[i])\n }\n // eslint-disable-next-line no-undef\n return btoa(s)\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')\n\n/* c8 ignore start */\n/**\n * @param {string} s\n * @return {Uint8Array}\n */\nconst fromBase64Browser = s => {\n // eslint-disable-next-line no-undef\n const a = atob(s)\n const bytes = createUint8ArrayFromLen(a.length)\n for (let i = 0; i < a.length; i++) {\n bytes[i] = a.charCodeAt(i)\n }\n return bytes\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} s\n */\nconst fromBase64Node = s => {\n const buf = Buffer.from(s, 'base64')\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n}\n\n/* c8 ignore next */\nexport const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node\n\n/* c8 ignore next */\nexport const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node\n\n/**\n * Copy the content of an Uint8Array view to a new ArrayBuffer.\n *\n * @param {Uint8Array} uint8Array\n * @return {Uint8Array}\n */\nexport const copyUint8Array = uint8Array => {\n const newBuf = createUint8ArrayFromLen(uint8Array.byteLength)\n newBuf.set(uint8Array)\n return newBuf\n}\n\n/**\n * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type.\n * See encoding.writeAny for more information.\n *\n * @param {any} data\n * @return {Uint8Array}\n */\nexport const encodeAny = data => {\n const encoder = encoding.createEncoder()\n encoding.writeAny(encoder, data)\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Decode an any-encoded value.\n *\n * @param {Uint8Array} buf\n * @return {any}\n */\nexport const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf))\n","/* eslint-env browser */\n\n/**\n * Helpers for cross-tab communication using broadcastchannel with LocalStorage fallback.\n *\n * ```js\n * // In browser window A:\n * broadcastchannel.subscribe('my events', data => console.log(data))\n * broadcastchannel.publish('my events', 'Hello world!') // => A: 'Hello world!' fires synchronously in same tab\n *\n * // In browser window B:\n * broadcastchannel.publish('my events', 'hello from tab B') // => A: 'hello from tab B'\n * ```\n *\n * @module broadcastchannel\n */\n\n// @todo before next major: use Uint8Array instead as buffer object\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as buffer from './buffer.js'\nimport * as storage from './storage.js'\n\n/**\n * @typedef {Object} Channel\n * @property {Set} Channel.subs\n * @property {any} Channel.bc\n */\n\n/**\n * @type {Map}\n */\nconst channels = new Map()\n\n/* c8 ignore start */\nclass LocalStoragePolyfill {\n /**\n * @param {string} room\n */\n constructor (room) {\n this.room = room\n /**\n * @type {null|function({data:ArrayBuffer}):void}\n */\n this.onmessage = null\n /**\n * @param {any} e\n */\n this._onChange = e => e.key === room && this.onmessage !== null && this.onmessage({ data: buffer.fromBase64(e.newValue || '') })\n storage.onChange(this._onChange)\n }\n\n /**\n * @param {ArrayBuffer} buf\n */\n postMessage (buf) {\n storage.varStorage.setItem(this.room, buffer.toBase64(buffer.createUint8ArrayFromArrayBuffer(buf)))\n }\n\n close () {\n storage.offChange(this._onChange)\n }\n}\n/* c8 ignore stop */\n\n// Use BroadcastChannel or Polyfill\n/* c8 ignore next */\nconst BC = typeof BroadcastChannel === 'undefined' ? LocalStoragePolyfill : BroadcastChannel\n\n/**\n * @param {string} room\n * @return {Channel}\n */\nconst getChannel = room =>\n map.setIfUndefined(channels, room, () => {\n const subs = set.create()\n const bc = new BC(room)\n /**\n * @param {{data:ArrayBuffer}} e\n */\n /* c8 ignore next */\n bc.onmessage = e => subs.forEach(sub => sub(e.data, 'broadcastchannel'))\n return {\n bc, subs\n }\n })\n\n/**\n * Subscribe to global `publish` events.\n *\n * @function\n * @param {string} room\n * @param {function(any, any):any} f\n */\nexport const subscribe = (room, f) => {\n getChannel(room).subs.add(f)\n return f\n}\n\n/**\n * Unsubscribe from `publish` global events.\n *\n * @function\n * @param {string} room\n * @param {function(any, any):any} f\n */\nexport const unsubscribe = (room, f) => {\n const channel = getChannel(room)\n const unsubscribed = channel.subs.delete(f)\n if (unsubscribed && channel.subs.size === 0) {\n channel.bc.close()\n channels.delete(room)\n }\n return unsubscribed\n}\n\n/**\n * Publish data to all subscribers (including subscribers on this tab)\n *\n * @function\n * @param {string} room\n * @param {any} data\n * @param {any} [origin]\n */\nexport const publish = (room, data, origin = null) => {\n const c = getChannel(room)\n c.bc.postMessage(data)\n c.subs.forEach(sub => sub(data, origin))\n}\n","/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* c8 ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n","/**\n * Observable class prototype.\n *\n * @module observable\n */\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as array from './array.js'\n\n/**\n * Handles named events.\n *\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map}\n */\n this._observers = map.create()\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, name, set.create).add(f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, _f)\n f(...args)\n }\n this.on(name, _f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @param {N} name The event name.\n * @param {Array} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // 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.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n","/**\n * @module awareness-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as time from 'lib0/time'\nimport * as math from 'lib0/math'\nimport { Observable } from 'lib0/observable'\nimport * as f from 'lib0/function'\nimport * as Y from 'yjs' // eslint-disable-line\n\nexport const outdatedTimeout = 30000\n\n/**\n * @typedef {Object} MetaClientState\n * @property {number} MetaClientState.clock\n * @property {number} MetaClientState.lastUpdated unix timestamp\n */\n\n/**\n * The Awareness class implements a simple shared state protocol that can be used for non-persistent data like awareness information\n * (cursor, username, status, ..). Each client can update its own local state and listen to state changes of\n * remote clients. Every client may set a state of a remote peer to `null` to mark the client as offline.\n *\n * Each client is identified by a unique client id (something we borrow from `doc.clientID`). A client can override\n * its own state by propagating a message with an increasing timestamp (`clock`). If such a message is received, it is\n * applied if the known state of that client is older than the new state (`clock < newClock`). If a client thinks that\n * a remote client is offline, it may propagate a message with\n * `{ clock: currentClientClock, state: null, client: remoteClient }`. If such a\n * message is received, and the known clock of that client equals the received clock, it will override the state with `null`.\n *\n * Before a client disconnects, it should propagate a `null` state with an updated clock.\n *\n * Awareness states must be updated every 30 seconds. Otherwise the Awareness instance will delete the client state.\n *\n * @extends {Observable}\n */\nexport class Awareness extends Observable {\n /**\n * @param {Y.Doc} doc\n */\n constructor (doc) {\n super()\n this.doc = doc\n /**\n * @type {number}\n */\n this.clientID = doc.clientID\n /**\n * Maps from client id to client state\n * @type {Map>}\n */\n this.states = new Map()\n /**\n * @type {Map}\n */\n this.meta = new Map()\n this._checkInterval = /** @type {any} */ (setInterval(() => {\n const now = time.getUnixTime()\n if (this.getLocalState() !== null && (outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ (this.meta.get(this.clientID)).lastUpdated)) {\n // renew local clock\n this.setLocalState(this.getLocalState())\n }\n /**\n * @type {Array}\n */\n const remove = []\n this.meta.forEach((meta, clientid) => {\n if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) {\n remove.push(clientid)\n }\n })\n if (remove.length > 0) {\n removeAwarenessStates(this, remove, 'timeout')\n }\n }, math.floor(outdatedTimeout / 10)))\n doc.on('destroy', () => {\n this.destroy()\n })\n this.setLocalState({})\n }\n\n destroy () {\n this.emit('destroy', [this])\n this.setLocalState(null)\n super.destroy()\n clearInterval(this._checkInterval)\n }\n\n /**\n * @return {Object|null}\n */\n getLocalState () {\n return this.states.get(this.clientID) || null\n }\n\n /**\n * @param {Object|null} state\n */\n setLocalState (state) {\n const clientID = this.clientID\n const currLocalMeta = this.meta.get(clientID)\n const clock = currLocalMeta === undefined ? 0 : currLocalMeta.clock + 1\n const prevState = this.states.get(clientID)\n if (state === null) {\n this.states.delete(clientID)\n } else {\n this.states.set(clientID, state)\n }\n this.meta.set(clientID, {\n clock,\n lastUpdated: time.getUnixTime()\n })\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n if (state === null) {\n removed.push(clientID)\n } else if (prevState == null) {\n if (state != null) {\n added.push(clientID)\n }\n } else {\n updated.push(clientID)\n if (!f.equalityDeep(prevState, state)) {\n filteredUpdated.push(clientID)\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n this.emit('change', [{ added, updated: filteredUpdated, removed }, 'local'])\n }\n this.emit('update', [{ added, updated, removed }, 'local'])\n }\n\n /**\n * @param {string} field\n * @param {any} value\n */\n setLocalStateField (field, value) {\n const state = this.getLocalState()\n if (state !== null) {\n this.setLocalState({\n ...state,\n [field]: value\n })\n }\n }\n\n /**\n * @return {Map>}\n */\n getStates () {\n return this.states\n }\n}\n\n/**\n * Mark (remote) clients as inactive and remove them from the list of active peers.\n * This change will be propagated to remote clients.\n *\n * @param {Awareness} awareness\n * @param {Array} clients\n * @param {any} origin\n */\nexport const removeAwarenessStates = (awareness, clients, origin) => {\n const removed = []\n for (let i = 0; i < clients.length; i++) {\n const clientID = clients[i]\n if (awareness.states.has(clientID)) {\n awareness.states.delete(clientID)\n if (clientID === awareness.clientID) {\n const curMeta = /** @type {MetaClientState} */ (awareness.meta.get(clientID))\n awareness.meta.set(clientID, {\n clock: curMeta.clock + 1,\n lastUpdated: time.getUnixTime()\n })\n }\n removed.push(clientID)\n }\n }\n if (removed.length > 0) {\n awareness.emit('change', [{ added: [], updated: [], removed }, origin])\n awareness.emit('update', [{ added: [], updated: [], removed }, origin])\n }\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Array} clients\n * @return {Uint8Array}\n */\nexport const encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {\n const len = clients.length\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = clients[i]\n const state = states.get(clientID) || null\n const clock = /** @type {MetaClientState} */ (awareness.meta.get(clientID)).clock\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(state))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Modify the content of an awareness update before re-encoding it to an awareness update.\n *\n * This might be useful when you have a central server that wants to ensure that clients\n * cant hijack somebody elses identity.\n *\n * @param {Uint8Array} update\n * @param {function(any):any} modify\n * @return {Uint8Array}\n */\nexport const modifyAwarenessUpdate = (update, modify) => {\n const decoder = decoding.createDecoder(update)\n const encoder = encoding.createEncoder()\n const len = decoding.readVarUint(decoder)\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n const clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const modifiedState = modify(state)\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(modifiedState))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Uint8Array} update\n * @param {any} origin This will be added to the emitted change event\n */\nexport const applyAwarenessUpdate = (awareness, update, origin) => {\n const decoder = decoding.createDecoder(update)\n const timestamp = time.getUnixTime()\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n const len = decoding.readVarUint(decoder)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n let clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const clientMeta = awareness.meta.get(clientID)\n const prevState = awareness.states.get(clientID)\n const currClock = clientMeta === undefined ? 0 : clientMeta.clock\n if (currClock < clock || (currClock === clock && state === null && awareness.states.has(clientID))) {\n if (state === null) {\n // never let a remote client remove this local state\n if (clientID === awareness.clientID && awareness.getLocalState() != null) {\n // remote client removed the local state. Do not remote state. Broadcast a message indicating\n // that this client still exists by increasing the clock\n clock++\n } else {\n awareness.states.delete(clientID)\n }\n } else {\n awareness.states.set(clientID, state)\n }\n awareness.meta.set(clientID, {\n clock,\n lastUpdated: timestamp\n })\n if (clientMeta === undefined && state !== null) {\n added.push(clientID)\n } else if (clientMeta !== undefined && state === null) {\n removed.push(clientID)\n } else if (state !== null) {\n if (!f.equalityDeep(state, prevState)) {\n filteredUpdated.push(clientID)\n }\n updated.push(clientID)\n }\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n awareness.emit('change', [{\n added, updated: filteredUpdated, removed\n }, origin])\n }\n if (added.length > 0 || updated.length > 0 || removed.length > 0) {\n awareness.emit('update', [{\n added, updated, removed\n }, origin])\n }\n}\n","/**\n * Mutual exclude for JavaScript.\n *\n * @module mutex\n */\n\n/**\n * @callback mutex\n * @param {function():void} cb Only executed when this mutex is not in the current stack\n * @param {function():void} [elseCb] Executed when this mutex is in the current stack\n */\n\n/**\n * Creates a mutual exclude function with the following property:\n *\n * ```js\n * const mutex = createMutex()\n * mutex(() => {\n * // This function is immediately executed\n * mutex(() => {\n * // This function is not executed, as the mutex is already active.\n * })\n * })\n * ```\n *\n * @return {mutex} A mutual exclude function\n * @public\n */\nexport const createMutex = () => {\n let token = true\n return (f, g) => {\n if (token) {\n token = false\n try {\n f()\n } finally {\n token = true\n }\n } else if (g !== undefined) {\n g()\n }\n }\n}\n","export default class EventEmitter {\n\n public callbacks: { [key: string]: Function[] } = {}\n\n public on(event: string, fn: Function): this {\n if (!this.callbacks[event]) {\n this.callbacks[event] = []\n }\n\n this.callbacks[event].push(fn)\n\n return this\n }\n\n protected emit(event: string, ...args: any): this {\n const callbacks = this.callbacks[event]\n\n if (callbacks) {\n callbacks.forEach(callback => callback.apply(this, args))\n }\n\n return this\n }\n\n public off(event: string, fn?: Function): this {\n const callbacks = this.callbacks[event]\n\n if (callbacks) {\n if (fn) {\n this.callbacks[event] = callbacks.filter(callback => callback !== fn)\n } else {\n delete this.callbacks[event]\n }\n }\n\n return this\n }\n\n removeAllListeners(): void {\n this.callbacks = {}\n }\n}\n","import {\n createDecoder,\n readVarUint,\n readVarUint8Array,\n readVarString,\n Decoder,\n} from 'lib0/decoding'\nimport {\n Encoder,\n createEncoder,\n writeVarUint,\n writeVarUint8Array,\n writeVarString,\n length,\n} from 'lib0/encoding'\nimport { MessageType } from './types.js'\n\nexport class IncomingMessage {\n\n data: any\n\n encoder: Encoder\n\n decoder: Decoder\n\n constructor(data: any) {\n this.data = data\n this.encoder = createEncoder()\n this.decoder = createDecoder(new Uint8Array(this.data))\n }\n\n readVarUint(): MessageType {\n return readVarUint(this.decoder)\n }\n\n readVarString(): string {\n return readVarString(this.decoder)\n }\n\n readVarUint8Array() {\n return readVarUint8Array(this.decoder)\n }\n\n writeVarUint(type: MessageType) {\n return writeVarUint(this.encoder, type)\n }\n\n writeVarString(string: string) {\n return writeVarString(this.encoder, string)\n }\n\n writeVarUint8Array(data: Uint8Array) {\n return writeVarUint8Array(this.encoder, data)\n }\n\n length() {\n return length(this.encoder)\n }\n}\n","/**\n * @module sync-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as Y from 'yjs'\n\n/**\n * @typedef {Map} StateMap\n */\n\n/**\n * Core Yjs defines two message types:\n * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.\n * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it\n * received all information from the remote client.\n *\n * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection\n * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both\n * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.\n *\n * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.\n * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies\n * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the\n * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can\n * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them.\n * Therefore it is necesarry that the client initiates the sync.\n *\n * Construction of a message:\n * [messageType : varUint, message definition..]\n *\n * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!\n *\n * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)\n */\n\nexport const messageYjsSyncStep1 = 0\nexport const messageYjsSyncStep2 = 1\nexport const messageYjsUpdate = 2\n\n/**\n * Create a sync step 1 message based on the state of the current shared document.\n *\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n */\nexport const writeSyncStep1 = (encoder, doc) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep1)\n const sv = Y.encodeStateVector(doc)\n encoding.writeVarUint8Array(encoder, sv)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n * @param {Uint8Array} [encodedStateVector]\n */\nexport const writeSyncStep2 = (encoder, doc, encodedStateVector) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep2)\n encoding.writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector))\n}\n\n/**\n * Read SyncStep1 message and reply with SyncStep2.\n *\n * @param {decoding.Decoder} decoder The reply to the received message\n * @param {encoding.Encoder} encoder The received message\n * @param {Y.Doc} doc\n */\nexport const readSyncStep1 = (decoder, encoder, doc) =>\n writeSyncStep2(encoder, doc, decoding.readVarUint8Array(decoder))\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin) => {\n try {\n Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n } catch (error) {\n // This catches errors that are thrown by event handlers\n console.error('Caught error while handling a Yjs update', error)\n }\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Uint8Array} update\n */\nexport const writeUpdate = (encoder, update) => {\n encoding.writeVarUint(encoder, messageYjsUpdate)\n encoding.writeVarUint8Array(encoder, update)\n}\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readUpdate = readSyncStep2\n\n/**\n * @param {decoding.Decoder} decoder A message received from another client\n * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => {\n const messageType = decoding.readVarUint(decoder)\n switch (messageType) {\n case messageYjsSyncStep1:\n readSyncStep1(decoder, encoder, doc)\n break\n case messageYjsSyncStep2:\n readSyncStep2(decoder, doc, transactionOrigin)\n break\n case messageYjsUpdate:\n readUpdate(decoder, doc, transactionOrigin)\n break\n default:\n throw new Error('Unknown message type')\n }\n return messageType\n}\n","import { Awareness } from 'y-protocols/awareness'\nimport * as Y from 'yjs'\nimport { Encoder } from 'lib0/encoding'\nimport type { Event, CloseEvent, MessageEvent } from 'ws'\nimport { AuthenticationMessage } from './OutgoingMessages/AuthenticationMessage.js'\nimport { AwarenessMessage } from './OutgoingMessages/AwarenessMessage.js'\nimport { QueryAwarenessMessage } from './OutgoingMessages/QueryAwarenessMessage.js'\nimport { SyncStepOneMessage } from './OutgoingMessages/SyncStepOneMessage.js'\nimport { SyncStepTwoMessage } from './OutgoingMessages/SyncStepTwoMessage.js'\nimport { UpdateMessage } from './OutgoingMessages/UpdateMessage.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\n\nexport enum MessageType {\n Sync = 0,\n Awareness = 1,\n Auth = 2,\n QueryAwareness = 3,\n Stateless = 5,\n CLOSE = 7,\n}\n\nexport enum WebSocketStatus {\n Connecting = 'connecting',\n Connected = 'connected',\n Disconnected = 'disconnected',\n}\n\nexport interface OutgoingMessageInterface {\n encoder: Encoder\n type?: MessageType\n}\n\nexport interface OutgoingMessageArguments {\n documentName: string,\n token: string,\n document: Y.Doc,\n awareness: Awareness,\n clients: number[],\n states: Map,\n update: any,\n payload: string,\n encoder: Encoder,\n}\n\nexport interface Constructable {\n new(...args: any) : T\n}\n\nexport type ConstructableOutgoingMessage =\n Constructable |\n Constructable |\n Constructable |\n Constructable |\n Constructable |\n Constructable\n\nexport type onAuthenticationFailedParameters = {\n reason: string,\n}\n\nexport type onOpenParameters = {\n event: Event,\n}\n\nexport type onMessageParameters = {\n event: MessageEvent,\n message: IncomingMessage,\n}\n\nexport type onOutgoingMessageParameters = {\n message: OutgoingMessage,\n}\n\nexport type onStatusParameters = {\n status: WebSocketStatus,\n}\n\nexport type onSyncedParameters = {\n state: boolean,\n}\n\nexport type onDisconnectParameters = {\n event: CloseEvent,\n}\n\nexport type onCloseParameters = {\n event: CloseEvent,\n}\n\nexport type onAwarenessUpdateParameters = {\n states: StatesArray\n}\n\nexport type onAwarenessChangeParameters = {\n states: StatesArray\n}\n\nexport type onStatelessParameters = {\n payload: string\n}\n\nexport type StatesArray = { clientId: number, [key: string | number]: any }[]\n","import { Encoder, createEncoder, toUint8Array } from 'lib0/encoding'\nimport { MessageType, OutgoingMessageArguments, OutgoingMessageInterface } from './types.js'\n\nexport class OutgoingMessage implements OutgoingMessageInterface {\n encoder: Encoder\n\n type?: MessageType\n\n constructor() {\n this.encoder = createEncoder()\n }\n\n get(args: Partial) {\n return args.encoder\n }\n\n toUint8Array() {\n return toUint8Array(this.encoder)\n }\n}\n","import * as awarenessProtocol from 'y-protocols/awareness'\nimport { readSyncMessage, messageYjsSyncStep2, messageYjsUpdate } from 'y-protocols/sync'\nimport { readAuthMessage } from '@hocuspocus/common'\nimport { readVarString } from 'lib0/decoding'\nimport { MessageType } from './types.js'\nimport { HocuspocusProvider } from './HocuspocusProvider.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\n\nexport class MessageReceiver {\n\n message: IncomingMessage\n\n broadcasted = false\n\n constructor(message: IncomingMessage) {\n this.message = message\n }\n\n public setBroadcasted(value: boolean) {\n this.broadcasted = value\n\n return this\n }\n\n public apply(provider: HocuspocusProvider, emitSynced = true) {\n const { message } = this\n const type = message.readVarUint()\n\n const emptyMessageLength = message.length()\n\n switch (type) {\n case MessageType.Sync:\n this.applySyncMessage(provider, emitSynced)\n break\n\n case MessageType.Awareness:\n this.applyAwarenessMessage(provider)\n break\n\n case MessageType.Auth:\n this.applyAuthMessage(provider)\n break\n\n case MessageType.QueryAwareness:\n this.applyQueryAwarenessMessage(provider)\n break\n\n case MessageType.Stateless:\n provider.receiveStateless(readVarString(message.decoder))\n break\n\n default:\n throw new Error(`Can’t apply message of unknown type: ${type}`)\n }\n\n // Reply\n if (message.length() > emptyMessageLength + 1) { // length of documentName (considered in emptyMessageLength plus length of yjs sync type, set in applySyncMessage)\n if (this.broadcasted) {\n // TODO: Some weird TypeScript error\n // @ts-ignore\n provider.broadcast(OutgoingMessage, { encoder: message.encoder })\n } else {\n // TODO: Some weird TypeScript error\n // @ts-ignore\n provider.send(OutgoingMessage, { encoder: message.encoder })\n }\n }\n }\n\n private applySyncMessage(provider: HocuspocusProvider, emitSynced: boolean) {\n const { message } = this\n\n message.writeVarUint(MessageType.Sync)\n\n // Apply update\n const syncMessageType = readSyncMessage(\n message.decoder,\n message.encoder,\n provider.document,\n provider,\n )\n\n // Synced once we receive Step2\n if (emitSynced && syncMessageType === messageYjsSyncStep2) {\n provider.synced = true\n }\n\n if (syncMessageType === messageYjsUpdate || syncMessageType === messageYjsSyncStep2) {\n if (provider.unsyncedChanges > 0) {\n provider.updateUnsyncedChanges(-1)\n }\n }\n }\n\n private applyAwarenessMessage(provider: HocuspocusProvider) {\n const { message } = this\n\n awarenessProtocol.applyAwarenessUpdate(\n provider.awareness,\n message.readVarUint8Array(),\n provider,\n )\n }\n\n private applyAuthMessage(provider: HocuspocusProvider) {\n const { message } = this\n\n readAuthMessage(\n message.decoder,\n provider.permissionDeniedHandler.bind(provider),\n provider.authenticatedHandler.bind(provider),\n )\n }\n\n private applyQueryAwarenessMessage(provider: HocuspocusProvider) {\n const { message } = this\n\n message.writeVarUint(MessageType.Awareness)\n message.writeVarUint8Array(\n awarenessProtocol.encodeAwarenessUpdate(\n provider.awareness,\n Array.from(provider.awareness.getStates().keys()),\n ),\n )\n }\n}\n","import { Encoder, toUint8Array } from 'lib0/encoding'\nimport * as bc from 'lib0/broadcastchannel'\nimport { ConstructableOutgoingMessage } from './types.js'\n\nexport class MessageSender {\n\n encoder: Encoder\n\n message: any\n\n constructor(Message: ConstructableOutgoingMessage, args: any = {}) {\n this.message = new Message()\n this.encoder = this.message.get(args)\n }\n\n create() {\n return toUint8Array(this.encoder)\n }\n\n send(webSocket: any) {\n webSocket?.send(this.create())\n }\n\n broadcast(channel: string) {\n bc.publish(channel, this.create())\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport * as syncProtocol from 'y-protocols/sync'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class SyncStepOneMessage extends OutgoingMessage {\n type = MessageType.Sync\n\n description = 'First sync step'\n\n get(args: Partial) {\n if (typeof args.document === 'undefined') {\n throw new Error('The sync step one message requires document as an argument')\n }\n\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n syncProtocol.writeSyncStep1(this.encoder, args.document)\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport * as syncProtocol from 'y-protocols/sync'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class SyncStepTwoMessage extends OutgoingMessage {\n type = MessageType.Sync\n\n description = 'Second sync step'\n\n get(args: Partial) {\n if (typeof args.document === 'undefined') {\n throw new Error('The sync step two message requires document as an argument')\n }\n\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n syncProtocol.writeSyncStep2(this.encoder, args.document)\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class QueryAwarenessMessage extends OutgoingMessage {\n type = MessageType.QueryAwareness\n\n description = 'Queries awareness states'\n\n get(args: Partial) {\n\n console.log('queryAwareness: writing string docName', args.documentName)\n console.log(this.encoder.cpos)\n\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n\n return this.encoder\n }\n}\n","import { writeVarString, writeVarUint } from 'lib0/encoding'\nimport { writeAuthentication } from '@hocuspocus/common'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class AuthenticationMessage extends OutgoingMessage {\n type = MessageType.Auth\n\n description = 'Authentication'\n\n get(args: Partial) {\n if (typeof args.token === 'undefined') {\n throw new Error('The authentication message requires `token` as an argument.')\n }\n\n writeVarString(this.encoder, args.documentName!)\n writeVarUint(this.encoder, this.type)\n writeAuthentication(this.encoder, args.token)\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport { encodeAwarenessUpdate } from 'y-protocols/awareness'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class AwarenessMessage extends OutgoingMessage {\n type = MessageType.Awareness\n\n description = 'Awareness states update'\n\n get(args: Partial) {\n if (typeof args.awareness === 'undefined') {\n throw new Error('The awareness message requires awareness as an argument')\n }\n\n if (typeof args.clients === 'undefined') {\n throw new Error('The awareness message requires clients as an argument')\n }\n\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n\n let awarenessUpdate\n if (args.states === undefined) {\n awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients)\n } else {\n awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients, args.states)\n }\n\n encoding.writeVarUint8Array(this.encoder, awarenessUpdate)\n\n return this.encoder\n }\n}\n","import { writeVarString, writeVarUint } from 'lib0/encoding'\nimport { writeUpdate } from 'y-protocols/sync'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class UpdateMessage extends OutgoingMessage {\n type = MessageType.Sync\n\n description = 'A document update'\n\n get(args: Partial) {\n writeVarString(this.encoder, args.documentName!)\n writeVarUint(this.encoder, this.type)\n\n writeUpdate(this.encoder, args.update)\n\n return this.encoder\n }\n}\n","/**\n * Utility module to work with urls.\n *\n * @module url\n */\n\nimport * as object from './object.js'\n\n/**\n * Parse query parameters from an url.\n *\n * @param {string} url\n * @return {Object}\n */\nexport const decodeQueryParams = url => {\n /**\n * @type {Object}\n */\n const query = {}\n const urlQuerySplit = url.split('?')\n const pairs = urlQuerySplit[urlQuerySplit.length - 1].split('&')\n for (let i = 0; i < pairs.length; i++) {\n const item = pairs[i]\n if (item.length > 0) {\n const pair = item.split('=')\n query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '')\n }\n }\n return query\n}\n\n/**\n * @param {Object} params\n * @return {string}\n */\nexport const encodeQueryParams = params =>\n object.map(params, (val, key) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&')\n","import * as time from 'lib0/time'\nimport * as mutex from 'lib0/mutex'\nimport * as url from 'lib0/url'\nimport type { MessageEvent } from 'ws'\nimport { retry } from '@lifeomic/attempt'\nimport {\n Forbidden, MessageTooBig, Unauthorized, WsReadyStates,\n} from '@hocuspocus/common'\nimport { Event } from 'ws'\nimport EventEmitter from './EventEmitter.js'\nimport {\n onCloseParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onStatusParameters, WebSocketStatus,\n onAwarenessChangeParameters, onAwarenessUpdateParameters,\n} from './types.js'\nimport { HocuspocusProvider } from './HocuspocusProvider.js'\n\nexport type HocuspocusProviderWebsocketConfiguration =\n Required>\n & Partial\n\nexport interface CompleteHocuspocusProviderWebsocketConfiguration {\n /**\n * URL of your @hocuspocus/server instance\n */\n url: string,\n\n /**\n * Pass `false` to start the connection manually.\n */\n connect: boolean,\n\n /**\n * URL parameters that should be added.\n */\n parameters: { [key: string]: any },\n /**\n * An optional WebSocket polyfill, for example for Node.js\n */\n WebSocketPolyfill: any,\n\n /**\n * Disconnect when no message is received for the defined amount of milliseconds.\n */\n messageReconnectTimeout: number,\n /**\n * The delay between each attempt in milliseconds. You can provide a factor to have the delay grow exponentially.\n */\n delay: number,\n /**\n * The intialDelay is the amount of time to wait before making the first attempt. This option should typically be 0 since you typically want the first attempt to happen immediately.\n */\n initialDelay: number,\n /**\n * The factor option is used to grow the delay exponentially.\n */\n factor: number,\n /**\n * The maximum number of attempts or 0 if there is no limit on number of attempts.\n */\n maxAttempts: number,\n /**\n * minDelay is used to set a lower bound of delay when jitter is enabled. This property has no effect if jitter is disabled.\n */\n minDelay: number,\n /**\n * The maxDelay option is used to set an upper bound for the delay when factor is enabled. A value of 0 can be provided if there should be no upper bound when calculating delay.\n */\n maxDelay: number,\n /**\n * If jitter is true then the calculated delay will be a random integer value between minDelay and the calculated delay for the current iteration.\n */\n jitter: boolean,\n /**\n * A timeout in milliseconds. If timeout is non-zero then a timer is set using setTimeout. If the timeout is triggered then future attempts will be aborted.\n */\n timeout: number,\n onOpen: (data: onOpenParameters) => void,\n onConnect: () => void,\n onMessage: (data: onMessageParameters) => void,\n onOutgoingMessage: (data: onOutgoingMessageParameters) => void,\n onStatus: (data: onStatusParameters) => void,\n onDisconnect: (data: onDisconnectParameters) => void,\n onClose: (data: onCloseParameters) => void,\n onDestroy: () => void,\n onAwarenessUpdate: (data: onAwarenessUpdateParameters) => void,\n onAwarenessChange: (data: onAwarenessChangeParameters) => void,\n /**\n * Don’t output any warnings.\n */\n quiet: boolean,\n}\n\nexport class HocuspocusProviderWebsocket extends EventEmitter {\n public configuration: CompleteHocuspocusProviderWebsocketConfiguration = {\n url: '',\n // @ts-ignore\n document: undefined,\n // @ts-ignore\n awareness: undefined,\n WebSocketPolyfill: undefined,\n parameters: {},\n connect: true,\n broadcast: true,\n forceSyncInterval: false,\n // TODO: this should depend on awareness.outdatedTime\n messageReconnectTimeout: 30000,\n // 1 second\n delay: 1000,\n // instant\n initialDelay: 0,\n // double the delay each time\n factor: 2,\n // unlimited retries\n maxAttempts: 0,\n // wait at least 1 second\n minDelay: 1000,\n // at least every 30 seconds\n maxDelay: 30000,\n // randomize\n jitter: true,\n // retry forever\n timeout: 0,\n onOpen: () => null,\n onConnect: () => null,\n onMessage: () => null,\n onOutgoingMessage: () => null,\n onStatus: () => null,\n onDisconnect: () => null,\n onClose: () => null,\n onDestroy: () => null,\n onAwarenessUpdate: () => null,\n onAwarenessChange: () => null,\n quiet: false,\n }\n\n subscribedToBroadcastChannel = false\n\n webSocket: WebSocket | null = null\n\n shouldConnect = true\n\n status = WebSocketStatus.Disconnected\n\n lastMessageReceived = 0\n\n mux = mutex.createMutex()\n\n intervals: any = {\n forceSync: null,\n connectionChecker: null,\n }\n\n connectionAttempt: {\n resolve: (value?: any) => void\n reject: (reason?: any) => void\n } | null = null\n\n constructor(configuration: HocuspocusProviderWebsocketConfiguration) {\n super()\n this.setConfiguration(configuration)\n\n this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill ? configuration.WebSocketPolyfill : WebSocket\n\n this.on('open', this.configuration.onOpen)\n this.on('open', this.onOpen.bind(this))\n this.on('connect', this.configuration.onConnect)\n this.on('message', this.configuration.onMessage)\n this.on('outgoingMessage', this.configuration.onOutgoingMessage)\n this.on('status', this.configuration.onStatus)\n this.on('status', this.onStatus.bind(this))\n this.on('disconnect', this.configuration.onDisconnect)\n this.on('close', this.configuration.onClose)\n this.on('destroy', this.configuration.onDestroy)\n this.on('awarenessUpdate', this.configuration.onAwarenessUpdate)\n this.on('awarenessChange', this.configuration.onAwarenessChange)\n\n this.on('close', this.onClose.bind(this))\n this.on('message', this.onMessage.bind(this))\n\n this.registerEventListeners()\n\n this.intervals.connectionChecker = setInterval(\n this.checkConnection.bind(this),\n this.configuration.messageReconnectTimeout / 10,\n )\n\n if (typeof configuration.connect !== 'undefined') {\n this.shouldConnect = configuration.connect\n }\n\n if (!this.shouldConnect) {\n return\n }\n\n this.connect()\n }\n\n receivedOnOpenPayload?: Event | undefined = undefined\n\n receivedOnStatusPayload?: onStatusParameters | undefined = undefined\n\n async onOpen(event: Event) {\n this.receivedOnOpenPayload = event\n }\n\n async onStatus(data: onStatusParameters) {\n this.receivedOnStatusPayload = data\n }\n\n attach(provider: HocuspocusProvider) {\n if (this.receivedOnOpenPayload) {\n provider.onOpen(this.receivedOnOpenPayload)\n }\n\n if (this.receivedOnStatusPayload) {\n provider.onStatus(this.receivedOnStatusPayload)\n }\n }\n\n detach(provider: HocuspocusProvider) {\n // tell the server to remove the listener\n\n }\n\n public setConfiguration(configuration: Partial = {}): void {\n this.configuration = { ...this.configuration, ...configuration }\n }\n\n boundConnect = this.connect.bind(this)\n\n cancelWebsocketRetry?: () => void\n\n async connect() {\n if (this.status === WebSocketStatus.Connected) {\n return\n }\n\n // Always cancel any previously initiated connection retryer instances\n if (this.cancelWebsocketRetry) {\n this.cancelWebsocketRetry()\n this.cancelWebsocketRetry = undefined\n }\n\n this.shouldConnect = true\n\n const abortableRetry = () => {\n let cancelAttempt = false\n\n const retryPromise = retry(this.createWebSocketConnection.bind(this), {\n delay: this.configuration.delay,\n initialDelay: this.configuration.initialDelay,\n factor: this.configuration.factor,\n maxAttempts: this.configuration.maxAttempts,\n minDelay: this.configuration.minDelay,\n maxDelay: this.configuration.maxDelay,\n jitter: this.configuration.jitter,\n timeout: this.configuration.timeout,\n beforeAttempt: context => {\n if (!this.shouldConnect || cancelAttempt) {\n context.abort()\n }\n },\n }).catch((error: any) => {\n // If we aborted the connection attempt then don’t throw an error\n // ref: https://github.com/lifeomic/attempt/blob/master/src/index.ts#L136\n if (error && error.code !== 'ATTEMPT_ABORTED') {\n throw error\n }\n })\n\n return {\n retryPromise,\n cancelFunc: () => {\n cancelAttempt = true\n },\n }\n }\n\n const { retryPromise, cancelFunc } = abortableRetry()\n this.cancelWebsocketRetry = cancelFunc\n\n return retryPromise\n }\n\n createWebSocketConnection() {\n return new Promise((resolve, reject) => {\n if (this.webSocket) {\n this.webSocket.close()\n this.webSocket = null\n }\n\n // Init the WebSocket connection\n const ws = new this.configuration.WebSocketPolyfill(this.url)\n ws.binaryType = 'arraybuffer'\n ws.onmessage = (payload: any) => this.emit('message', payload)\n ws.onclose = (payload: any) => this.emit('close', { event: payload })\n ws.onopen = (payload: any) => this.emit('open', payload)\n ws.onerror = (err: any) => {\n reject(err)\n }\n this.webSocket = ws\n\n // Reset the status\n this.status = WebSocketStatus.Connecting\n this.emit('status', { status: WebSocketStatus.Connecting })\n\n // Store resolve/reject for later use\n this.connectionAttempt = {\n resolve,\n reject,\n }\n })\n }\n\n onMessage(event: MessageEvent) {\n this.resolveConnectionAttempt()\n }\n\n resolveConnectionAttempt() {\n if (this.connectionAttempt) {\n this.connectionAttempt.resolve()\n this.connectionAttempt = null\n\n this.status = WebSocketStatus.Connected\n this.emit('status', { status: WebSocketStatus.Connected })\n this.emit('connect')\n }\n }\n\n stopConnectionAttempt() {\n this.connectionAttempt = null\n }\n\n rejectConnectionAttempt() {\n this.connectionAttempt?.reject()\n this.connectionAttempt = null\n }\n\n checkConnection() {\n // Don’t check the connection when it’s not even established\n if (this.status !== WebSocketStatus.Connected) {\n return\n }\n\n // Don’t close then connection while waiting for the first message\n if (!this.lastMessageReceived) {\n return\n }\n\n // Don’t close the connection when a message was received recently\n if (this.configuration.messageReconnectTimeout >= time.getUnixTime() - this.lastMessageReceived) {\n return\n }\n\n // No message received in a long time, not even your own\n // Awareness updates, which are updated every 15 seconds.\n this.webSocket?.close()\n }\n\n registerEventListeners() {\n if (typeof window === 'undefined') {\n return\n }\n\n window.addEventListener('online', this.boundConnect)\n }\n\n // Ensure that the URL always ends with /\n get serverUrl() {\n while (this.configuration.url[this.configuration.url.length - 1] === '/') {\n return this.configuration.url.slice(0, this.configuration.url.length - 1)\n }\n\n return this.configuration.url\n }\n\n get url() {\n const encodedParams = url.encodeQueryParams(this.configuration.parameters)\n\n return `${this.serverUrl}${encodedParams.length === 0 ? '' : `?${encodedParams}`}`\n }\n\n disconnect() {\n this.shouldConnect = false\n\n if (this.webSocket === null) {\n return\n }\n\n try {\n this.webSocket.close()\n } catch {\n //\n }\n }\n\n send(message: any) {\n if (this.webSocket?.readyState === WsReadyStates.Open) {\n this.webSocket.send(message)\n }\n }\n\n onClose({ event }: onCloseParameters) {\n this.webSocket = null\n\n if (this.status === WebSocketStatus.Connected) {\n this.status = WebSocketStatus.Disconnected\n this.emit('status', { status: WebSocketStatus.Disconnected })\n this.emit('disconnect', { event })\n }\n\n if (event.code === Unauthorized.code) {\n if (event.reason === Unauthorized.reason) {\n console.warn('[HocuspocusProvider] An authentication token is required, but you didn’t send one. Try adding a `token` to your HocuspocusProvider configuration. Won’t try again.')\n } else {\n console.warn(`[HocuspocusProvider] Connection closed with status Unauthorized: ${event.reason}`)\n }\n\n this.shouldConnect = false\n }\n\n if (event.code === Forbidden.code) {\n if (!this.configuration.quiet) {\n console.warn('[HocuspocusProvider] The provided authentication token isn’t allowed to connect to this server. Will try again.')\n return // TODO REMOVE ME\n }\n }\n\n if (event.code === MessageTooBig.code) {\n console.warn(`[HocuspocusProvider] Connection closed with status MessageTooBig: ${event.reason}`)\n this.shouldConnect = false\n }\n\n if (this.connectionAttempt) {\n // That connection attempt failed.\n this.rejectConnectionAttempt()\n } else if (this.shouldConnect) {\n // The connection was closed by the server. Let’s just try again.\n this.connect()\n }\n\n // If we’ll reconnect, we’re done for now.\n if (this.shouldConnect) {\n return\n }\n\n // The status is set correctly already.\n if (this.status === WebSocketStatus.Disconnected) {\n return\n }\n\n // Let’s update the connection status.\n this.status = WebSocketStatus.Disconnected\n this.emit('status', { status: WebSocketStatus.Disconnected })\n this.emit('disconnect', { event })\n }\n\n destroy() {\n this.emit('destroy')\n\n if (this.intervals.forceSync) {\n clearInterval(this.intervals.forceSync)\n }\n\n clearInterval(this.intervals.connectionChecker)\n\n // If there is still a connection attempt outstanding then we should stop\n // it before calling disconnect, otherwise it will be rejected in the onClose\n // handler and trigger a retry\n this.stopConnectionAttempt()\n\n this.disconnect()\n\n this.removeAllListeners()\n\n if (typeof window === 'undefined') {\n return\n }\n\n window.removeEventListener('online', this.boundConnect)\n }\n\n}\n","import { writeVarString, writeVarUint } from 'lib0/encoding'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class StatelessMessage extends OutgoingMessage {\n type = MessageType.Stateless\n\n description = 'A stateless message'\n\n get(args: Partial) {\n writeVarString(this.encoder, args.documentName!)\n writeVarUint(this.encoder, this.type)\n writeVarString(this.encoder, args.payload ?? '')\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class CloseMessage extends OutgoingMessage {\n type = MessageType.CLOSE\n\n description = 'Ask the server to close the connection'\n\n get(args: Partial) {\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n\n return this.encoder\n }\n}\n","import * as Y from 'yjs'\nimport * as bc from 'lib0/broadcastchannel'\nimport { Awareness, removeAwarenessStates } from 'y-protocols/awareness'\nimport * as mutex from 'lib0/mutex'\nimport type { CloseEvent, Event, MessageEvent } from 'ws'\nimport { awarenessStatesToArray } from '@hocuspocus/common'\nimport EventEmitter from './EventEmitter.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { MessageReceiver } from './MessageReceiver.js'\nimport { MessageSender } from './MessageSender.js'\nimport { SyncStepOneMessage } from './OutgoingMessages/SyncStepOneMessage.js'\nimport { SyncStepTwoMessage } from './OutgoingMessages/SyncStepTwoMessage.js'\nimport { QueryAwarenessMessage } from './OutgoingMessages/QueryAwarenessMessage.js'\nimport { AuthenticationMessage } from './OutgoingMessages/AuthenticationMessage.js'\nimport { AwarenessMessage } from './OutgoingMessages/AwarenessMessage.js'\nimport { UpdateMessage } from './OutgoingMessages/UpdateMessage.js'\nimport {\n ConstructableOutgoingMessage,\n onAuthenticationFailedParameters,\n onCloseParameters,\n onDisconnectParameters,\n onMessageParameters,\n onOpenParameters,\n onOutgoingMessageParameters, onStatelessParameters,\n onStatusParameters,\n onSyncedParameters,\n WebSocketStatus,\n onAwarenessChangeParameters,\n onAwarenessUpdateParameters,\n} from './types.js'\nimport {\n CompleteHocuspocusProviderWebsocketConfiguration,\n HocuspocusProviderWebsocket,\n} from './HocuspocusProviderWebsocket.js'\nimport { StatelessMessage } from './OutgoingMessages/StatelessMessage.js'\nimport { CloseMessage } from './OutgoingMessages/CloseMessage.js'\n\nexport type HocuspocusProviderConfiguration =\n Required>\n & Partial & (\n Required> |\n Required>\n )\n\nexport interface CompleteHocuspocusProviderConfiguration {\n /**\n * The identifier/name of your document\n */\n name: string,\n /**\n * The actual Y.js document\n */\n document: Y.Doc,\n\n /**\n * Pass false to disable broadcasting between browser tabs.\n */\n broadcast: boolean,\n /**\n * An Awareness instance to keep the presence state of all clients.\n */\n awareness: Awareness,\n /**\n * A token that’s sent to the backend for authentication purposes.\n */\n token: string | (() => string) | (() => Promise) | null,\n /**\n * URL parameters that should be added.\n */\n parameters: { [key: string]: any },\n /**\n * Hocuspocus websocket provider\n */\n websocketProvider: HocuspocusProviderWebsocket,\n /**\n * Force syncing the document in the defined interval.\n */\n forceSyncInterval: false | number,\n\n onAuthenticated: () => void,\n onAuthenticationFailed: (data: onAuthenticationFailedParameters) => void,\n onOpen: (data: onOpenParameters) => void,\n onConnect: () => void,\n onMessage: (data: onMessageParameters) => void,\n onOutgoingMessage: (data: onOutgoingMessageParameters) => void,\n onStatus: (data: onStatusParameters) => void,\n onSynced: (data: onSyncedParameters) => void,\n onDisconnect: (data: onDisconnectParameters) => void,\n onClose: (data: onCloseParameters) => void,\n onDestroy: () => void,\n onAwarenessUpdate: (data: onAwarenessUpdateParameters) => void,\n onAwarenessChange: (data: onAwarenessChangeParameters) => void,\n onStateless: (data: onStatelessParameters) => void\n\n /**\n * Don’t output any warnings.\n */\n quiet: boolean,\n}\n\nexport class HocuspocusProvider extends EventEmitter {\n public configuration: CompleteHocuspocusProviderConfiguration = {\n name: '',\n // @ts-ignore\n document: undefined,\n // @ts-ignore\n awareness: undefined,\n token: null,\n parameters: {},\n broadcast: true,\n forceSyncInterval: false,\n onAuthenticated: () => null,\n onAuthenticationFailed: () => null,\n onOpen: () => null,\n onConnect: () => null,\n onMessage: () => null,\n onOutgoingMessage: () => null,\n onStatus: () => null,\n onSynced: () => null,\n onDisconnect: () => null,\n onClose: () => null,\n onDestroy: () => null,\n onAwarenessUpdate: () => null,\n onAwarenessChange: () => null,\n onStateless: () => null,\n quiet: false,\n }\n\n subscribedToBroadcastChannel = false\n\n isSynced = false\n\n unsyncedChanges = 0\n\n status = WebSocketStatus.Disconnected\n\n isAuthenticated = false\n\n authorizedScope: string | undefined = undefined\n\n mux = mutex.createMutex()\n\n intervals: any = {\n forceSync: null,\n }\n\n isConnected = true\n\n constructor(configuration: HocuspocusProviderConfiguration) {\n super()\n this.setConfiguration(configuration)\n\n this.configuration.document = configuration.document ? configuration.document : new Y.Doc()\n this.configuration.awareness = configuration.awareness ? configuration.awareness : new Awareness(this.document)\n\n this.on('open', this.configuration.onOpen)\n this.on('message', this.configuration.onMessage)\n this.on('outgoingMessage', this.configuration.onOutgoingMessage)\n this.on('synced', this.configuration.onSynced)\n this.on('destroy', this.configuration.onDestroy)\n this.on('awarenessUpdate', this.configuration.onAwarenessUpdate)\n this.on('awarenessChange', this.configuration.onAwarenessChange)\n this.on('stateless', this.configuration.onStateless)\n\n this.on('authenticated', this.configuration.onAuthenticated)\n this.on('authenticationFailed', this.configuration.onAuthenticationFailed)\n\n this.configuration.websocketProvider.on('connect', this.configuration.onConnect)\n this.configuration.websocketProvider.on('connect', (e: Event) => this.emit('connect', e))\n\n this.configuration.websocketProvider.on('open', this.onOpen.bind(this))\n this.configuration.websocketProvider.on('open', (e: Event) => this.emit('open', e))\n\n this.configuration.websocketProvider.on('message', this.onMessage.bind(this))\n\n this.configuration.websocketProvider.on('close', this.onClose.bind(this))\n this.configuration.websocketProvider.on('close', this.configuration.onClose)\n this.configuration.websocketProvider.on('close', (e: Event) => this.emit('close', e))\n\n this.configuration.websocketProvider.on('status', this.onStatus.bind(this))\n\n this.configuration.websocketProvider.on('disconnect', this.configuration.onDisconnect)\n this.configuration.websocketProvider.on('disconnect', (e: Event) => this.emit('disconnect', e))\n\n this.configuration.websocketProvider.on('destroy', this.configuration.onDestroy)\n this.configuration.websocketProvider.on('destroy', (e: Event) => this.emit('destroy', e))\n\n this.awareness.on('update', () => {\n this.emit('awarenessUpdate', { states: awarenessStatesToArray(this.awareness.getStates()) })\n })\n\n this.awareness.on('change', () => {\n this.emit('awarenessChange', { states: awarenessStatesToArray(this.awareness.getStates()) })\n })\n\n this.document.on('update', this.documentUpdateHandler.bind(this))\n this.awareness.on('update', this.awarenessUpdateHandler.bind(this))\n this.registerEventListeners()\n\n if (this.configuration.forceSyncInterval) {\n this.intervals.forceSync = setInterval(\n this.forceSync.bind(this),\n this.configuration.forceSyncInterval,\n )\n }\n\n this.configuration.websocketProvider.attach(this)\n }\n\n public onStatus({ status } : onStatusParameters) {\n this.status = status\n\n this.configuration.onStatus({ status })\n this.emit('status', { status })\n }\n\n public setConfiguration(configuration: Partial = {}): void {\n if (!configuration.websocketProvider && (configuration as CompleteHocuspocusProviderWebsocketConfiguration).url) {\n const websocketProviderConfig = configuration as CompleteHocuspocusProviderWebsocketConfiguration\n\n this.configuration.websocketProvider = new HocuspocusProviderWebsocket({\n url: websocketProviderConfig.url,\n parameters: websocketProviderConfig.parameters,\n })\n }\n\n this.configuration = { ...this.configuration, ...configuration }\n }\n\n get document() {\n return this.configuration.document\n }\n\n get awareness() {\n return this.configuration.awareness\n }\n\n get hasUnsyncedChanges(): boolean {\n return this.unsyncedChanges > 0\n }\n\n updateUnsyncedChanges(unsyncedChanges = 0) {\n this.unsyncedChanges += unsyncedChanges\n this.emit('unsyncedChanges', this.unsyncedChanges)\n }\n\n forceSync() {\n this.send(SyncStepOneMessage, { document: this.document, documentName: this.configuration.name })\n }\n\n boundBeforeUnload = this.beforeUnload.bind(this)\n\n beforeUnload() {\n removeAwarenessStates(this.awareness, [this.document.clientID], 'window unload')\n }\n\n registerEventListeners() {\n if (typeof window === 'undefined') {\n return\n }\n\n window.addEventListener('beforeunload', this.boundBeforeUnload)\n }\n\n sendStateless(payload: string) {\n this.send(StatelessMessage, { documentName: this.configuration.name, payload })\n }\n\n documentUpdateHandler(update: Uint8Array, origin: any) {\n if (origin === this) {\n return\n }\n\n this.updateUnsyncedChanges(1)\n this.send(UpdateMessage, { update, documentName: this.configuration.name }, true)\n }\n\n awarenessUpdateHandler({ added, updated, removed }: any, origin: any) {\n const changedClients = added.concat(updated).concat(removed)\n\n this.send(AwarenessMessage, {\n awareness: this.awareness,\n clients: changedClients,\n documentName: this.configuration.name,\n }, true)\n }\n\n get synced(): boolean {\n return this.isSynced\n }\n\n set synced(state) {\n if (this.isSynced === state) {\n return\n }\n\n if (state && this.unsyncedChanges > 0) {\n this.updateUnsyncedChanges(-1 * this.unsyncedChanges)\n }\n\n this.isSynced = state\n this.emit('synced', { state })\n this.emit('sync', { state })\n }\n\n receiveStateless(payload: string) {\n this.emit('stateless', { payload })\n }\n\n get isAuthenticationRequired(): boolean {\n return !!this.configuration.token && !this.isAuthenticated\n }\n\n // not needed, but provides backward compatibility with e.g. lexicla/yjs\n async connect() {\n return this.configuration.websocketProvider.connect()\n }\n\n disconnect() {\n this.disconnectBroadcastChannel()\n this.configuration.websocketProvider.detach(this)\n }\n\n async onOpen(event: Event) {\n this.isAuthenticated = false\n\n this.emit('open', { event })\n\n if (this.isAuthenticationRequired) {\n this.send(AuthenticationMessage, {\n token: await this.getToken(),\n documentName: this.configuration.name,\n })\n }\n\n this.startSync()\n }\n\n async getToken() {\n if (typeof this.configuration.token === 'function') {\n const token = await this.configuration.token()\n return token\n }\n\n return this.configuration.token\n }\n\n startSync() {\n this.send(SyncStepOneMessage, { document: this.document, documentName: this.configuration.name })\n\n if (this.awareness.getLocalState() !== null) {\n this.send(AwarenessMessage, {\n awareness: this.awareness,\n clients: [this.document.clientID],\n documentName: this.configuration.name,\n })\n }\n }\n\n send(message: ConstructableOutgoingMessage, args: any, broadcast = false) {\n if (!this.isConnected) return\n\n if (broadcast) {\n this.mux(() => { this.broadcast(message, args) })\n }\n\n const messageSender = new MessageSender(message, args)\n\n this.emit('outgoingMessage', { message: messageSender.message })\n messageSender.send(this.configuration.websocketProvider)\n }\n\n onMessage(event: MessageEvent) {\n const message = new IncomingMessage(event.data)\n\n const documentName = message.readVarString()\n\n if (documentName !== this.configuration.name) {\n return // message is meant for another provider\n }\n\n message.writeVarString(documentName)\n\n this.emit('message', { event, message: new IncomingMessage(event.data) })\n\n new MessageReceiver(message).apply(this)\n }\n\n onClose(event: CloseEvent) {\n this.isAuthenticated = false\n this.synced = false\n\n // update awareness (all users except local left)\n removeAwarenessStates(\n this.awareness,\n Array.from(this.awareness.getStates().keys()).filter(client => client !== this.document.clientID),\n this,\n )\n }\n\n destroy() {\n this.emit('destroy')\n\n if (this.intervals.forceSync) {\n clearInterval(this.intervals.forceSync)\n }\n\n removeAwarenessStates(this.awareness, [this.document.clientID], 'provider destroy')\n\n this.disconnect()\n\n this.awareness.off('update', this.awarenessUpdateHandler)\n this.document.off('update', this.documentUpdateHandler)\n\n this.removeAllListeners()\n\n this.send(CloseMessage, { documentName: this.configuration.name })\n this.isConnected = false\n\n if (typeof window === 'undefined') {\n return\n }\n\n window.removeEventListener('beforeunload', this.boundBeforeUnload)\n }\n\n permissionDeniedHandler(reason: string) {\n this.emit('authenticationFailed', { reason })\n this.isAuthenticated = false\n this.disconnect()\n this.status = WebSocketStatus.Disconnected\n }\n\n authenticatedHandler(scope: string) {\n this.isAuthenticated = true\n this.authorizedScope = scope\n\n this.emit('authenticated')\n this.startSync()\n }\n\n get broadcastChannel() {\n return `${this.configuration.name}`\n }\n\n boundBroadcastChannelSubscriber = this.broadcastChannelSubscriber.bind(this)\n\n broadcastChannelSubscriber(data: ArrayBuffer) {\n this.mux(() => {\n const message = new IncomingMessage(data)\n\n const documentName = message.readVarString()\n\n message.writeVarString(documentName)\n\n new MessageReceiver(message)\n .setBroadcasted(true)\n .apply(this, false)\n })\n }\n\n subscribeToBroadcastChannel() {\n if (!this.subscribedToBroadcastChannel) {\n bc.subscribe(this.broadcastChannel, this.boundBroadcastChannelSubscriber)\n this.subscribedToBroadcastChannel = true\n }\n\n this.mux(() => {\n this.broadcast(SyncStepOneMessage, { document: this.document })\n this.broadcast(SyncStepTwoMessage, { document: this.document })\n this.broadcast(QueryAwarenessMessage, { document: this.document })\n this.broadcast(AwarenessMessage, { awareness: this.awareness, clients: [this.document.clientID], document: this.document })\n })\n }\n\n disconnectBroadcastChannel() {\n // broadcast message with local awareness state set to null (indicating disconnect)\n this.send(AwarenessMessage, {\n awareness: this.awareness,\n clients: [this.document.clientID],\n states: new Map(),\n documentName: this.configuration.name,\n }, true)\n\n if (this.subscribedToBroadcastChannel) {\n bc.unsubscribe(this.broadcastChannel, this.boundBroadcastChannelSubscriber)\n this.subscribedToBroadcastChannel = false\n }\n }\n\n broadcast(Message: ConstructableOutgoingMessage, args?: any) {\n if (!this.configuration.broadcast) {\n return\n }\n\n if (!this.subscribedToBroadcastChannel) {\n return\n }\n\n new MessageSender(Message, args).broadcast(this.broadcastChannel)\n }\n\n setAwarenessField(key: string, value: any) {\n this.awareness.setLocalStateField(key, value)\n }\n}\n","import {\n CompleteHocuspocusProviderWebsocketConfiguration,\n HocuspocusProviderWebsocket, HocuspocusProviderWebsocketConfiguration,\n} from './HocuspocusProviderWebsocket.js'\n\nexport type TiptapCollabProviderWebsocketConfiguration =\n Partial &\n AdditionalTiptapCollabProviderWebsocketConfiguration\n\nexport interface AdditionalTiptapCollabProviderWebsocketConfiguration {\n /**\n * A Hocuspocus Cloud App ID, get one here: https://collab.tiptap.dev\n */\n appId: string,\n}\n\nexport class TiptapCollabProviderWebsocket extends HocuspocusProviderWebsocket {\n constructor(configuration: TiptapCollabProviderWebsocketConfiguration) {\n super({ ...configuration as HocuspocusProviderWebsocketConfiguration, url: `wss://${configuration.appId}.collab.tiptap.cloud` })\n }\n}\n","import {\n HocuspocusProvider,\n HocuspocusProviderConfiguration,\n} from './HocuspocusProvider.js'\n\nimport { TiptapCollabProviderWebsocket } from './TiptapCollabProviderWebsocket.js'\n\nexport type TiptapCollabProviderConfiguration =\n Required> &\n Partial &\n AdditionalTiptapCollabProviderConfiguration\n\nexport interface AdditionalTiptapCollabProviderConfiguration {\n /**\n * A Hocuspocus Cloud App ID, get one here: https://collab.tiptap.dev\n */\n appId: string,\n}\n\nexport class TiptapCollabProvider extends HocuspocusProvider {\n constructor(configuration: TiptapCollabProviderConfiguration) {\n if (!configuration.websocketProvider) {\n configuration.websocketProvider = new TiptapCollabProviderWebsocket({ appId: configuration.appId })\n }\n\n if (!configuration.token) {\n configuration.token = 'notoken' // need to send a token anyway (which will be ignored)\n }\n\n super(configuration as HocuspocusProviderConfiguration)\n }\n}\n"],"names":["create","length","object.length","object.hasProperty","map.create","string.fromCamelCase","conditions.undefinedToNull","storage.varStorage","f.isOneOf","buffer.createUint8ArrayViewFromArrayBuffer","binary.BITS7","binary.BIT8","math.floor","string.utf8TextEncoder","string.encodeUtf8","math.min","math.max","error.create","number.MAX_SAFE_INTEGER","string.utf8TextDecoder","string.fromCharCode","env.isBrowser","buffer.fromBase64","storage.onChange","buffer.toBase64","buffer.createUint8ArrayFromArrayBuffer","storage.offChange","map.setIfUndefined","set.create","array.from","time.getUnixTime","f.equalityDeep","encoding.createEncoder","encoding.writeVarUint","encoding.writeVarString","encoding.toUint8Array","decoding.createDecoder","decoding.readVarUint","decoding.readVarString","Y","encoding.writeVarUint8Array","decoding.readVarUint8Array","MessageType","WebSocketStatus","awarenessProtocol.applyAwarenessUpdate","readAuthMessage","awarenessProtocol.encodeAwarenessUpdate","bc.publish","syncProtocol.writeSyncStep1","syncProtocol.writeSyncStep2","writeAuthentication","object.map","mutex.createMutex","retry","url.encodeQueryParams","WsReadyStates","Unauthorized","Forbidden","MessageTooBig","awarenessStatesToArray","bc.subscribe","bc.unsubscribe"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMA,QAAM,GAAG,MAAM,IAAI,GAAG,GAAE;AAerC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,cAAc,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,KAAK;AACrD,EAAE,IAAI,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,EAAC;AACxB,EAAE,IAAI,GAAG,KAAK,SAAS,EAAE;AACzB,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,GAAG,OAAO,EAAE,EAAC;AACjC,GAAG;AACH,EAAE,OAAO,GAAG;AACZ;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMA,QAAM,GAAG,MAAM,IAAI,GAAG;;ACNnC;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,YAAY,GAAG,MAAM,CAAC,aAAY;AAE/C;AACA;AACA;AACA;AACA;AACA,MAAM,WAAW,GAAG,CAAC,IAAI,CAAC,CAAC,WAAW,GAAE;AACxC;AACA,MAAM,aAAa,GAAG,QAAO;AAC7B;AACA;AACA;AACA;AACA;AACO,MAAM,QAAQ,GAAG,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,aAAa,EAAE,EAAE,EAAC;AACzD;AACA,MAAM,kBAAkB,GAAG,WAAU;AACrC;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,aAAa,GAAG,CAAC,CAAC,EAAE,SAAS,KAAK,Q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AAE,CAAS,MAAA,EAAA,aAAa,CAAC,KAAK,CAAsB,oBAAA,CAAA,EAAE,CAAC,CAAA;KACjI;AACF;;ACDK,MAAO,oBAAqB,SAAQ,kBAAkB,CAAA;AAC1D,IAAA,WAAA,CAAY,aAAgD,EAAA;AAC1D,QAAA,IAAI,CAAC,aAAa,CAAC,iBAAiB,EAAE;AACpC,YAAA,aAAa,CAAC,iBAAiB,GAAG,IAAI,6BAA6B,CAAC,EAAE,KAAK,EAAE,aAAa,CAAC,KAAK,EAAE,CAAC,CAAA;AACpG,SAAA;AAED,QAAA,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE;AACxB,YAAA,aAAa,CAAC,KAAK,GAAG,SAAS,CAAA;AAChC,SAAA;QAED,KAAK,CAAC,aAAgD,CAAC,CAAA;KACxD;AACF;;;;;;;"} -\ No newline at end of file -+{"version":3,"file":"hocuspocus-provider.cjs","sources":["../../../node_modules/lib0/map.js","../../../node_modules/lib0/set.js","../../../node_modules/lib0/array.js","../../../node_modules/lib0/string.js","../../../node_modules/lib0/conditions.js","../../../node_modules/lib0/storage.js","../../../node_modules/lib0/object.js","../../../node_modules/lib0/function.js","../../../node_modules/lib0/environment.js","../../../node_modules/lib0/math.js","../../../node_modules/lib0/binary.js","../../../node_modules/lib0/number.js","../../../node_modules/lib0/encoding.js","../../../node_modules/lib0/error.js","../../../node_modules/lib0/decoding.js","../../../node_modules/lib0/buffer.js","../../../node_modules/lib0/broadcastchannel.js","../../../node_modules/lib0/mutex.js","../../../node_modules/lib0/time.js","../../../node_modules/lib0/observable.js","../../../node_modules/y-protocols/awareness.js","../src/EventEmitter.ts","../../../node_modules/lib0/url.js","../src/types.ts","../src/HocuspocusProviderWebsocket.ts","../src/IncomingMessage.ts","../../../node_modules/y-protocols/sync.js","../src/OutgoingMessage.ts","../src/MessageReceiver.ts","../src/MessageSender.ts","../src/OutgoingMessages/AuthenticationMessage.ts","../src/OutgoingMessages/AwarenessMessage.ts","../src/OutgoingMessages/CloseMessage.ts","../src/OutgoingMessages/QueryAwarenessMessage.ts","../src/OutgoingMessages/StatelessMessage.ts","../src/OutgoingMessages/SyncStepOneMessage.ts","../src/OutgoingMessages/SyncStepTwoMessage.ts","../src/OutgoingMessages/UpdateMessage.ts","../src/HocuspocusProvider.ts","../src/TiptapCollabProviderWebsocket.ts","../src/TiptapCollabProvider.ts"],"sourcesContent":["/**\n * Utility module to work with key-value stores.\n *\n * @module map\n */\n\n/**\n * Creates a new Map instance.\n *\n * @function\n * @return {Map}\n *\n * @function\n */\nexport const create = () => new Map()\n\n/**\n * Copy a Map object into a fresh Map object.\n *\n * @function\n * @template X,Y\n * @param {Map} m\n * @return {Map}\n */\nexport const copy = m => {\n const r = create()\n m.forEach((v, k) => { r.set(k, v) })\n return r\n}\n\n/**\n * Get map property. Create T if property is undefined and set T on map.\n *\n * ```js\n * const listeners = map.setIfUndefined(events, 'eventName', set.create)\n * listeners.add(listener)\n * ```\n *\n * @function\n * @template V,K\n * @template {Map} MAP\n * @param {MAP} map\n * @param {K} key\n * @param {function():V} createT\n * @return {V}\n */\nexport const setIfUndefined = (map, key, createT) => {\n let set = map.get(key)\n if (set === undefined) {\n map.set(key, set = createT())\n }\n return set\n}\n\n/**\n * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function.\n *\n * @function\n * @template K\n * @template V\n * @template R\n * @param {Map} m\n * @param {function(V,K):R} f\n * @return {Array}\n */\nexport const map = (m, f) => {\n const res = []\n for (const [key, value] of m) {\n res.push(f(value, key))\n }\n return res\n}\n\n/**\n * Tests whether any key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @todo should rename to some - similarly to Array.some\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const any = (m, f) => {\n for (const [key, value] of m) {\n if (f(value, key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * Tests whether all key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const all = (m, f) => {\n for (const [key, value] of m) {\n if (!f(value, key)) {\n return false\n }\n }\n return true\n}\n","/**\n * Utility module to work with sets.\n *\n * @module set\n */\n\nexport const create = () => new Set()\n\n/**\n * @template T\n * @param {Set} set\n * @return {Array}\n */\nexport const toArray = set => Array.from(set)\n\n/**\n * @template T\n * @param {Set} set\n * @return {T}\n */\nexport const first = set =>\n set.values().next().value || undefined\n\n/**\n * @template T\n * @param {Iterable} entries\n * @return {Set}\n */\nexport const from = entries => new Set(entries)\n","/**\n * Utility module to work with Arrays.\n *\n * @module array\n */\n\nimport * as set from './set.js'\n\n/**\n * Return the last element of an array. The element must exist\n *\n * @template L\n * @param {ArrayLike} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array}\n */\nexport const create = () => /** @type {Array} */ ([])\n\n/**\n * @template D\n * @param {Array} a\n * @return {Array}\n */\nexport const copy = a => /** @type {Array} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array} dest\n * @param {Array} src\n */\nexport const appendTo = (dest, src) => {\n for (let i = 0; i < src.length; i++) {\n dest.push(src[i])\n }\n}\n\n/**\n * Transforms something array-like to an actual Array.\n *\n * @function\n * @template T\n * @param {ArrayLike|Iterable} arraylike\n * @return {T}\n */\nexport const from = Array.from\n\n/**\n * True iff condition holds on every element in the Array.\n *\n * @function\n * @template ITEM\n * @template {ArrayLike} ARR\n *\n * @param {ARR} arr\n * @param {function(ITEM, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const every = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (!f(arr[i], i, arr)) {\n return false\n }\n }\n return true\n}\n\n/**\n * True iff condition holds on some element in the Array.\n *\n * @function\n * @template S\n * @template {ArrayLike} ARR\n * @param {ARR} arr\n * @param {function(S, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const some = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (f(arr[i], i, arr)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @template ELEM\n *\n * @param {ArrayLike} a\n * @param {ArrayLike} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a.length === b.length && every(a, (item, index) => item === b[index])\n\n/**\n * @template ELEM\n * @param {Array>} arr\n * @return {Array}\n */\nexport const flatten = arr => fold(arr, /** @type {Array} */ ([]), (acc, val) => acc.concat(val))\n\n/**\n * @template T\n * @param {number} len\n * @param {function(number, Array):T} f\n * @return {Array}\n */\nexport const unfold = (len, f) => {\n const array = new Array(len)\n for (let i = 0; i < len; i++) {\n array[i] = f(i, array)\n }\n return array\n}\n\n/**\n * @template T\n * @template RESULT\n * @param {Array} arr\n * @param {RESULT} seed\n * @param {function(RESULT, T, number):RESULT} folder\n */\nexport const fold = (arr, seed, folder) => arr.reduce(folder, seed)\n\nexport const isArray = Array.isArray\n\n/**\n * @template T\n * @param {Array} arr\n * @return {Array}\n */\nexport const unique = arr => from(set.from(arr))\n\n/**\n * @template T\n * @template M\n * @param {ArrayLike} arr\n * @param {function(T):M} mapper\n * @return {Array}\n */\nexport const uniqueBy = (arr, mapper) => {\n /**\n * @type {Set}\n */\n const happened = set.create()\n /**\n * @type {Array}\n */\n const result = []\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i]\n const mapped = mapper(el)\n if (!happened.has(mapped)) {\n happened.add(mapped)\n result.push(el)\n }\n }\n return result\n}\n","import * as array from './array.js'\n\n/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * The largest utf16 character.\n * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8)\n */\nexport const MAX_UTF16_CHARACTER = fromCharCode(65535)\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* c8 ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* c8 ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* c8 ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* c8 ignore start */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* c8 ignore next */\n utf8TextDecoder = null\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* c8 ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n\n/**\n * @param {string} source\n * @param {number} n\n */\nexport const repeat = (source, n) => array.unfold(n, () => source).join('')\n","/**\n * Often used conditions.\n *\n * @module conditions\n */\n\n/**\n * @template T\n * @param {T|null|undefined} v\n * @return {T|null}\n */\n/* c8 ignore next */\nexport const undefinedToNull = v => v === undefined ? null : v\n","/* eslint-env browser */\n\n/**\n * Isomorphic variable storage.\n *\n * Uses LocalStorage in the browser and falls back to in-memory storage.\n *\n * @module storage\n */\n\n/* c8 ignore start */\nclass VarStoragePolyfill {\n constructor () {\n this.map = new Map()\n }\n\n /**\n * @param {string} key\n * @param {any} newValue\n */\n setItem (key, newValue) {\n this.map.set(key, newValue)\n }\n\n /**\n * @param {string} key\n */\n getItem (key) {\n return this.map.get(key)\n }\n}\n/* c8 ignore stop */\n\n/**\n * @type {any}\n */\nlet _localStorage = new VarStoragePolyfill()\nlet usePolyfill = true\n\n/* c8 ignore start */\ntry {\n // if the same-origin rule is violated, accessing localStorage might thrown an error\n if (typeof localStorage !== 'undefined') {\n _localStorage = localStorage\n usePolyfill = false\n }\n} catch (e) { }\n/* c8 ignore stop */\n\n/**\n * This is basically localStorage in browser, or a polyfill in nodejs\n */\n/* c8 ignore next */\nexport const varStorage = _localStorage\n\n/**\n * A polyfill for `addEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler))\n\n/**\n * A polyfill for `removeEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler))\n","/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object} obj\n */\nexport const keys = Object.keys\n\n/**\n * @template V\n * @param {{[k:string]:V}} obj\n * @param {function(V,string):any} f\n */\nexport const forEach = (obj, f) => {\n for (const key in obj) {\n f(obj[key], key)\n }\n}\n\n/**\n * @todo implement mapToArray & map\n *\n * @template R\n * @param {Object} obj\n * @param {function(any,string):R} f\n * @return {Array}\n */\nexport const map = (obj, f) => {\n const results = []\n for (const key in obj) {\n results.push(f(obj[key], key))\n }\n return results\n}\n\n/**\n * @param {Object} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n for (const key in obj) {\n if (f(obj[key], key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {Object|undefined} obj\n */\nexport const isEmpty = obj => {\n for (const _k in obj) {\n return false\n }\n return true\n}\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n for (const key in obj) {\n if (!f(obj[key], key)) {\n return false\n }\n }\n return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object} a\n * @param {Object} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val))\n","/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array} fs\n * @param {Array} args\n */\nexport const callAll = (fs, args, i = 0) => {\n try {\n for (; i < fs.length; i++) {\n fs[i](...args)\n }\n } finally {\n if (i < fs.length) {\n callAll(fs, args, i + 1)\n }\n }\n}\n\nexport const nop = () => {}\n\n/**\n * @template T\n * @param {function():T} f\n * @return {T}\n */\nexport const apply = f => f()\n\n/**\n * @template A\n *\n * @param {A} a\n * @return {A}\n */\nexport const id = a => a\n\n/**\n * @template T\n *\n * @param {T} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equalityStrict = (a, b) => a === b\n\n/**\n * @template T\n *\n * @param {Array|object} a\n * @param {Array|object} b\n * @return {boolean}\n */\nexport const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((array.isArray(a) && array.equalFlat(a, /** @type {Array} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/* c8 ignore start */\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a == null || b == null) {\n return equalityStrict(a, b)\n }\n if (a.constructor !== b.constructor) {\n return false\n }\n if (a === b) {\n return true\n }\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n break\n }\n case Map: {\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n return false\n }\n }\n break\n }\n case Object:\n if (object.length(a) !== object.length(b)) {\n return false\n }\n for (const key in a) {\n if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n return false\n }\n }\n break\n case Array:\n if (a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!equalityDeep(a[i], b[i])) {\n return false\n }\n }\n break\n default:\n return false\n }\n return true\n}\n\n/**\n * @template V\n * @template {V} OPTS\n *\n * @param {V} value\n * @param {Array} options\n */\n// @ts-ignore\nexport const isOneOf = (value, options) => options.includes(value)\n/* c8 ignore stop */\n\nexport const isArray = array.isArray\n\n/**\n * @param {any} s\n * @return {s is String}\n */\nexport const isString = (s) => s && s.constructor === String\n\n/**\n * @param {any} n\n * @return {n is Number}\n */\nexport const isNumber = n => n != null && n.constructor === Number\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {any} n\n * @param {TYPE} T\n * @return {n is InstanceType}\n */\nexport const is = (n, T) => n && n.constructor === T\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {TYPE} T\n */\nexport const isTemplate = (T) =>\n /**\n * @param {any} n\n * @return {n is InstanceType}\n **/\n n => n && n.constructor === T\n","/**\n * Isomorphic module to work access the environment (query params, env variables).\n *\n * @module map\n */\n\nimport * as map from './map.js'\nimport * as string from './string.js'\nimport * as conditions from './conditions.js'\nimport * as storage from './storage.js'\nimport * as f from './function.js'\n\n/* c8 ignore next */\n// @ts-ignore\nexport const isNode = typeof process !== 'undefined' && process.release &&\n /node|io\\.js/.test(process.release.name)\n/* c8 ignore next */\nexport const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && !isNode\n/* c8 ignore next 3 */\nexport const isMac = typeof navigator !== 'undefined'\n ? /Mac/.test(navigator.platform)\n : false\n\n/**\n * @type {Map}\n */\nlet params\nconst args = []\n\n/* c8 ignore start */\nconst computeParams = () => {\n if (params === undefined) {\n if (isNode) {\n params = map.create()\n const pargs = process.argv\n let currParamName = null\n for (let i = 0; i < pargs.length; i++) {\n const parg = pargs[i]\n if (parg[0] === '-') {\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n currParamName = parg\n } else {\n if (currParamName !== null) {\n params.set(currParamName, parg)\n currParamName = null\n } else {\n args.push(parg)\n }\n }\n }\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n // in ReactNative for example this would not be true (unless connected to the Remote Debugger)\n } else if (typeof location === 'object') {\n params = map.create(); // eslint-disable-next-line no-undef\n (location.search || '?').slice(1).split('&').forEach((kv) => {\n if (kv.length !== 0) {\n const [key, value] = kv.split('=')\n params.set(`--${string.fromCamelCase(key, '-')}`, value)\n params.set(`-${string.fromCamelCase(key, '-')}`, value)\n }\n })\n } else {\n params = map.create()\n }\n }\n return params\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next */\nexport const hasParam = (name) => computeParams().has(name)\n\n/**\n * @param {string} name\n * @param {string} defaultVal\n * @return {string}\n */\n/* c8 ignore next 2 */\nexport const getParam = (name, defaultVal) =>\n computeParams().get(name) || defaultVal\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 4 */\nexport const getVariable = (name) =>\n isNode\n ? conditions.undefinedToNull(process.env[name.toUpperCase()])\n : conditions.undefinedToNull(storage.varStorage.getItem(name))\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 2 */\nexport const getConf = (name) =>\n computeParams().get('--' + name) || getVariable(name)\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next 2 */\nexport const hasConf = (name) =>\n hasParam('--' + name) || getVariable(name) !== null\n\n/* c8 ignore next */\nexport const production = hasConf('production')\n\n/* c8 ignore next 2 */\nconst forceColor = isNode &&\n f.isOneOf(process.env.FORCE_COLOR, ['true', '1', '2'])\n\n/* c8 ignore start */\nexport const supportsColor = !hasParam('no-colors') &&\n (!isNode || process.stdout.isTTY || forceColor) && (\n !isNode || hasParam('color') || forceColor ||\n getVariable('COLORTERM') !== null ||\n (getVariable('TERM') || '').includes('color')\n)\n/* c8 ignore stop */\n","/**\n * Common Math expressions.\n *\n * @module math\n */\n\nexport const floor = Math.floor\nexport const ceil = Math.ceil\nexport const abs = Math.abs\nexport const imul = Math.imul\nexport const round = Math.round\nexport const log10 = Math.log10\nexport const log2 = Math.log2\nexport const log = Math.log\nexport const sqrt = Math.sqrt\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The sum of a and b\n */\nexport const add = (a, b) => a + b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The smaller element of a and b\n */\nexport const min = (a, b) => a < b ? a : b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The bigger element of a and b\n */\nexport const max = (a, b) => a > b ? a : b\n\nexport const isNaN = Number.isNaN\n\nexport const pow = Math.pow\n/**\n * Base 10 exponential function. Returns the value of 10 raised to the power of pow.\n *\n * @param {number} exp\n * @return {number}\n */\nexport const exp10 = exp => Math.pow(10, exp)\n\nexport const sign = Math.sign\n\n/**\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\nexport const HIGHEST_INT32 = binary.BITS31\nexport const HIGHEST_UINT32 = binary.BITS32\n\n/* c8 ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n","/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\nimport * as string from './string.js'\nimport * as array from './array.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * @param {function(Encoder):void} f\n */\nexport const encode = (f) => {\n const encoder = createEncoder()\n f(encoder)\n return toUint8Array(encoder)\n}\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Check whether encoder is empty.\n *\n * @function\n * @param {Encoder} encoder\n * @return {boolean}\n */\nexport const hasContent = encoder => encoder.cpos > 0 || encoder.bufs.length > 0\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nexport const verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer. Max encodable integer is 2^53.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num = math.floor(num / 64) // shift >>> 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n}\n\n/**\n * A cache to store strings temporarily\n */\nconst _strBuffer = new Uint8Array(30000)\nconst _maxStrBSize = _strBuffer.length / 3\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringNative = (encoder, str) => {\n if (str.length < _maxStrBSize) {\n // We can encode the string into the existing buffer\n /* c8 ignore next */\n const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0\n writeVarUint(encoder, written)\n for (let i = 0; i < written; i++) {\n write(encoder, _strBuffer[i])\n }\n } else {\n writeVarUint8Array(encoder, string.encodeUtf8(str))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringPolyfill = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\n/* c8 ignore next */\nexport const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill\n\n/**\n * Write a string terminated by a special byte sequence. This is not very performant and is\n * generally discouraged. However, the resulting byte arrays are lexiographically ordered which\n * makes this a nice feature for databases.\n *\n * The string will be encoded using utf8 and then terminated and escaped using writeTerminatingUint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const writeTerminatedString = (encoder, str) =>\n writeTerminatedUint8Array(encoder, string.encodeUtf8(str))\n\n/**\n * Write a terminating Uint8Array. Note that this is not performant and is generally\n * discouraged. There are few situations when this is needed.\n *\n * We use 0x0 as a terminating character. 0x1 serves as an escape character for 0x0 and 0x1.\n *\n * Example: [0,1,2] is encoded to [1,0,1,1,2,0]. 0x0, and 0x1 needed to be escaped using 0x1. Then\n * the result is terminated using the 0x0 character.\n *\n * This is basically how many systems implement null terminated strings. However, we use an escape\n * character 0x1 to avoid issues and potenial attacks on our database (if this is used as a key\n * encoder for NoSql databases).\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} buf The string that is to be encoded.\n */\nexport const writeTerminatedUint8Array = (encoder, buf) => {\n for (let i = 0; i < buf.length; i++) {\n const b = buf[i]\n if (b === 0 || b === 1) {\n write(encoder, 1)\n }\n write(encoder, buf[i])\n }\n write(encoder, 0)\n}\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && math.abs(data) <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (array.isArray(data)) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n","/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* c8 ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n","/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as binary from './binary.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as string from './string.js'\nimport * as error from './error.js'\nimport * as encoding from './encoding.js'\n\nconst errorUnexpectedEndOfArray = error.create('Unexpected end of array')\nconst errorIntegerOutOfRange = error.create('Integer out of Range')\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n */\nexport class Decoder {\n /**\n * @param {Uint8Array} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @param {Uint8Array} uint8Array\n * @return {Decoder}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = buffer.createUint8ArrayViewFromArrayBuffer(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let mult = 1\n const len = decoder.arr.length\n while (decoder.pos < len) {\n const r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num\n mult *= 128 // next iteration, shift 7 \"more\" to the left\n if (r < binary.BIT8) {\n return num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let mult = 64\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n const len = decoder.arr.length\n while (decoder.pos < len) {\n r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult\n mult *= 128\n if (r < binary.BIT8) {\n return sign * num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * We don't test this function anymore as we use native decoding/encoding by default now.\n * Better not modify this anymore..\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\n/* c8 ignore start */\nexport const _readVarStringPolyfill = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n/* c8 ignore stop */\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n */\nexport const _readVarStringNative = decoder =>\n /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder))\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n *\n */\n/* c8 ignore next */\nexport const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill\n\n/**\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTerminatedUint8Array = decoder => {\n const encoder = encoding.createEncoder()\n let b\n while (true) {\n b = readUint8(decoder)\n if (b === 0) {\n return encoding.toUint8Array(encoder)\n }\n if (b === 1) {\n b = readUint8(decoder)\n }\n encoding.write(encoder, b)\n }\n}\n\n/**\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const readTerminatedString = decoder => string.decodeUtf8(readTerminatedUint8Array(decoder))\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object\n const len = readVarUint(decoder)\n /**\n * @type {Object}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = math.floor(diff / 2) // shift >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n","/**\n * Utility functions to work with buffers (Uint8Array).\n *\n * @module buffer\n */\n\nimport * as string from './string.js'\nimport * as env from './environment.js'\nimport * as encoding from './encoding.js'\nimport * as decoding from './decoding.js'\n\n/**\n * @param {number} len\n */\nexport const createUint8ArrayFromLen = len => new Uint8Array(len)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n * @param {number} byteOffset\n * @param {number} length\n */\nexport const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n */\nexport const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer)\n\n/* c8 ignore start */\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Browser = bytes => {\n let s = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n s += string.fromCharCode(bytes[i])\n }\n // eslint-disable-next-line no-undef\n return btoa(s)\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')\n\n/* c8 ignore start */\n/**\n * @param {string} s\n * @return {Uint8Array}\n */\nconst fromBase64Browser = s => {\n // eslint-disable-next-line no-undef\n const a = atob(s)\n const bytes = createUint8ArrayFromLen(a.length)\n for (let i = 0; i < a.length; i++) {\n bytes[i] = a.charCodeAt(i)\n }\n return bytes\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} s\n */\nconst fromBase64Node = s => {\n const buf = Buffer.from(s, 'base64')\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n}\n\n/* c8 ignore next */\nexport const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node\n\n/* c8 ignore next */\nexport const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node\n\n/**\n * Copy the content of an Uint8Array view to a new ArrayBuffer.\n *\n * @param {Uint8Array} uint8Array\n * @return {Uint8Array}\n */\nexport const copyUint8Array = uint8Array => {\n const newBuf = createUint8ArrayFromLen(uint8Array.byteLength)\n newBuf.set(uint8Array)\n return newBuf\n}\n\n/**\n * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type.\n * See encoding.writeAny for more information.\n *\n * @param {any} data\n * @return {Uint8Array}\n */\nexport const encodeAny = data => {\n const encoder = encoding.createEncoder()\n encoding.writeAny(encoder, data)\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Decode an any-encoded value.\n *\n * @param {Uint8Array} buf\n * @return {any}\n */\nexport const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf))\n","/* eslint-env browser */\n\n/**\n * Helpers for cross-tab communication using broadcastchannel with LocalStorage fallback.\n *\n * ```js\n * // In browser window A:\n * broadcastchannel.subscribe('my events', data => console.log(data))\n * broadcastchannel.publish('my events', 'Hello world!') // => A: 'Hello world!' fires synchronously in same tab\n *\n * // In browser window B:\n * broadcastchannel.publish('my events', 'hello from tab B') // => A: 'hello from tab B'\n * ```\n *\n * @module broadcastchannel\n */\n\n// @todo before next major: use Uint8Array instead as buffer object\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as buffer from './buffer.js'\nimport * as storage from './storage.js'\n\n/**\n * @typedef {Object} Channel\n * @property {Set} Channel.subs\n * @property {any} Channel.bc\n */\n\n/**\n * @type {Map}\n */\nconst channels = new Map()\n\n/* c8 ignore start */\nclass LocalStoragePolyfill {\n /**\n * @param {string} room\n */\n constructor (room) {\n this.room = room\n /**\n * @type {null|function({data:ArrayBuffer}):void}\n */\n this.onmessage = null\n /**\n * @param {any} e\n */\n this._onChange = e => e.key === room && this.onmessage !== null && this.onmessage({ data: buffer.fromBase64(e.newValue || '') })\n storage.onChange(this._onChange)\n }\n\n /**\n * @param {ArrayBuffer} buf\n */\n postMessage (buf) {\n storage.varStorage.setItem(this.room, buffer.toBase64(buffer.createUint8ArrayFromArrayBuffer(buf)))\n }\n\n close () {\n storage.offChange(this._onChange)\n }\n}\n/* c8 ignore stop */\n\n// Use BroadcastChannel or Polyfill\n/* c8 ignore next */\nconst BC = typeof BroadcastChannel === 'undefined' ? LocalStoragePolyfill : BroadcastChannel\n\n/**\n * @param {string} room\n * @return {Channel}\n */\nconst getChannel = room =>\n map.setIfUndefined(channels, room, () => {\n const subs = set.create()\n const bc = new BC(room)\n /**\n * @param {{data:ArrayBuffer}} e\n */\n /* c8 ignore next */\n bc.onmessage = e => subs.forEach(sub => sub(e.data, 'broadcastchannel'))\n return {\n bc, subs\n }\n })\n\n/**\n * Subscribe to global `publish` events.\n *\n * @function\n * @param {string} room\n * @param {function(any, any):any} f\n */\nexport const subscribe = (room, f) => {\n getChannel(room).subs.add(f)\n return f\n}\n\n/**\n * Unsubscribe from `publish` global events.\n *\n * @function\n * @param {string} room\n * @param {function(any, any):any} f\n */\nexport const unsubscribe = (room, f) => {\n const channel = getChannel(room)\n const unsubscribed = channel.subs.delete(f)\n if (unsubscribed && channel.subs.size === 0) {\n channel.bc.close()\n channels.delete(room)\n }\n return unsubscribed\n}\n\n/**\n * Publish data to all subscribers (including subscribers on this tab)\n *\n * @function\n * @param {string} room\n * @param {any} data\n * @param {any} [origin]\n */\nexport const publish = (room, data, origin = null) => {\n const c = getChannel(room)\n c.bc.postMessage(data)\n c.subs.forEach(sub => sub(data, origin))\n}\n","/**\n * Mutual exclude for JavaScript.\n *\n * @module mutex\n */\n\n/**\n * @callback mutex\n * @param {function():void} cb Only executed when this mutex is not in the current stack\n * @param {function():void} [elseCb] Executed when this mutex is in the current stack\n */\n\n/**\n * Creates a mutual exclude function with the following property:\n *\n * ```js\n * const mutex = createMutex()\n * mutex(() => {\n * // This function is immediately executed\n * mutex(() => {\n * // This function is not executed, as the mutex is already active.\n * })\n * })\n * ```\n *\n * @return {mutex} A mutual exclude function\n * @public\n */\nexport const createMutex = () => {\n let token = true\n return (f, g) => {\n if (token) {\n token = false\n try {\n f()\n } finally {\n token = true\n }\n } else if (g !== undefined) {\n g()\n }\n }\n}\n","/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* c8 ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n","/**\n * Observable class prototype.\n *\n * @module observable\n */\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as array from './array.js'\n\n/**\n * Handles named events.\n *\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map}\n */\n this._observers = map.create()\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, name, set.create).add(f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, _f)\n f(...args)\n }\n this.on(name, _f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @param {N} name The event name.\n * @param {Array} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // 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.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n","/**\n * @module awareness-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as time from 'lib0/time'\nimport * as math from 'lib0/math'\nimport { Observable } from 'lib0/observable'\nimport * as f from 'lib0/function'\nimport * as Y from 'yjs' // eslint-disable-line\n\nexport const outdatedTimeout = 30000\n\n/**\n * @typedef {Object} MetaClientState\n * @property {number} MetaClientState.clock\n * @property {number} MetaClientState.lastUpdated unix timestamp\n */\n\n/**\n * The Awareness class implements a simple shared state protocol that can be used for non-persistent data like awareness information\n * (cursor, username, status, ..). Each client can update its own local state and listen to state changes of\n * remote clients. Every client may set a state of a remote peer to `null` to mark the client as offline.\n *\n * Each client is identified by a unique client id (something we borrow from `doc.clientID`). A client can override\n * its own state by propagating a message with an increasing timestamp (`clock`). If such a message is received, it is\n * applied if the known state of that client is older than the new state (`clock < newClock`). If a client thinks that\n * a remote client is offline, it may propagate a message with\n * `{ clock: currentClientClock, state: null, client: remoteClient }`. If such a\n * message is received, and the known clock of that client equals the received clock, it will override the state with `null`.\n *\n * Before a client disconnects, it should propagate a `null` state with an updated clock.\n *\n * Awareness states must be updated every 30 seconds. Otherwise the Awareness instance will delete the client state.\n *\n * @extends {Observable}\n */\nexport class Awareness extends Observable {\n /**\n * @param {Y.Doc} doc\n */\n constructor (doc) {\n super()\n this.doc = doc\n /**\n * @type {number}\n */\n this.clientID = doc.clientID\n /**\n * Maps from client id to client state\n * @type {Map>}\n */\n this.states = new Map()\n /**\n * @type {Map}\n */\n this.meta = new Map()\n this._checkInterval = /** @type {any} */ (setInterval(() => {\n const now = time.getUnixTime()\n if (this.getLocalState() !== null && (outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ (this.meta.get(this.clientID)).lastUpdated)) {\n // renew local clock\n this.setLocalState(this.getLocalState())\n }\n /**\n * @type {Array}\n */\n const remove = []\n this.meta.forEach((meta, clientid) => {\n if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) {\n remove.push(clientid)\n }\n })\n if (remove.length > 0) {\n removeAwarenessStates(this, remove, 'timeout')\n }\n }, math.floor(outdatedTimeout / 10)))\n doc.on('destroy', () => {\n this.destroy()\n })\n this.setLocalState({})\n }\n\n destroy () {\n this.emit('destroy', [this])\n this.setLocalState(null)\n super.destroy()\n clearInterval(this._checkInterval)\n }\n\n /**\n * @return {Object|null}\n */\n getLocalState () {\n return this.states.get(this.clientID) || null\n }\n\n /**\n * @param {Object|null} state\n */\n setLocalState (state) {\n const clientID = this.clientID\n const currLocalMeta = this.meta.get(clientID)\n const clock = currLocalMeta === undefined ? 0 : currLocalMeta.clock + 1\n const prevState = this.states.get(clientID)\n if (state === null) {\n this.states.delete(clientID)\n } else {\n this.states.set(clientID, state)\n }\n this.meta.set(clientID, {\n clock,\n lastUpdated: time.getUnixTime()\n })\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n if (state === null) {\n removed.push(clientID)\n } else if (prevState == null) {\n if (state != null) {\n added.push(clientID)\n }\n } else {\n updated.push(clientID)\n if (!f.equalityDeep(prevState, state)) {\n filteredUpdated.push(clientID)\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n this.emit('change', [{ added, updated: filteredUpdated, removed }, 'local'])\n }\n this.emit('update', [{ added, updated, removed }, 'local'])\n }\n\n /**\n * @param {string} field\n * @param {any} value\n */\n setLocalStateField (field, value) {\n const state = this.getLocalState()\n if (state !== null) {\n this.setLocalState({\n ...state,\n [field]: value\n })\n }\n }\n\n /**\n * @return {Map>}\n */\n getStates () {\n return this.states\n }\n}\n\n/**\n * Mark (remote) clients as inactive and remove them from the list of active peers.\n * This change will be propagated to remote clients.\n *\n * @param {Awareness} awareness\n * @param {Array} clients\n * @param {any} origin\n */\nexport const removeAwarenessStates = (awareness, clients, origin) => {\n const removed = []\n for (let i = 0; i < clients.length; i++) {\n const clientID = clients[i]\n if (awareness.states.has(clientID)) {\n awareness.states.delete(clientID)\n if (clientID === awareness.clientID) {\n const curMeta = /** @type {MetaClientState} */ (awareness.meta.get(clientID))\n awareness.meta.set(clientID, {\n clock: curMeta.clock + 1,\n lastUpdated: time.getUnixTime()\n })\n }\n removed.push(clientID)\n }\n }\n if (removed.length > 0) {\n awareness.emit('change', [{ added: [], updated: [], removed }, origin])\n awareness.emit('update', [{ added: [], updated: [], removed }, origin])\n }\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Array} clients\n * @return {Uint8Array}\n */\nexport const encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {\n const len = clients.length\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = clients[i]\n const state = states.get(clientID) || null\n const clock = /** @type {MetaClientState} */ (awareness.meta.get(clientID)).clock\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(state))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Modify the content of an awareness update before re-encoding it to an awareness update.\n *\n * This might be useful when you have a central server that wants to ensure that clients\n * cant hijack somebody elses identity.\n *\n * @param {Uint8Array} update\n * @param {function(any):any} modify\n * @return {Uint8Array}\n */\nexport const modifyAwarenessUpdate = (update, modify) => {\n const decoder = decoding.createDecoder(update)\n const encoder = encoding.createEncoder()\n const len = decoding.readVarUint(decoder)\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n const clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const modifiedState = modify(state)\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(modifiedState))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Uint8Array} update\n * @param {any} origin This will be added to the emitted change event\n */\nexport const applyAwarenessUpdate = (awareness, update, origin) => {\n const decoder = decoding.createDecoder(update)\n const timestamp = time.getUnixTime()\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n const len = decoding.readVarUint(decoder)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n let clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const clientMeta = awareness.meta.get(clientID)\n const prevState = awareness.states.get(clientID)\n const currClock = clientMeta === undefined ? 0 : clientMeta.clock\n if (currClock < clock || (currClock === clock && state === null && awareness.states.has(clientID))) {\n if (state === null) {\n // never let a remote client remove this local state\n if (clientID === awareness.clientID && awareness.getLocalState() != null) {\n // remote client removed the local state. Do not remote state. Broadcast a message indicating\n // that this client still exists by increasing the clock\n clock++\n } else {\n awareness.states.delete(clientID)\n }\n } else {\n awareness.states.set(clientID, state)\n }\n awareness.meta.set(clientID, {\n clock,\n lastUpdated: timestamp\n })\n if (clientMeta === undefined && state !== null) {\n added.push(clientID)\n } else if (clientMeta !== undefined && state === null) {\n removed.push(clientID)\n } else if (state !== null) {\n if (!f.equalityDeep(state, prevState)) {\n filteredUpdated.push(clientID)\n }\n updated.push(clientID)\n }\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n awareness.emit('change', [{\n added, updated: filteredUpdated, removed\n }, origin])\n }\n if (added.length > 0 || updated.length > 0 || removed.length > 0) {\n awareness.emit('update', [{\n added, updated, removed\n }, origin])\n }\n}\n","export default class EventEmitter {\n\n public callbacks: { [key: string]: Function[] } = {}\n\n public on(event: string, fn: Function): this {\n if (!this.callbacks[event]) {\n this.callbacks[event] = []\n }\n\n this.callbacks[event].push(fn)\n\n return this\n }\n\n protected emit(event: string, ...args: any): this {\n const callbacks = this.callbacks[event]\n\n if (callbacks) {\n callbacks.forEach(callback => callback.apply(this, args))\n }\n\n return this\n }\n\n public off(event: string, fn?: Function): this {\n const callbacks = this.callbacks[event]\n\n if (callbacks) {\n if (fn) {\n this.callbacks[event] = callbacks.filter(callback => callback !== fn)\n } else {\n delete this.callbacks[event]\n }\n }\n\n return this\n }\n\n removeAllListeners(): void {\n this.callbacks = {}\n }\n}\n","/**\n * Utility module to work with urls.\n *\n * @module url\n */\n\nimport * as object from './object.js'\n\n/**\n * Parse query parameters from an url.\n *\n * @param {string} url\n * @return {Object}\n */\nexport const decodeQueryParams = url => {\n /**\n * @type {Object}\n */\n const query = {}\n const urlQuerySplit = url.split('?')\n const pairs = urlQuerySplit[urlQuerySplit.length - 1].split('&')\n for (let i = 0; i < pairs.length; i++) {\n const item = pairs[i]\n if (item.length > 0) {\n const pair = item.split('=')\n query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '')\n }\n }\n return query\n}\n\n/**\n * @param {Object} params\n * @return {string}\n */\nexport const encodeQueryParams = params =>\n object.map(params, (val, key) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&')\n","import { Encoder } from 'lib0/encoding'\nimport type { CloseEvent, Event, MessageEvent } from 'ws'\nimport { Awareness } from 'y-protocols/awareness'\nimport * as Y from 'yjs'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { AuthenticationMessage } from './OutgoingMessages/AuthenticationMessage.js'\nimport { AwarenessMessage } from './OutgoingMessages/AwarenessMessage.js'\nimport { QueryAwarenessMessage } from './OutgoingMessages/QueryAwarenessMessage.js'\nimport { SyncStepOneMessage } from './OutgoingMessages/SyncStepOneMessage.js'\nimport { SyncStepTwoMessage } from './OutgoingMessages/SyncStepTwoMessage.js'\nimport { UpdateMessage } from './OutgoingMessages/UpdateMessage.js'\n\nexport enum MessageType {\n Sync = 0,\n Awareness = 1,\n Auth = 2,\n QueryAwareness = 3,\n Stateless = 5,\n CLOSE = 7,\n SyncStatus = 8,\n}\n\nexport enum WebSocketStatus {\n Connecting = 'connecting',\n Connected = 'connected',\n Disconnected = 'disconnected',\n}\n\nexport interface OutgoingMessageInterface {\n encoder: Encoder\n type?: MessageType\n}\n\nexport interface OutgoingMessageArguments {\n documentName: string,\n token: string,\n document: Y.Doc,\n awareness: Awareness,\n clients: number[],\n states: Map,\n update: any,\n payload: string,\n encoder: Encoder,\n}\n\nexport interface Constructable {\n new(...args: any) : T\n}\n\nexport type ConstructableOutgoingMessage =\n Constructable |\n Constructable |\n Constructable |\n Constructable |\n Constructable |\n Constructable\n\nexport type onAuthenticationFailedParameters = {\n reason: string,\n}\n\nexport type onOpenParameters = {\n event: Event,\n}\n\nexport type onMessageParameters = {\n event: MessageEvent,\n message: IncomingMessage,\n}\n\nexport type onOutgoingMessageParameters = {\n message: OutgoingMessage,\n}\n\nexport type onStatusParameters = {\n status: WebSocketStatus,\n}\n\nexport type onSyncedParameters = {\n state: boolean,\n}\n\nexport type onDisconnectParameters = {\n event: CloseEvent,\n}\n\nexport type onCloseParameters = {\n event: CloseEvent,\n}\n\nexport type onAwarenessUpdateParameters = {\n states: StatesArray\n}\n\nexport type onAwarenessChangeParameters = {\n states: StatesArray\n}\n\nexport type onStatelessParameters = {\n payload: string\n}\n\nexport type StatesArray = { clientId: number, [key: string | number]: any }[]\n","import {\n Forbidden, MessageTooBig, Unauthorized, WsReadyStates,\n} from '@hocuspocus/common'\nimport { retry } from '@lifeomic/attempt'\nimport * as mutex from 'lib0/mutex'\nimport * as time from 'lib0/time'\nimport * as url from 'lib0/url'\nimport type { MessageEvent } from 'ws'\nimport { Event } from 'ws'\nimport EventEmitter from './EventEmitter.js'\nimport { HocuspocusProvider } from './HocuspocusProvider.js'\nimport {\n WebSocketStatus,\n onAwarenessChangeParameters, onAwarenessUpdateParameters,\n onCloseParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onStatusParameters,\n} from './types.js'\n\nexport type HocuspocusProviderWebsocketConfiguration =\n Required>\n & Partial\n\nexport interface CompleteHocuspocusProviderWebsocketConfiguration {\n /**\n * URL of your @hocuspocus/server instance\n */\n url: string,\n\n /**\n * Pass `false` to start the connection manually.\n */\n connect: boolean,\n\n /**\n * URL parameters that should be added.\n */\n parameters: { [key: string]: any },\n /**\n * An optional WebSocket polyfill, for example for Node.js\n */\n WebSocketPolyfill: any,\n\n /**\n * Disconnect when no message is received for the defined amount of milliseconds.\n */\n messageReconnectTimeout: number,\n /**\n * The delay between each attempt in milliseconds. You can provide a factor to have the delay grow exponentially.\n */\n delay: number,\n /**\n * The intialDelay is the amount of time to wait before making the first attempt. This option should typically be 0 since you typically want the first attempt to happen immediately.\n */\n initialDelay: number,\n /**\n * The factor option is used to grow the delay exponentially.\n */\n factor: number,\n /**\n * The maximum number of attempts or 0 if there is no limit on number of attempts.\n */\n maxAttempts: number,\n /**\n * minDelay is used to set a lower bound of delay when jitter is enabled. This property has no effect if jitter is disabled.\n */\n minDelay: number,\n /**\n * The maxDelay option is used to set an upper bound for the delay when factor is enabled. A value of 0 can be provided if there should be no upper bound when calculating delay.\n */\n maxDelay: number,\n /**\n * If jitter is true then the calculated delay will be a random integer value between minDelay and the calculated delay for the current iteration.\n */\n jitter: boolean,\n /**\n * A timeout in milliseconds. If timeout is non-zero then a timer is set using setTimeout. If the timeout is triggered then future attempts will be aborted.\n */\n timeout: number,\n onOpen: (data: onOpenParameters) => void,\n onConnect: () => void,\n onMessage: (data: onMessageParameters) => void,\n onOutgoingMessage: (data: onOutgoingMessageParameters) => void,\n onStatus: (data: onStatusParameters) => void,\n onDisconnect: (data: onDisconnectParameters) => void,\n onClose: (data: onCloseParameters) => void,\n onDestroy: () => void,\n onAwarenessUpdate: (data: onAwarenessUpdateParameters) => void,\n onAwarenessChange: (data: onAwarenessChangeParameters) => void,\n /**\n * Don’t output any warnings.\n */\n quiet: boolean,\n}\n\nexport class HocuspocusProviderWebsocket extends EventEmitter {\n private messageQueue: any[] = []\n\n public configuration: CompleteHocuspocusProviderWebsocketConfiguration = {\n url: '',\n // @ts-ignore\n document: undefined,\n // @ts-ignore\n awareness: undefined,\n WebSocketPolyfill: undefined,\n parameters: {},\n connect: true,\n broadcast: true,\n forceSyncInterval: false,\n // TODO: this should depend on awareness.outdatedTime\n messageReconnectTimeout: 30000,\n // 1 second\n delay: 1000,\n // instant\n initialDelay: 0,\n // double the delay each time\n factor: 2,\n // unlimited retries\n maxAttempts: 0,\n // wait at least 1 second\n minDelay: 1000,\n // at least every 30 seconds\n maxDelay: 30000,\n // randomize\n jitter: true,\n // retry forever\n timeout: 0,\n onOpen: () => null,\n onConnect: () => null,\n onMessage: () => null,\n onOutgoingMessage: () => null,\n onStatus: () => null,\n onDisconnect: () => null,\n onClose: () => null,\n onDestroy: () => null,\n onAwarenessUpdate: () => null,\n onAwarenessChange: () => null,\n quiet: false,\n }\n\n subscribedToBroadcastChannel = false\n\n webSocket: WebSocket | null = null\n\n shouldConnect = true\n\n status = WebSocketStatus.Disconnected\n\n lastMessageReceived = 0\n\n mux = mutex.createMutex()\n\n intervals: any = {\n forceSync: null,\n connectionChecker: null,\n }\n\n connectionAttempt: {\n resolve: (value?: any) => void\n reject: (reason?: any) => void\n } | null = null\n\n constructor(configuration: HocuspocusProviderWebsocketConfiguration) {\n super()\n this.setConfiguration(configuration)\n\n this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill ? configuration.WebSocketPolyfill : WebSocket\n\n this.on('open', this.configuration.onOpen)\n this.on('open', this.onOpen.bind(this))\n this.on('connect', this.configuration.onConnect)\n this.on('message', this.configuration.onMessage)\n this.on('outgoingMessage', this.configuration.onOutgoingMessage)\n this.on('status', this.configuration.onStatus)\n this.on('status', this.onStatus.bind(this))\n this.on('disconnect', this.configuration.onDisconnect)\n this.on('close', this.configuration.onClose)\n this.on('destroy', this.configuration.onDestroy)\n this.on('awarenessUpdate', this.configuration.onAwarenessUpdate)\n this.on('awarenessChange', this.configuration.onAwarenessChange)\n\n this.on('close', this.onClose.bind(this))\n this.on('message', this.onMessage.bind(this))\n\n this.registerEventListeners()\n\n this.intervals.connectionChecker = setInterval(\n this.checkConnection.bind(this),\n this.configuration.messageReconnectTimeout / 10,\n )\n\n if (typeof configuration.connect !== 'undefined') {\n this.shouldConnect = configuration.connect\n }\n\n if (!this.shouldConnect) {\n return\n }\n\n this.connect()\n }\n\n receivedOnOpenPayload?: Event | undefined = undefined\n\n receivedOnStatusPayload?: onStatusParameters | undefined = undefined\n\n async onOpen(event: Event) {\n this.receivedOnOpenPayload = event\n }\n\n async onStatus(data: onStatusParameters) {\n this.receivedOnStatusPayload = data\n }\n\n attach(provider: HocuspocusProvider) {\n if (this.receivedOnOpenPayload) {\n provider.onOpen(this.receivedOnOpenPayload)\n }\n\n if (this.receivedOnStatusPayload) {\n provider.onStatus(this.receivedOnStatusPayload)\n }\n }\n\n detach(provider: HocuspocusProvider) {\n // tell the server to remove the listener\n\n }\n\n public setConfiguration(configuration: Partial = {}): void {\n this.configuration = { ...this.configuration, ...configuration }\n }\n\n boundConnect = this.connect.bind(this)\n\n cancelWebsocketRetry?: () => void\n\n async connect() {\n if (this.status === WebSocketStatus.Connected) {\n return\n }\n\n // Always cancel any previously initiated connection retryer instances\n if (this.cancelWebsocketRetry) {\n this.cancelWebsocketRetry()\n this.cancelWebsocketRetry = undefined\n }\n\n this.shouldConnect = true\n\n const abortableRetry = () => {\n let cancelAttempt = false\n\n const retryPromise = retry(this.createWebSocketConnection.bind(this), {\n delay: this.configuration.delay,\n initialDelay: this.configuration.initialDelay,\n factor: this.configuration.factor,\n maxAttempts: this.configuration.maxAttempts,\n minDelay: this.configuration.minDelay,\n maxDelay: this.configuration.maxDelay,\n jitter: this.configuration.jitter,\n timeout: this.configuration.timeout,\n beforeAttempt: context => {\n if (!this.shouldConnect || cancelAttempt) {\n context.abort()\n }\n },\n }).catch((error: any) => {\n // If we aborted the connection attempt then don’t throw an error\n // ref: https://github.com/lifeomic/attempt/blob/master/src/index.ts#L136\n if (error && error.code !== 'ATTEMPT_ABORTED') {\n throw error\n }\n })\n\n return {\n retryPromise,\n cancelFunc: () => {\n cancelAttempt = true\n },\n }\n }\n\n const { retryPromise, cancelFunc } = abortableRetry()\n this.cancelWebsocketRetry = cancelFunc\n\n return retryPromise\n }\n\n createWebSocketConnection() {\n return new Promise((resolve, reject) => {\n if (this.webSocket) {\n this.messageQueue = []\n this.webSocket.close()\n this.webSocket = null\n }\n\n // Init the WebSocket connection\n const ws = new this.configuration.WebSocketPolyfill(this.url)\n ws.binaryType = 'arraybuffer'\n ws.onmessage = (payload: any) => this.emit('message', payload)\n ws.onclose = (payload: any) => this.emit('close', { event: payload })\n ws.onopen = (payload: any) => this.emit('open', payload)\n ws.onerror = (err: any) => {\n reject(err)\n }\n this.webSocket = ws\n\n // Reset the status\n this.status = WebSocketStatus.Connecting\n this.emit('status', { status: WebSocketStatus.Connecting })\n\n // Store resolve/reject for later use\n this.connectionAttempt = {\n resolve,\n reject,\n }\n })\n }\n\n onMessage(event: MessageEvent) {\n this.resolveConnectionAttempt()\n }\n\n resolveConnectionAttempt() {\n if (this.connectionAttempt) {\n this.connectionAttempt.resolve()\n this.connectionAttempt = null\n\n this.status = WebSocketStatus.Connected\n this.emit('status', { status: WebSocketStatus.Connected })\n this.emit('connect')\n this.messageQueue.forEach(message => this.send(message))\n this.messageQueue = []\n }\n }\n\n stopConnectionAttempt() {\n this.connectionAttempt = null\n }\n\n rejectConnectionAttempt() {\n this.connectionAttempt?.reject()\n this.connectionAttempt = null\n }\n\n checkConnection() {\n // Don’t check the connection when it’s not even established\n if (this.status !== WebSocketStatus.Connected) {\n return\n }\n\n // Don’t close then connection while waiting for the first message\n if (!this.lastMessageReceived) {\n return\n }\n\n // Don’t close the connection when a message was received recently\n if (this.configuration.messageReconnectTimeout >= time.getUnixTime() - this.lastMessageReceived) {\n return\n }\n\n // No message received in a long time, not even your own\n // Awareness updates, which are updated every 15 seconds.\n this.webSocket?.close()\n this.messageQueue = []\n }\n\n registerEventListeners() {\n if (typeof window === 'undefined') {\n return\n }\n\n window.addEventListener('online', this.boundConnect)\n }\n\n // Ensure that the URL always ends with /\n get serverUrl() {\n while (this.configuration.url[this.configuration.url.length - 1] === '/') {\n return this.configuration.url.slice(0, this.configuration.url.length - 1)\n }\n\n return this.configuration.url\n }\n\n get url() {\n const encodedParams = url.encodeQueryParams(this.configuration.parameters)\n\n return `${this.serverUrl}${encodedParams.length === 0 ? '' : `?${encodedParams}`}`\n }\n\n disconnect() {\n this.shouldConnect = false\n\n if (this.webSocket === null) {\n return\n }\n\n try {\n this.webSocket.close()\n this.messageQueue = []\n } catch {\n //\n }\n }\n\n send(message: any) {\n if (this.webSocket?.readyState === WsReadyStates.Open) {\n this.webSocket.send(message)\n } else {\n this.messageQueue.push(message)\n }\n }\n\n onClose({ event }: onCloseParameters) {\n this.webSocket = null\n\n if (this.status === WebSocketStatus.Connected) {\n this.status = WebSocketStatus.Disconnected\n this.emit('status', { status: WebSocketStatus.Disconnected })\n this.emit('disconnect', { event })\n }\n\n if (event.code === Unauthorized.code) {\n if (event.reason === Unauthorized.reason) {\n console.warn('[HocuspocusProvider] An authentication token is required, but you didn’t send one. Try adding a `token` to your HocuspocusProvider configuration. Won’t try again.')\n } else {\n console.warn(`[HocuspocusProvider] Connection closed with status Unauthorized: ${event.reason}`)\n }\n\n this.shouldConnect = false\n }\n\n if (event.code === Forbidden.code) {\n if (!this.configuration.quiet) {\n console.warn('[HocuspocusProvider] The provided authentication token isn’t allowed to connect to this server. Will try again.')\n return // TODO REMOVE ME\n }\n }\n\n if (event.code === MessageTooBig.code) {\n console.warn(`[HocuspocusProvider] Connection closed with status MessageTooBig: ${event.reason}`)\n this.shouldConnect = false\n }\n\n if (this.connectionAttempt) {\n // That connection attempt failed.\n this.rejectConnectionAttempt()\n } else if (this.shouldConnect) {\n // The connection was closed by the server. Let’s just try again.\n this.connect()\n }\n\n // If we’ll reconnect, we’re done for now.\n if (this.shouldConnect) {\n return\n }\n\n // The status is set correctly already.\n if (this.status === WebSocketStatus.Disconnected) {\n return\n }\n\n // Let’s update the connection status.\n this.status = WebSocketStatus.Disconnected\n this.emit('status', { status: WebSocketStatus.Disconnected })\n this.emit('disconnect', { event })\n }\n\n destroy() {\n this.emit('destroy')\n\n if (this.intervals.forceSync) {\n clearInterval(this.intervals.forceSync)\n }\n\n clearInterval(this.intervals.connectionChecker)\n\n // If there is still a connection attempt outstanding then we should stop\n // it before calling disconnect, otherwise it will be rejected in the onClose\n // handler and trigger a retry\n this.stopConnectionAttempt()\n\n this.disconnect()\n\n this.removeAllListeners()\n\n if (typeof window === 'undefined') {\n return\n }\n\n window.removeEventListener('online', this.boundConnect)\n }\n\n}\n","import {\n createDecoder,\n readVarUint,\n readVarUint8Array,\n readVarString,\n Decoder,\n} from 'lib0/decoding'\nimport {\n Encoder,\n createEncoder,\n writeVarUint,\n writeVarUint8Array,\n writeVarString,\n length,\n} from 'lib0/encoding'\nimport { MessageType } from './types.js'\n\nexport class IncomingMessage {\n\n data: any\n\n encoder: Encoder\n\n decoder: Decoder\n\n constructor(data: any) {\n this.data = data\n this.encoder = createEncoder()\n this.decoder = createDecoder(new Uint8Array(this.data))\n }\n\n readVarUint(): MessageType {\n return readVarUint(this.decoder)\n }\n\n readVarString(): string {\n return readVarString(this.decoder)\n }\n\n readVarUint8Array() {\n return readVarUint8Array(this.decoder)\n }\n\n writeVarUint(type: MessageType) {\n return writeVarUint(this.encoder, type)\n }\n\n writeVarString(string: string) {\n return writeVarString(this.encoder, string)\n }\n\n writeVarUint8Array(data: Uint8Array) {\n return writeVarUint8Array(this.encoder, data)\n }\n\n length() {\n return length(this.encoder)\n }\n}\n","/**\n * @module sync-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as Y from 'yjs'\n\n/**\n * @typedef {Map} StateMap\n */\n\n/**\n * Core Yjs defines two message types:\n * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.\n * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it\n * received all information from the remote client.\n *\n * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection\n * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both\n * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.\n *\n * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.\n * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies\n * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the\n * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can\n * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them.\n * Therefore it is necesarry that the client initiates the sync.\n *\n * Construction of a message:\n * [messageType : varUint, message definition..]\n *\n * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!\n *\n * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)\n */\n\nexport const messageYjsSyncStep1 = 0\nexport const messageYjsSyncStep2 = 1\nexport const messageYjsUpdate = 2\n\n/**\n * Create a sync step 1 message based on the state of the current shared document.\n *\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n */\nexport const writeSyncStep1 = (encoder, doc) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep1)\n const sv = Y.encodeStateVector(doc)\n encoding.writeVarUint8Array(encoder, sv)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n * @param {Uint8Array} [encodedStateVector]\n */\nexport const writeSyncStep2 = (encoder, doc, encodedStateVector) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep2)\n encoding.writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector))\n}\n\n/**\n * Read SyncStep1 message and reply with SyncStep2.\n *\n * @param {decoding.Decoder} decoder The reply to the received message\n * @param {encoding.Encoder} encoder The received message\n * @param {Y.Doc} doc\n */\nexport const readSyncStep1 = (decoder, encoder, doc) =>\n writeSyncStep2(encoder, doc, decoding.readVarUint8Array(decoder))\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin) => {\n try {\n Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n } catch (error) {\n // This catches errors that are thrown by event handlers\n console.error('Caught error while handling a Yjs update', error)\n }\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Uint8Array} update\n */\nexport const writeUpdate = (encoder, update) => {\n encoding.writeVarUint(encoder, messageYjsUpdate)\n encoding.writeVarUint8Array(encoder, update)\n}\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readUpdate = readSyncStep2\n\n/**\n * @param {decoding.Decoder} decoder A message received from another client\n * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => {\n const messageType = decoding.readVarUint(decoder)\n switch (messageType) {\n case messageYjsSyncStep1:\n readSyncStep1(decoder, encoder, doc)\n break\n case messageYjsSyncStep2:\n readSyncStep2(decoder, doc, transactionOrigin)\n break\n case messageYjsUpdate:\n readUpdate(decoder, doc, transactionOrigin)\n break\n default:\n throw new Error('Unknown message type')\n }\n return messageType\n}\n","import { Encoder, createEncoder, toUint8Array } from 'lib0/encoding'\nimport { MessageType, OutgoingMessageArguments, OutgoingMessageInterface } from './types.js'\n\nexport class OutgoingMessage implements OutgoingMessageInterface {\n encoder: Encoder\n\n type?: MessageType\n\n constructor() {\n this.encoder = createEncoder()\n }\n\n get(args: Partial) {\n return args.encoder\n }\n\n toUint8Array() {\n return toUint8Array(this.encoder)\n }\n}\n","import { readAuthMessage } from '@hocuspocus/common'\nimport { readVarInt, readVarString } from 'lib0/decoding'\nimport * as awarenessProtocol from 'y-protocols/awareness'\nimport { messageYjsSyncStep2, readSyncMessage } from 'y-protocols/sync'\nimport { HocuspocusProvider } from './HocuspocusProvider.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { MessageType } from './types.js'\n\nexport class MessageReceiver {\n\n message: IncomingMessage\n\n broadcasted = false\n\n constructor(message: IncomingMessage) {\n this.message = message\n }\n\n public setBroadcasted(value: boolean) {\n this.broadcasted = value\n\n return this\n }\n\n public apply(provider: HocuspocusProvider, emitSynced: boolean) {\n const { message } = this\n const type = message.readVarUint()\n\n const emptyMessageLength = message.length()\n\n switch (type) {\n case MessageType.Sync:\n this.applySyncMessage(provider, emitSynced)\n break\n\n case MessageType.Awareness:\n this.applyAwarenessMessage(provider)\n break\n\n case MessageType.Auth:\n this.applyAuthMessage(provider)\n break\n\n case MessageType.QueryAwareness:\n this.applyQueryAwarenessMessage(provider)\n break\n\n case MessageType.Stateless:\n provider.receiveStateless(readVarString(message.decoder))\n break\n\n case MessageType.SyncStatus:\n this.applySyncStatusMessage(provider, readVarInt(message.decoder) === 1)\n break\n default:\n throw new Error(`Can’t apply message of unknown type: ${type}`)\n }\n\n // Reply\n if (message.length() > emptyMessageLength + 1) { // length of documentName (considered in emptyMessageLength plus length of yjs sync type, set in applySyncMessage)\n if (this.broadcasted) {\n // TODO: Some weird TypeScript error\n // @ts-ignore\n provider.broadcast(OutgoingMessage, { encoder: message.encoder })\n } else {\n // TODO: Some weird TypeScript error\n // @ts-ignore\n provider.send(OutgoingMessage, { encoder: message.encoder })\n }\n }\n }\n\n private applySyncMessage(provider: HocuspocusProvider, emitSynced: boolean) {\n const { message } = this\n\n message.writeVarUint(MessageType.Sync)\n\n // Apply update\n const syncMessageType = readSyncMessage(\n message.decoder,\n message.encoder,\n provider.document,\n provider,\n )\n\n // Synced once we receive Step2\n if (emitSynced && syncMessageType === messageYjsSyncStep2) {\n provider.synced = true\n }\n }\n\n applySyncStatusMessage(provider: HocuspocusProvider, applied: boolean) {\n if (applied) {\n provider.decrementUnsyncedChanges()\n }\n }\n\n private applyAwarenessMessage(provider: HocuspocusProvider) {\n const { message } = this\n\n awarenessProtocol.applyAwarenessUpdate(\n provider.awareness,\n message.readVarUint8Array(),\n provider,\n )\n }\n\n private applyAuthMessage(provider: HocuspocusProvider) {\n const { message } = this\n\n readAuthMessage(\n message.decoder,\n provider.permissionDeniedHandler.bind(provider),\n provider.authenticatedHandler.bind(provider),\n )\n }\n\n private applyQueryAwarenessMessage(provider: HocuspocusProvider) {\n const { message } = this\n\n message.writeVarUint(MessageType.Awareness)\n message.writeVarUint8Array(\n awarenessProtocol.encodeAwarenessUpdate(\n provider.awareness,\n Array.from(provider.awareness.getStates().keys()),\n ),\n )\n }\n}\n","import { Encoder, toUint8Array } from 'lib0/encoding'\nimport * as bc from 'lib0/broadcastchannel'\nimport { ConstructableOutgoingMessage } from './types.js'\n\nexport class MessageSender {\n\n encoder: Encoder\n\n message: any\n\n constructor(Message: ConstructableOutgoingMessage, args: any = {}) {\n this.message = new Message()\n this.encoder = this.message.get(args)\n }\n\n create() {\n return toUint8Array(this.encoder)\n }\n\n send(webSocket: any) {\n webSocket?.send(this.create())\n }\n\n broadcast(channel: string) {\n bc.publish(channel, this.create())\n }\n}\n","import { writeVarString, writeVarUint } from 'lib0/encoding'\nimport { writeAuthentication } from '@hocuspocus/common'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class AuthenticationMessage extends OutgoingMessage {\n type = MessageType.Auth\n\n description = 'Authentication'\n\n get(args: Partial) {\n if (typeof args.token === 'undefined') {\n throw new Error('The authentication message requires `token` as an argument.')\n }\n\n writeVarString(this.encoder, args.documentName!)\n writeVarUint(this.encoder, this.type)\n writeAuthentication(this.encoder, args.token)\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport { encodeAwarenessUpdate } from 'y-protocols/awareness'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class AwarenessMessage extends OutgoingMessage {\n type = MessageType.Awareness\n\n description = 'Awareness states update'\n\n get(args: Partial) {\n if (typeof args.awareness === 'undefined') {\n throw new Error('The awareness message requires awareness as an argument')\n }\n\n if (typeof args.clients === 'undefined') {\n throw new Error('The awareness message requires clients as an argument')\n }\n\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n\n let awarenessUpdate\n if (args.states === undefined) {\n awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients)\n } else {\n awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients, args.states)\n }\n\n encoding.writeVarUint8Array(this.encoder, awarenessUpdate)\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class CloseMessage extends OutgoingMessage {\n type = MessageType.CLOSE\n\n description = 'Ask the server to close the connection'\n\n get(args: Partial) {\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class QueryAwarenessMessage extends OutgoingMessage {\n type = MessageType.QueryAwareness\n\n description = 'Queries awareness states'\n\n get(args: Partial) {\n\n console.log('queryAwareness: writing string docName', args.documentName)\n console.log(this.encoder.cpos)\n\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n\n return this.encoder\n }\n}\n","import { writeVarString, writeVarUint } from 'lib0/encoding'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class StatelessMessage extends OutgoingMessage {\n type = MessageType.Stateless\n\n description = 'A stateless message'\n\n get(args: Partial) {\n writeVarString(this.encoder, args.documentName!)\n writeVarUint(this.encoder, this.type)\n writeVarString(this.encoder, args.payload ?? '')\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport * as syncProtocol from 'y-protocols/sync'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class SyncStepOneMessage extends OutgoingMessage {\n type = MessageType.Sync\n\n description = 'First sync step'\n\n get(args: Partial) {\n if (typeof args.document === 'undefined') {\n throw new Error('The sync step one message requires document as an argument')\n }\n\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n syncProtocol.writeSyncStep1(this.encoder, args.document)\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport * as syncProtocol from 'y-protocols/sync'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class SyncStepTwoMessage extends OutgoingMessage {\n type = MessageType.Sync\n\n description = 'Second sync step'\n\n get(args: Partial) {\n if (typeof args.document === 'undefined') {\n throw new Error('The sync step two message requires document as an argument')\n }\n\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n syncProtocol.writeSyncStep2(this.encoder, args.document)\n\n return this.encoder\n }\n}\n","import { writeVarString, writeVarUint } from 'lib0/encoding'\nimport { writeUpdate } from 'y-protocols/sync'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class UpdateMessage extends OutgoingMessage {\n type = MessageType.Sync\n\n description = 'A document update'\n\n get(args: Partial) {\n writeVarString(this.encoder, args.documentName!)\n writeVarUint(this.encoder, this.type)\n\n writeUpdate(this.encoder, args.update)\n\n return this.encoder\n }\n}\n","import { awarenessStatesToArray } from '@hocuspocus/common'\nimport * as bc from 'lib0/broadcastchannel'\nimport * as mutex from 'lib0/mutex'\nimport type { CloseEvent, Event, MessageEvent } from 'ws'\nimport { Awareness, removeAwarenessStates } from 'y-protocols/awareness'\nimport * as Y from 'yjs'\nimport EventEmitter from './EventEmitter.js'\nimport {\n CompleteHocuspocusProviderWebsocketConfiguration,\n HocuspocusProviderWebsocket,\n} from './HocuspocusProviderWebsocket.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { MessageReceiver } from './MessageReceiver.js'\nimport { MessageSender } from './MessageSender.js'\nimport { AuthenticationMessage } from './OutgoingMessages/AuthenticationMessage.js'\nimport { AwarenessMessage } from './OutgoingMessages/AwarenessMessage.js'\nimport { CloseMessage } from './OutgoingMessages/CloseMessage.js'\nimport { QueryAwarenessMessage } from './OutgoingMessages/QueryAwarenessMessage.js'\nimport { StatelessMessage } from './OutgoingMessages/StatelessMessage.js'\nimport { SyncStepOneMessage } from './OutgoingMessages/SyncStepOneMessage.js'\nimport { SyncStepTwoMessage } from './OutgoingMessages/SyncStepTwoMessage.js'\nimport { UpdateMessage } from './OutgoingMessages/UpdateMessage.js'\nimport {\n ConstructableOutgoingMessage,\n WebSocketStatus,\n onAuthenticationFailedParameters,\n onAwarenessChangeParameters,\n onAwarenessUpdateParameters,\n onCloseParameters,\n onDisconnectParameters,\n onMessageParameters,\n onOpenParameters,\n onOutgoingMessageParameters, onStatelessParameters,\n onStatusParameters,\n onSyncedParameters,\n} from './types.js'\n\nexport type HocuspocusProviderConfiguration =\n Required>\n & Partial & (\n Required> |\n Required>\n )\n\nexport interface CompleteHocuspocusProviderConfiguration {\n /**\n * The identifier/name of your document\n */\n name: string,\n /**\n * The actual Y.js document\n */\n document: Y.Doc,\n\n /**\n * Pass false to disable broadcasting between browser tabs.\n */\n broadcast: boolean,\n /**\n * An Awareness instance to keep the presence state of all clients.\n */\n awareness: Awareness,\n /**\n * A token that’s sent to the backend for authentication purposes.\n */\n token: string | (() => string) | (() => Promise) | null,\n /**\n * URL parameters that should be added.\n */\n parameters: { [key: string]: any },\n /**\n * Hocuspocus websocket provider\n */\n websocketProvider: HocuspocusProviderWebsocket,\n /**\n * Force syncing the document in the defined interval.\n */\n forceSyncInterval: false | number,\n\n onAuthenticated: () => void,\n onAuthenticationFailed: (data: onAuthenticationFailedParameters) => void,\n onOpen: (data: onOpenParameters) => void,\n onConnect: () => void,\n onMessage: (data: onMessageParameters) => void,\n onOutgoingMessage: (data: onOutgoingMessageParameters) => void,\n onStatus: (data: onStatusParameters) => void,\n onSynced: (data: onSyncedParameters) => void,\n onDisconnect: (data: onDisconnectParameters) => void,\n onClose: (data: onCloseParameters) => void,\n onDestroy: () => void,\n onAwarenessUpdate: (data: onAwarenessUpdateParameters) => void,\n onAwarenessChange: (data: onAwarenessChangeParameters) => void,\n onStateless: (data: onStatelessParameters) => void\n\n /**\n * Don’t output any warnings.\n */\n quiet: boolean,\n}\n\nexport class HocuspocusProvider extends EventEmitter {\n public configuration: CompleteHocuspocusProviderConfiguration = {\n name: '',\n // @ts-ignore\n document: undefined,\n // @ts-ignore\n awareness: undefined,\n token: null,\n parameters: {},\n broadcast: true,\n forceSyncInterval: false,\n onAuthenticated: () => null,\n onAuthenticationFailed: () => null,\n onOpen: () => null,\n onConnect: () => null,\n onMessage: () => null,\n onOutgoingMessage: () => null,\n onStatus: () => null,\n onSynced: () => null,\n onDisconnect: () => null,\n onClose: () => null,\n onDestroy: () => null,\n onAwarenessUpdate: () => null,\n onAwarenessChange: () => null,\n onStateless: () => null,\n quiet: false,\n }\n\n subscribedToBroadcastChannel = false\n\n isSynced = false\n\n unsyncedChanges = 0\n\n status = WebSocketStatus.Disconnected\n\n isAuthenticated = false\n\n authorizedScope: string | undefined = undefined\n\n mux = mutex.createMutex()\n\n intervals: any = {\n forceSync: null,\n }\n\n isConnected = true\n\n constructor(configuration: HocuspocusProviderConfiguration) {\n super()\n this.setConfiguration(configuration)\n\n this.configuration.document = configuration.document ? configuration.document : new Y.Doc()\n this.configuration.awareness = configuration.awareness ? configuration.awareness : new Awareness(this.document)\n\n this.on('open', this.configuration.onOpen)\n this.on('message', this.configuration.onMessage)\n this.on('outgoingMessage', this.configuration.onOutgoingMessage)\n this.on('synced', this.configuration.onSynced)\n this.on('destroy', this.configuration.onDestroy)\n this.on('awarenessUpdate', this.configuration.onAwarenessUpdate)\n this.on('awarenessChange', this.configuration.onAwarenessChange)\n this.on('stateless', this.configuration.onStateless)\n\n this.on('authenticated', this.configuration.onAuthenticated)\n this.on('authenticationFailed', this.configuration.onAuthenticationFailed)\n\n this.configuration.websocketProvider.on('connect', this.configuration.onConnect)\n this.configuration.websocketProvider.on('connect', (e: Event) => this.emit('connect', e))\n\n this.configuration.websocketProvider.on('open', this.onOpen.bind(this))\n this.configuration.websocketProvider.on('open', (e: Event) => this.emit('open', e))\n\n this.configuration.websocketProvider.on('message', this.onMessage.bind(this))\n\n this.configuration.websocketProvider.on('close', this.onClose.bind(this))\n this.configuration.websocketProvider.on('close', this.configuration.onClose)\n this.configuration.websocketProvider.on('close', (e: Event) => this.emit('close', e))\n\n this.configuration.websocketProvider.on('status', this.onStatus.bind(this))\n\n this.configuration.websocketProvider.on('disconnect', this.configuration.onDisconnect)\n this.configuration.websocketProvider.on('disconnect', (e: Event) => this.emit('disconnect', e))\n\n this.configuration.websocketProvider.on('destroy', this.configuration.onDestroy)\n this.configuration.websocketProvider.on('destroy', (e: Event) => this.emit('destroy', e))\n\n this.awareness.on('update', () => {\n this.emit('awarenessUpdate', { states: awarenessStatesToArray(this.awareness.getStates()) })\n })\n\n this.awareness.on('change', () => {\n this.emit('awarenessChange', { states: awarenessStatesToArray(this.awareness.getStates()) })\n })\n\n this.document.on('update', this.documentUpdateHandler.bind(this))\n this.awareness.on('update', this.awarenessUpdateHandler.bind(this))\n this.registerEventListeners()\n\n if (this.configuration.forceSyncInterval) {\n this.intervals.forceSync = setInterval(\n this.forceSync.bind(this),\n this.configuration.forceSyncInterval,\n )\n }\n\n this.configuration.websocketProvider.attach(this)\n }\n\n public onStatus({ status } : onStatusParameters) {\n this.status = status\n\n this.configuration.onStatus({ status })\n this.emit('status', { status })\n }\n\n public setConfiguration(configuration: Partial = {}): void {\n if (!configuration.websocketProvider && (configuration as CompleteHocuspocusProviderWebsocketConfiguration).url) {\n const websocketProviderConfig = configuration as CompleteHocuspocusProviderWebsocketConfiguration\n\n this.configuration.websocketProvider = new HocuspocusProviderWebsocket({\n url: websocketProviderConfig.url,\n parameters: websocketProviderConfig.parameters,\n })\n }\n\n this.configuration = { ...this.configuration, ...configuration }\n }\n\n get document() {\n return this.configuration.document\n }\n\n get awareness() {\n return this.configuration.awareness\n }\n\n get hasUnsyncedChanges(): boolean {\n return this.unsyncedChanges > 0\n }\n\n incrementUnsyncedChanges() {\n this.unsyncedChanges += 1\n this.emit('unsyncedChanges', this.unsyncedChanges)\n }\n\n decrementUnsyncedChanges() {\n this.unsyncedChanges -= 1\n if (this.unsyncedChanges === 0) {\n this.synced = true\n }\n this.emit('unsyncedChanges', this.unsyncedChanges)\n }\n\n forceSync() {\n this.send(SyncStepOneMessage, { document: this.document, documentName: this.configuration.name })\n }\n\n boundBeforeUnload = this.beforeUnload.bind(this)\n\n beforeUnload() {\n removeAwarenessStates(this.awareness, [this.document.clientID], 'window unload')\n }\n\n registerEventListeners() {\n if (typeof window === 'undefined') {\n return\n }\n\n window.addEventListener('beforeunload', this.boundBeforeUnload)\n }\n\n sendStateless(payload: string) {\n this.send(StatelessMessage, { documentName: this.configuration.name, payload })\n }\n\n documentUpdateHandler(update: Uint8Array, origin: any) {\n if (origin === this) {\n return\n }\n\n this.incrementUnsyncedChanges()\n this.send(UpdateMessage, { update, documentName: this.configuration.name }, true)\n }\n\n awarenessUpdateHandler({ added, updated, removed }: any, origin: any) {\n const changedClients = added.concat(updated).concat(removed)\n\n this.send(AwarenessMessage, {\n awareness: this.awareness,\n clients: changedClients,\n documentName: this.configuration.name,\n }, true)\n }\n\n get synced(): boolean {\n return this.isSynced\n }\n\n set synced(state) {\n if (this.isSynced === state) {\n return\n }\n\n this.isSynced = state\n this.emit('synced', { state })\n this.emit('sync', { state })\n }\n\n receiveStateless(payload: string) {\n this.emit('stateless', { payload })\n }\n\n get isAuthenticationRequired(): boolean {\n return !!this.configuration.token && !this.isAuthenticated\n }\n\n // not needed, but provides backward compatibility with e.g. lexicla/yjs\n async connect() {\n return this.configuration.websocketProvider.connect()\n }\n\n disconnect() {\n this.disconnectBroadcastChannel()\n this.configuration.websocketProvider.detach(this)\n }\n\n async onOpen(event: Event) {\n this.isAuthenticated = false\n\n this.emit('open', { event })\n\n if (this.isAuthenticationRequired) {\n this.send(AuthenticationMessage, {\n token: await this.getToken(),\n documentName: this.configuration.name,\n })\n }\n\n this.startSync()\n }\n\n async getToken() {\n if (typeof this.configuration.token === 'function') {\n const token = await this.configuration.token()\n return token\n }\n\n return this.configuration.token\n }\n\n startSync() {\n this.incrementUnsyncedChanges()\n this.send(SyncStepOneMessage, { document: this.document, documentName: this.configuration.name })\n\n if (this.awareness.getLocalState() !== null) {\n this.send(AwarenessMessage, {\n awareness: this.awareness,\n clients: [this.document.clientID],\n documentName: this.configuration.name,\n })\n }\n }\n\n send(message: ConstructableOutgoingMessage, args: any, broadcast = false) {\n if (!this.isConnected) {\n return\n }\n\n if (broadcast) {\n this.mux(() => { this.broadcast(message, args) })\n }\n\n const messageSender = new MessageSender(message, args)\n\n this.emit('outgoingMessage', { message: messageSender.message })\n messageSender.send(this.configuration.websocketProvider)\n }\n\n onMessage(event: MessageEvent) {\n const message = new IncomingMessage(event.data)\n\n const documentName = message.readVarString()\n\n if (documentName !== this.configuration.name) {\n return // message is meant for another provider\n }\n\n message.writeVarString(documentName)\n\n this.emit('message', { event, message: new IncomingMessage(event.data) })\n\n new MessageReceiver(message).apply(this, true)\n }\n\n onClose(event: CloseEvent) {\n this.isAuthenticated = false\n this.synced = false\n\n // update awareness (all users except local left)\n removeAwarenessStates(\n this.awareness,\n Array.from(this.awareness.getStates().keys()).filter(client => client !== this.document.clientID),\n this,\n )\n }\n\n destroy() {\n this.emit('destroy')\n\n if (this.intervals.forceSync) {\n clearInterval(this.intervals.forceSync)\n }\n\n removeAwarenessStates(this.awareness, [this.document.clientID], 'provider destroy')\n\n this.disconnect()\n\n this.awareness.off('update', this.awarenessUpdateHandler)\n this.document.off('update', this.documentUpdateHandler)\n\n this.removeAllListeners()\n\n this.send(CloseMessage, { documentName: this.configuration.name })\n this.isConnected = false\n\n if (typeof window === 'undefined') {\n return\n }\n\n window.removeEventListener('beforeunload', this.boundBeforeUnload)\n }\n\n permissionDeniedHandler(reason: string) {\n this.emit('authenticationFailed', { reason })\n this.isAuthenticated = false\n this.disconnect()\n this.status = WebSocketStatus.Disconnected\n }\n\n authenticatedHandler(scope: string) {\n this.isAuthenticated = true\n this.authorizedScope = scope\n\n this.emit('authenticated')\n this.startSync()\n }\n\n get broadcastChannel() {\n return `${this.configuration.name}`\n }\n\n boundBroadcastChannelSubscriber = this.broadcastChannelSubscriber.bind(this)\n\n broadcastChannelSubscriber(data: ArrayBuffer) {\n this.mux(() => {\n const message = new IncomingMessage(data)\n\n const documentName = message.readVarString()\n\n message.writeVarString(documentName)\n\n new MessageReceiver(message)\n .setBroadcasted(true)\n .apply(this, false)\n })\n }\n\n subscribeToBroadcastChannel() {\n if (!this.subscribedToBroadcastChannel) {\n bc.subscribe(this.broadcastChannel, this.boundBroadcastChannelSubscriber)\n this.subscribedToBroadcastChannel = true\n }\n\n this.mux(() => {\n this.broadcast(SyncStepOneMessage, { document: this.document })\n this.broadcast(SyncStepTwoMessage, { document: this.document })\n this.broadcast(QueryAwarenessMessage, { document: this.document })\n this.broadcast(AwarenessMessage, { awareness: this.awareness, clients: [this.document.clientID], document: this.document })\n })\n }\n\n disconnectBroadcastChannel() {\n // broadcast message with local awareness state set to null (indicating disconnect)\n this.send(AwarenessMessage, {\n awareness: this.awareness,\n clients: [this.document.clientID],\n states: new Map(),\n documentName: this.configuration.name,\n }, true)\n\n if (this.subscribedToBroadcastChannel) {\n bc.unsubscribe(this.broadcastChannel, this.boundBroadcastChannelSubscriber)\n this.subscribedToBroadcastChannel = false\n }\n }\n\n broadcast(Message: ConstructableOutgoingMessage, args?: any) {\n if (!this.configuration.broadcast) {\n return\n }\n\n if (!this.subscribedToBroadcastChannel) {\n return\n }\n\n new MessageSender(Message, args).broadcast(this.broadcastChannel)\n }\n\n setAwarenessField(key: string, value: any) {\n this.awareness.setLocalStateField(key, value)\n }\n}\n","import {\n CompleteHocuspocusProviderWebsocketConfiguration,\n HocuspocusProviderWebsocket, HocuspocusProviderWebsocketConfiguration,\n} from './HocuspocusProviderWebsocket.js'\n\nexport type TiptapCollabProviderWebsocketConfiguration =\n Partial &\n AdditionalTiptapCollabProviderWebsocketConfiguration\n\nexport interface AdditionalTiptapCollabProviderWebsocketConfiguration {\n /**\n * A Hocuspocus Cloud App ID, get one here: https://collab.tiptap.dev\n */\n appId: string,\n}\n\nexport class TiptapCollabProviderWebsocket extends HocuspocusProviderWebsocket {\n constructor(configuration: TiptapCollabProviderWebsocketConfiguration) {\n super({ ...configuration as HocuspocusProviderWebsocketConfiguration, url: `wss://${configuration.appId}.collab.tiptap.cloud` })\n }\n}\n","import {\n HocuspocusProvider,\n HocuspocusProviderConfiguration,\n} from './HocuspocusProvider.js'\n\nimport { TiptapCollabProviderWebsocket } from './TiptapCollabProviderWebsocket.js'\n\nexport type TiptapCollabProviderConfiguration =\n Required> &\n Partial &\n AdditionalTiptapCollabProviderConfiguration\n\nexport interface AdditionalTiptapCollabProviderConfiguration {\n /**\n * A Hocuspocus Cloud App ID, get one here: https://collab.tiptap.dev\n */\n appId: string,\n}\n\nexport class TiptapCollabProvider extends HocuspocusProvider {\n constructor(configuration: TiptapCollabProviderConfiguration) {\n if (!configuration.websocketProvider) {\n configuration.websocketProvider = new TiptapCollabProviderWebsocket({ appId: configuration.appId })\n }\n\n if (!configuration.token) {\n configuration.token = 'notoken' // need to send a token anyway (which will be ignored)\n }\n\n super(configuration as HocuspocusProviderConfiguration)\n }\n}\n"],"names":["create","length","object.length","object.hasProperty","map.create","string.fromCamelCase","conditions.undefinedToNull","storage.varStorage","f.isOneOf","buffer.createUint8ArrayViewFromArrayBuffer","binary.BITS7","binary.BIT8","math.floor","string.utf8TextEncoder","string.encodeUtf8","math.min","math.max","error.create","number.MAX_SAFE_INTEGER","binary.BITS6","binary.BIT7","string.utf8TextDecoder","string.fromCharCode","env.isBrowser","buffer.fromBase64","storage.onChange","buffer.toBase64","buffer.createUint8ArrayFromArrayBuffer","storage.offChange","map.setIfUndefined","set.create","array.from","time.getUnixTime","f.equalityDeep","encoding.createEncoder","encoding.writeVarUint","encoding.writeVarString","encoding.toUint8Array","decoding.createDecoder","decoding.readVarUint","decoding.readVarString","object.map","MessageType","WebSocketStatus","mutex.createMutex","retry","url.encodeQueryParams","WsReadyStates","Unauthorized","Forbidden","MessageTooBig","Y","encoding.writeVarUint8Array","decoding.readVarUint8Array","awarenessProtocol.applyAwarenessUpdate","readAuthMessage","awarenessProtocol.encodeAwarenessUpdate","bc.publish","writeAuthentication","syncProtocol.writeSyncStep1","syncProtocol.writeSyncStep2","awarenessStatesToArray","bc.subscribe","bc.unsubscribe"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;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C,IAAI,CAAC,gBAAgB,CAAC,CAAA;KAClE;IAED,iBAAiB,CAAC,GAAW,EAAE,KAAU,EAAA;QACvC,IAAI,CAAC,SAAS,CAAC,kBAAkB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;KAC9C;AACF;;AChfK,MAAO,6BAA8B,SAAQ,2BAA2B,CAAA;AAC5E,IAAA,WAAA,CAAY,aAAyD,EAAA;AACnE,QAAA,KAAK,CAAC,EAAE,GAAG,aAAyD,EAAE,GAAG,EAAE,CAAS,MAAA,EAAA,aAAa,CAAC,KAAK,CAAsB,oBAAA,CAAA,EAAE,CAAC,CAAA;KACjI;AACF;;ACDK,MAAO,oBAAqB,SAAQ,kBAAkB,CAAA;AAC1D,IAAA,WAAA,CAAY,aAAgD,EAAA;AAC1D,QAAA,IAAI,CAAC,aAAa,CAAC,iBAAiB,EAAE;AACpC,YAAA,aAAa,CAAC,iBAAiB,GAAG,IAAI,6BAA6B,CAAC,EAAE,KAAK,EAAE,aAAa,CAAC,KAAK,EAAE,CAAC,CAAA;AACpG,SAAA;AAED,QAAA,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE;AACxB,YAAA,aAAa,CAAC,KAAK,GAAG,SAAS,CAAA;AAChC,SAAA;QAED,KAAK,CAAC,aAAgD,CAAC,CAAA;KACxD;AACF;;;;;;;"} -\ No newline at end of file -diff --git a/node_modules/@hocuspocus/provider/dist/hocuspocus-provider.esm.js b/node_modules/@hocuspocus/provider/dist/hocuspocus-provider.esm.js -index e0b6d8d..0e4dfc7 100644 ---- a/node_modules/@hocuspocus/provider/dist/hocuspocus-provider.esm.js -+++ b/node_modules/@hocuspocus/provider/dist/hocuspocus-provider.esm.js -@@ -1,5 +1,5 @@ -+import { WsReadyStates, Unauthorized, Forbidden, MessageTooBig, readAuthMessage, writeAuthentication, awarenessStatesToArray } from '@hocuspocus/common'; - import * as Y from 'yjs'; --import { readAuthMessage, writeAuthentication, WsReadyStates, Unauthorized, Forbidden, MessageTooBig, awarenessStatesToArray } from '@hocuspocus/common'; - import { retry } from '@lifeomic/attempt'; - - /** -@@ -50,6 +50,22 @@ const setIfUndefined = (map, key, createT) => { - - const create$1 = () => new Set(); - -+/** -+ * Utility module to work with Arrays. -+ * -+ * @module array -+ */ -+ -+/** -+ * Transforms something array-like to an actual Array. -+ * -+ * @function -+ * @template T -+ * @param {ArrayLike|Iterable} arraylike -+ * @return {T} -+ */ -+const from = Array.from; -+ - /** - * Utility module to work with strings. - * -@@ -212,22 +228,6 @@ const onChange = eventHandler => usePolyfill || addEventListener('storage', /** - /* c8 ignore next */ - const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler)); - --/** -- * Utility module to work with Arrays. -- * -- * @module array -- */ -- --/** -- * Transforms something array-like to an actual Array. -- * -- * @function -- * @template T -- * @param {ArrayLike|Iterable} arraylike -- * @return {T} -- */ --const from = Array.from; -- - /** - * Utility functions for working with EcmaScript objects. - * -@@ -375,7 +375,6 @@ const equalityDeep = (a, b) => { - */ - // @ts-ignore - const isOneOf = (value, options) => options.includes(value); --/* c8 ignore stop */ - - /** - * Isomorphic module to work access the environment (query params, env variables). -@@ -507,7 +506,9 @@ const min = (a, b) => a < b ? a : b; - const max = (a, b) => a > b ? a : b; - - /* eslint-env browser */ -+const BIT7 = 64; - const BIT8 = 128; -+const BITS6 = 63; - const BITS7 = 127; - - /** -@@ -865,6 +866,44 @@ const readVarUint = decoder => { - throw errorUnexpectedEndOfArray - }; - -+/** -+ * Read signed integer (32bit) with variable length. -+ * 1/8th of the storage is used as encoding overhead. -+ * * numbers < 2^7 is stored in one bytlength -+ * * numbers < 2^14 is stored in two bylength -+ * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change. -+ * -+ * @function -+ * @param {Decoder} decoder -+ * @return {number} An unsigned integer.length -+ */ -+const readVarInt = decoder => { -+ let r = decoder.arr[decoder.pos++]; -+ let num = r & BITS6; -+ let mult = 64; -+ const sign = (r & BIT7) > 0 ? -1 : 1; -+ if ((r & BIT8) === 0) { -+ // don't continue reading -+ return sign * num -+ } -+ const len = decoder.arr.length; -+ while (decoder.pos < len) { -+ r = decoder.arr[decoder.pos++]; -+ // num = num | ((r & binary.BITS7) << len) -+ num = num + (r & BITS7) * mult; -+ mult *= 128; -+ if (r < BIT8) { -+ return sign * num -+ } -+ /* c8 ignore start */ -+ if (num > MAX_SAFE_INTEGER) { -+ throw errorIntegerOutOfRange -+ } -+ /* c8 ignore stop */ -+ } -+ throw errorUnexpectedEndOfArray -+}; -+ - /** - * We don't test this function anymore as we use native decoding/encoding by default now. - * Better not modify this anymore.. -@@ -1112,6 +1151,50 @@ const publish = (room, data, origin = null) => { - c.subs.forEach(sub => sub(data, origin)); - }; - -+/** -+ * Mutual exclude for JavaScript. -+ * -+ * @module mutex -+ */ -+ -+/** -+ * @callback mutex -+ * @param {function():void} cb Only executed when this mutex is not in the current stack -+ * @param {function():void} [elseCb] Executed when this mutex is in the current stack -+ */ -+ -+/** -+ * Creates a mutual exclude function with the following property: -+ * -+ * ```js -+ * const mutex = createMutex() -+ * mutex(() => { -+ * // This function is immediately executed -+ * mutex(() => { -+ * // This function is not executed, as the mutex is already active. -+ * }) -+ * }) -+ * ``` -+ * -+ * @return {mutex} A mutual exclude function -+ * @public -+ */ -+const createMutex = () => { -+ let token = true; -+ return (f, g) => { -+ if (token) { -+ token = false; -+ try { -+ f(); -+ } finally { -+ token = true; -+ } -+ } else if (g !== undefined) { -+ g(); -+ } -+ } -+}; -+ - /** - * Utility module to work with time. - * -@@ -1462,50 +1545,6 @@ const applyAwarenessUpdate = (awareness, update, origin) => { - } - }; - --/** -- * Mutual exclude for JavaScript. -- * -- * @module mutex -- */ -- --/** -- * @callback mutex -- * @param {function():void} cb Only executed when this mutex is not in the current stack -- * @param {function():void} [elseCb] Executed when this mutex is in the current stack -- */ -- --/** -- * Creates a mutual exclude function with the following property: -- * -- * ```js -- * const mutex = createMutex() -- * mutex(() => { -- * // This function is immediately executed -- * mutex(() => { -- * // This function is not executed, as the mutex is already active. -- * }) -- * }) -- * ``` -- * -- * @return {mutex} A mutual exclude function -- * @public -- */ --const createMutex = () => { -- let token = true; -- return (f, g) => { -- if (token) { -- token = false; -- try { -- f(); -- } finally { -- token = true; -- } -- } else if (g !== undefined) { -- g(); -- } -- } --}; -- - class EventEmitter { - constructor() { - this.callbacks = {}; -@@ -1541,712 +1580,690 @@ class EventEmitter { - } - } - --class IncomingMessage { -- constructor(data) { -- this.data = data; -- this.encoder = createEncoder(); -- this.decoder = createDecoder(new Uint8Array(this.data)); -- } -- readVarUint() { -- return readVarUint(this.decoder); -- } -- readVarString() { -- return readVarString(this.decoder); -- } -- readVarUint8Array() { -- return readVarUint8Array(this.decoder); -- } -- writeVarUint(type) { -- return writeVarUint(this.encoder, type); -- } -- writeVarString(string) { -- return writeVarString(this.encoder, string); -- } -- writeVarUint8Array(data) { -- return writeVarUint8Array(this.encoder, data); -- } -- length() { -- return length(this.encoder); -- } --} -- --/** -- * @module sync-protocol -- */ -- --/** -- * @typedef {Map} StateMap -- */ -- --/** -- * Core Yjs defines two message types: -- * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2. -- * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it -- * received all information from the remote client. -- * -- * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection -- * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both -- * SyncStep2 and SyncDone, it is assured that it is synced to the remote client. -- * -- * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1. -- * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies -- * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the -- * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can -- * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them. -- * Therefore it is necesarry that the client initiates the sync. -- * -- * Construction of a message: -- * [messageType : varUint, message definition..] -- * -- * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol! -- * -- * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer) -- */ -- --const messageYjsSyncStep1 = 0; --const messageYjsSyncStep2 = 1; --const messageYjsUpdate = 2; -- - /** -- * Create a sync step 1 message based on the state of the current shared document. -+ * Utility module to work with urls. - * -- * @param {encoding.Encoder} encoder -- * @param {Y.Doc} doc -+ * @module url - */ --const writeSyncStep1 = (encoder, doc) => { -- writeVarUint(encoder, messageYjsSyncStep1); -- const sv = Y.encodeStateVector(doc); -- writeVarUint8Array(encoder, sv); --}; - - /** -- * @param {encoding.Encoder} encoder -- * @param {Y.Doc} doc -- * @param {Uint8Array} [encodedStateVector] -+ * @param {Object} params -+ * @return {string} - */ --const writeSyncStep2 = (encoder, doc, encodedStateVector) => { -- writeVarUint(encoder, messageYjsSyncStep2); -- writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector)); --}; -+const encodeQueryParams = params => -+ map(params, (val, key) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&'); - --/** -- * Read SyncStep1 message and reply with SyncStep2. -- * -- * @param {decoding.Decoder} decoder The reply to the received message -- * @param {encoding.Encoder} encoder The received message -- * @param {Y.Doc} doc -- */ --const readSyncStep1 = (decoder, encoder, doc) => -- writeSyncStep2(encoder, doc, readVarUint8Array(decoder)); -+var MessageType; -+(function (MessageType) { -+ MessageType[MessageType["Sync"] = 0] = "Sync"; -+ MessageType[MessageType["Awareness"] = 1] = "Awareness"; -+ MessageType[MessageType["Auth"] = 2] = "Auth"; -+ MessageType[MessageType["QueryAwareness"] = 3] = "QueryAwareness"; -+ MessageType[MessageType["Stateless"] = 5] = "Stateless"; -+ MessageType[MessageType["CLOSE"] = 7] = "CLOSE"; -+ MessageType[MessageType["SyncStatus"] = 8] = "SyncStatus"; -+})(MessageType || (MessageType = {})); -+var WebSocketStatus; -+(function (WebSocketStatus) { -+ WebSocketStatus["Connecting"] = "connecting"; -+ WebSocketStatus["Connected"] = "connected"; -+ WebSocketStatus["Disconnected"] = "disconnected"; -+})(WebSocketStatus || (WebSocketStatus = {})); - --/** -- * Read and apply Structs and then DeleteStore to a y instance. -- * -- * @param {decoding.Decoder} decoder -- * @param {Y.Doc} doc -- * @param {any} transactionOrigin -- */ --const readSyncStep2 = (decoder, doc, transactionOrigin) => { -- try { -- Y.applyUpdate(doc, readVarUint8Array(decoder), transactionOrigin); -- } catch (error) { -- // This catches errors that are thrown by event handlers -- console.error('Caught error while handling a Yjs update', error); -- } --}; -- --/** -- * @param {encoding.Encoder} encoder -- * @param {Uint8Array} update -- */ --const writeUpdate = (encoder, update) => { -- writeVarUint(encoder, messageYjsUpdate); -- writeVarUint8Array(encoder, update); --}; -- --/** -- * Read and apply Structs and then DeleteStore to a y instance. -- * -- * @param {decoding.Decoder} decoder -- * @param {Y.Doc} doc -- * @param {any} transactionOrigin -- */ --const readUpdate = readSyncStep2; -- --/** -- * @param {decoding.Decoder} decoder A message received from another client -- * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty. -- * @param {Y.Doc} doc -- * @param {any} transactionOrigin -- */ --const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => { -- const messageType = readVarUint(decoder); -- switch (messageType) { -- case messageYjsSyncStep1: -- readSyncStep1(decoder, encoder, doc); -- break -- case messageYjsSyncStep2: -- readSyncStep2(decoder, doc, transactionOrigin); -- break -- case messageYjsUpdate: -- readUpdate(decoder, doc, transactionOrigin); -- break -- default: -- throw new Error('Unknown message type') -- } -- return messageType --}; -- --var MessageType; --(function (MessageType) { -- MessageType[MessageType["Sync"] = 0] = "Sync"; -- MessageType[MessageType["Awareness"] = 1] = "Awareness"; -- MessageType[MessageType["Auth"] = 2] = "Auth"; -- MessageType[MessageType["QueryAwareness"] = 3] = "QueryAwareness"; -- MessageType[MessageType["Stateless"] = 5] = "Stateless"; -- MessageType[MessageType["CLOSE"] = 7] = "CLOSE"; --})(MessageType || (MessageType = {})); --var WebSocketStatus; --(function (WebSocketStatus) { -- WebSocketStatus["Connecting"] = "connecting"; -- WebSocketStatus["Connected"] = "connected"; -- WebSocketStatus["Disconnected"] = "disconnected"; --})(WebSocketStatus || (WebSocketStatus = {})); -- --class OutgoingMessage { -- constructor() { -- this.encoder = createEncoder(); -+class HocuspocusProviderWebsocket extends EventEmitter { -+ constructor(configuration) { -+ super(); -+ this.messageQueue = []; -+ this.configuration = { -+ url: '', -+ // @ts-ignore -+ document: undefined, -+ // @ts-ignore -+ awareness: undefined, -+ WebSocketPolyfill: undefined, -+ parameters: {}, -+ connect: true, -+ broadcast: true, -+ forceSyncInterval: false, -+ // TODO: this should depend on awareness.outdatedTime -+ messageReconnectTimeout: 30000, -+ // 1 second -+ delay: 1000, -+ // instant -+ initialDelay: 0, -+ // double the delay each time -+ factor: 2, -+ // unlimited retries -+ maxAttempts: 0, -+ // wait at least 1 second -+ minDelay: 1000, -+ // at least every 30 seconds -+ maxDelay: 30000, -+ // randomize -+ jitter: true, -+ // retry forever -+ timeout: 0, -+ onOpen: () => null, -+ onConnect: () => null, -+ onMessage: () => null, -+ onOutgoingMessage: () => null, -+ onStatus: () => null, -+ onDisconnect: () => null, -+ onClose: () => null, -+ onDestroy: () => null, -+ onAwarenessUpdate: () => null, -+ onAwarenessChange: () => null, -+ quiet: false, -+ }; -+ this.subscribedToBroadcastChannel = false; -+ this.webSocket = null; -+ this.shouldConnect = true; -+ this.status = WebSocketStatus.Disconnected; -+ this.lastMessageReceived = 0; -+ this.mux = createMutex(); -+ this.intervals = { -+ forceSync: null, -+ connectionChecker: null, -+ }; -+ this.connectionAttempt = null; -+ this.receivedOnOpenPayload = undefined; -+ this.receivedOnStatusPayload = undefined; -+ this.boundConnect = this.connect.bind(this); -+ this.setConfiguration(configuration); -+ this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill ? configuration.WebSocketPolyfill : WebSocket; -+ this.on('open', this.configuration.onOpen); -+ this.on('open', this.onOpen.bind(this)); -+ this.on('connect', this.configuration.onConnect); -+ this.on('message', this.configuration.onMessage); -+ this.on('outgoingMessage', this.configuration.onOutgoingMessage); -+ this.on('status', this.configuration.onStatus); -+ this.on('status', this.onStatus.bind(this)); -+ this.on('disconnect', this.configuration.onDisconnect); -+ this.on('close', this.configuration.onClose); -+ this.on('destroy', this.configuration.onDestroy); -+ this.on('awarenessUpdate', this.configuration.onAwarenessUpdate); -+ this.on('awarenessChange', this.configuration.onAwarenessChange); -+ this.on('close', this.onClose.bind(this)); -+ this.on('message', this.onMessage.bind(this)); -+ this.registerEventListeners(); -+ this.intervals.connectionChecker = setInterval(this.checkConnection.bind(this), this.configuration.messageReconnectTimeout / 10); -+ if (typeof configuration.connect !== 'undefined') { -+ this.shouldConnect = configuration.connect; -+ } -+ if (!this.shouldConnect) { -+ return; -+ } -+ this.connect(); - } -- get(args) { -- return args.encoder; -+ async onOpen(event) { -+ this.receivedOnOpenPayload = event; - } -- toUint8Array() { -- return toUint8Array(this.encoder); -+ async onStatus(data) { -+ this.receivedOnStatusPayload = data; - } --} -- --class MessageReceiver { -- constructor(message) { -- this.broadcasted = false; -- this.message = message; -+ attach(provider) { -+ if (this.receivedOnOpenPayload) { -+ provider.onOpen(this.receivedOnOpenPayload); -+ } -+ if (this.receivedOnStatusPayload) { -+ provider.onStatus(this.receivedOnStatusPayload); -+ } - } -- setBroadcasted(value) { -- this.broadcasted = value; -- return this; -+ detach(provider) { -+ // tell the server to remove the listener - } -- apply(provider, emitSynced = true) { -- const { message } = this; -- const type = message.readVarUint(); -- const emptyMessageLength = message.length(); -- switch (type) { -- case MessageType.Sync: -- this.applySyncMessage(provider, emitSynced); -- break; -- case MessageType.Awareness: -- this.applyAwarenessMessage(provider); -- break; -- case MessageType.Auth: -- this.applyAuthMessage(provider); -- break; -- case MessageType.QueryAwareness: -- this.applyQueryAwarenessMessage(provider); -- break; -- case MessageType.Stateless: -- provider.receiveStateless(readVarString(message.decoder)); -- break; -- default: -- throw new Error(`Can’t apply message of unknown type: ${type}`); -+ setConfiguration(configuration = {}) { -+ this.configuration = { ...this.configuration, ...configuration }; -+ } -+ async connect() { -+ if (this.status === WebSocketStatus.Connected) { -+ return; - } -- // Reply -- if (message.length() > emptyMessageLength + 1) { // length of documentName (considered in emptyMessageLength plus length of yjs sync type, set in applySyncMessage) -- if (this.broadcasted) { -- // TODO: Some weird TypeScript error -- // @ts-ignore -- provider.broadcast(OutgoingMessage, { encoder: message.encoder }); -+ // Always cancel any previously initiated connection retryer instances -+ if (this.cancelWebsocketRetry) { -+ this.cancelWebsocketRetry(); -+ this.cancelWebsocketRetry = undefined; -+ } -+ this.shouldConnect = true; -+ const abortableRetry = () => { -+ let cancelAttempt = false; -+ const retryPromise = retry(this.createWebSocketConnection.bind(this), { -+ delay: this.configuration.delay, -+ initialDelay: this.configuration.initialDelay, -+ factor: this.configuration.factor, -+ maxAttempts: this.configuration.maxAttempts, -+ minDelay: this.configuration.minDelay, -+ maxDelay: this.configuration.maxDelay, -+ jitter: this.configuration.jitter, -+ timeout: this.configuration.timeout, -+ beforeAttempt: context => { -+ if (!this.shouldConnect || cancelAttempt) { -+ context.abort(); -+ } -+ }, -+ }).catch((error) => { -+ // If we aborted the connection attempt then don’t throw an error -+ // ref: https://github.com/lifeomic/attempt/blob/master/src/index.ts#L136 -+ if (error && error.code !== 'ATTEMPT_ABORTED') { -+ throw error; -+ } -+ }); -+ return { -+ retryPromise, -+ cancelFunc: () => { -+ cancelAttempt = true; -+ }, -+ }; -+ }; -+ const { retryPromise, cancelFunc } = abortableRetry(); -+ this.cancelWebsocketRetry = cancelFunc; -+ return retryPromise; -+ } -+ createWebSocketConnection() { -+ return new Promise((resolve, reject) => { -+ if (this.webSocket) { -+ this.messageQueue = []; -+ this.webSocket.close(); -+ this.webSocket = null; -+ } -+ // Init the WebSocket connection -+ const ws = new this.configuration.WebSocketPolyfill(this.url); -+ ws.binaryType = 'arraybuffer'; -+ ws.onmessage = (payload) => this.emit('message', payload); -+ ws.onclose = (payload) => this.emit('close', { event: payload }); -+ ws.onopen = (payload) => this.emit('open', payload); -+ ws.onerror = (err) => { -+ reject(err); -+ }; -+ this.webSocket = ws; -+ // Reset the status -+ this.status = WebSocketStatus.Connecting; -+ this.emit('status', { status: WebSocketStatus.Connecting }); -+ // Store resolve/reject for later use -+ this.connectionAttempt = { -+ resolve, -+ reject, -+ }; -+ }); -+ } -+ onMessage(event) { -+ this.resolveConnectionAttempt(); -+ } -+ resolveConnectionAttempt() { -+ if (this.connectionAttempt) { -+ this.connectionAttempt.resolve(); -+ this.connectionAttempt = null; -+ this.status = WebSocketStatus.Connected; -+ this.emit('status', { status: WebSocketStatus.Connected }); -+ this.emit('connect'); -+ this.messageQueue.forEach(message => this.send(message)); -+ this.messageQueue = []; -+ } -+ } -+ stopConnectionAttempt() { -+ this.connectionAttempt = null; -+ } -+ rejectConnectionAttempt() { -+ var _a; -+ (_a = this.connectionAttempt) === null || _a === void 0 ? void 0 : _a.reject(); -+ this.connectionAttempt = null; -+ } -+ checkConnection() { -+ var _a; -+ // Don’t check the connection when it’s not even established -+ if (this.status !== WebSocketStatus.Connected) { -+ return; -+ } -+ // Don’t close then connection while waiting for the first message -+ if (!this.lastMessageReceived) { -+ return; -+ } -+ // Don’t close the connection when a message was received recently -+ if (this.configuration.messageReconnectTimeout >= getUnixTime() - this.lastMessageReceived) { -+ return; -+ } -+ // No message received in a long time, not even your own -+ // Awareness updates, which are updated every 15 seconds. -+ (_a = this.webSocket) === null || _a === void 0 ? void 0 : _a.close(); -+ this.messageQueue = []; -+ } -+ registerEventListeners() { -+ if (typeof window === 'undefined') { -+ return; -+ } -+ window.addEventListener('online', this.boundConnect); -+ } -+ // Ensure that the URL always ends with / -+ get serverUrl() { -+ while (this.configuration.url[this.configuration.url.length - 1] === '/') { -+ return this.configuration.url.slice(0, this.configuration.url.length - 1); -+ } -+ return this.configuration.url; -+ } -+ get url() { -+ const encodedParams = encodeQueryParams(this.configuration.parameters); -+ return `${this.serverUrl}${encodedParams.length === 0 ? '' : `?${encodedParams}`}`; -+ } -+ disconnect() { -+ this.shouldConnect = false; -+ if (this.webSocket === null) { -+ return; -+ } -+ try { -+ this.webSocket.close(); -+ this.messageQueue = []; -+ } -+ catch { -+ // -+ } -+ } -+ send(message) { -+ var _a; -+ if (((_a = this.webSocket) === null || _a === void 0 ? void 0 : _a.readyState) === WsReadyStates.Open) { -+ this.webSocket.send(message); -+ } -+ else { -+ this.messageQueue.push(message); -+ } -+ } -+ onClose({ event }) { -+ this.webSocket = null; -+ if (this.status === WebSocketStatus.Connected) { -+ this.status = WebSocketStatus.Disconnected; -+ this.emit('status', { status: WebSocketStatus.Disconnected }); -+ this.emit('disconnect', { event }); -+ } -+ if (event.code === Unauthorized.code) { -+ if (event.reason === Unauthorized.reason) { -+ console.warn('[HocuspocusProvider] An authentication token is required, but you didn’t send one. Try adding a `token` to your HocuspocusProvider configuration. Won’t try again.'); - } - else { -- // TODO: Some weird TypeScript error -- // @ts-ignore -- provider.send(OutgoingMessage, { encoder: message.encoder }); -+ console.warn(`[HocuspocusProvider] Connection closed with status Unauthorized: ${event.reason}`); - } -+ this.shouldConnect = false; -+ } -+ if (event.code === Forbidden.code) { -+ if (!this.configuration.quiet) { -+ console.warn('[HocuspocusProvider] The provided authentication token isn’t allowed to connect to this server. Will try again.'); -+ return; // TODO REMOVE ME -+ } -+ } -+ if (event.code === MessageTooBig.code) { -+ console.warn(`[HocuspocusProvider] Connection closed with status MessageTooBig: ${event.reason}`); -+ this.shouldConnect = false; -+ } -+ if (this.connectionAttempt) { -+ // That connection attempt failed. -+ this.rejectConnectionAttempt(); -+ } -+ else if (this.shouldConnect) { -+ // The connection was closed by the server. Let’s just try again. -+ this.connect(); -+ } -+ // If we’ll reconnect, we’re done for now. -+ if (this.shouldConnect) { -+ return; -+ } -+ // The status is set correctly already. -+ if (this.status === WebSocketStatus.Disconnected) { -+ return; - } -+ // Let’s update the connection status. -+ this.status = WebSocketStatus.Disconnected; -+ this.emit('status', { status: WebSocketStatus.Disconnected }); -+ this.emit('disconnect', { event }); - } -- applySyncMessage(provider, emitSynced) { -- const { message } = this; -- message.writeVarUint(MessageType.Sync); -- // Apply update -- const syncMessageType = readSyncMessage(message.decoder, message.encoder, provider.document, provider); -- // Synced once we receive Step2 -- if (emitSynced && syncMessageType === messageYjsSyncStep2) { -- provider.synced = true; -+ destroy() { -+ this.emit('destroy'); -+ if (this.intervals.forceSync) { -+ clearInterval(this.intervals.forceSync); - } -- if (syncMessageType === messageYjsUpdate || syncMessageType === messageYjsSyncStep2) { -- if (provider.unsyncedChanges > 0) { -- provider.updateUnsyncedChanges(-1); -- } -+ clearInterval(this.intervals.connectionChecker); -+ // If there is still a connection attempt outstanding then we should stop -+ // it before calling disconnect, otherwise it will be rejected in the onClose -+ // handler and trigger a retry -+ this.stopConnectionAttempt(); -+ this.disconnect(); -+ this.removeAllListeners(); -+ if (typeof window === 'undefined') { -+ return; - } -- } -- applyAwarenessMessage(provider) { -- const { message } = this; -- applyAwarenessUpdate(provider.awareness, message.readVarUint8Array(), provider); -- } -- applyAuthMessage(provider) { -- const { message } = this; -- readAuthMessage(message.decoder, provider.permissionDeniedHandler.bind(provider), provider.authenticatedHandler.bind(provider)); -- } -- applyQueryAwarenessMessage(provider) { -- const { message } = this; -- message.writeVarUint(MessageType.Awareness); -- message.writeVarUint8Array(encodeAwarenessUpdate(provider.awareness, Array.from(provider.awareness.getStates().keys()))); -+ window.removeEventListener('online', this.boundConnect); - } - } - --class MessageSender { -- constructor(Message, args = {}) { -- this.message = new Message(); -- this.encoder = this.message.get(args); -+class IncomingMessage { -+ constructor(data) { -+ this.data = data; -+ this.encoder = createEncoder(); -+ this.decoder = createDecoder(new Uint8Array(this.data)); - } -- create() { -- return toUint8Array(this.encoder); -+ readVarUint() { -+ return readVarUint(this.decoder); - } -- send(webSocket) { -- webSocket === null || webSocket === void 0 ? void 0 : webSocket.send(this.create()); -+ readVarString() { -+ return readVarString(this.decoder); - } -- broadcast(channel) { -- publish(channel, this.create()); -+ readVarUint8Array() { -+ return readVarUint8Array(this.decoder); - } --} -- --class SyncStepOneMessage extends OutgoingMessage { -- constructor() { -- super(...arguments); -- this.type = MessageType.Sync; -- this.description = 'First sync step'; -+ writeVarUint(type) { -+ return writeVarUint(this.encoder, type); - } -- get(args) { -- if (typeof args.document === 'undefined') { -- throw new Error('The sync step one message requires document as an argument'); -- } -- writeVarString(this.encoder, args.documentName); -- writeVarUint(this.encoder, this.type); -- writeSyncStep1(this.encoder, args.document); -- return this.encoder; -+ writeVarString(string) { -+ return writeVarString(this.encoder, string); - } --} -- --class SyncStepTwoMessage extends OutgoingMessage { -- constructor() { -- super(...arguments); -- this.type = MessageType.Sync; -- this.description = 'Second sync step'; -+ writeVarUint8Array(data) { -+ return writeVarUint8Array(this.encoder, data); - } -- get(args) { -- if (typeof args.document === 'undefined') { -- throw new Error('The sync step two message requires document as an argument'); -- } -- writeVarString(this.encoder, args.documentName); -- writeVarUint(this.encoder, this.type); -- writeSyncStep2(this.encoder, args.document); -- return this.encoder; -+ length() { -+ return length(this.encoder); - } - } - --class QueryAwarenessMessage extends OutgoingMessage { -- constructor() { -- super(...arguments); -- this.type = MessageType.QueryAwareness; -- this.description = 'Queries awareness states'; -- } -- get(args) { -- console.log('queryAwareness: writing string docName', args.documentName); -- console.log(this.encoder.cpos); -- writeVarString(this.encoder, args.documentName); -- writeVarUint(this.encoder, this.type); -- return this.encoder; -- } --} -+/** -+ * @module sync-protocol -+ */ - --class AuthenticationMessage extends OutgoingMessage { -- constructor() { -- super(...arguments); -- this.type = MessageType.Auth; -- this.description = 'Authentication'; -- } -- get(args) { -- if (typeof args.token === 'undefined') { -- throw new Error('The authentication message requires `token` as an argument.'); -- } -- writeVarString(this.encoder, args.documentName); -- writeVarUint(this.encoder, this.type); -- writeAuthentication(this.encoder, args.token); -- return this.encoder; -- } --} -+/** -+ * @typedef {Map} StateMap -+ */ - --class AwarenessMessage extends OutgoingMessage { -- constructor() { -- super(...arguments); -- this.type = MessageType.Awareness; -- this.description = 'Awareness states update'; -- } -- get(args) { -- if (typeof args.awareness === 'undefined') { -- throw new Error('The awareness message requires awareness as an argument'); -- } -- if (typeof args.clients === 'undefined') { -- throw new Error('The awareness message requires clients as an argument'); -- } -- writeVarString(this.encoder, args.documentName); -- writeVarUint(this.encoder, this.type); -- let awarenessUpdate; -- if (args.states === undefined) { -- awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients); -- } -- else { -- awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients, args.states); -- } -- writeVarUint8Array(this.encoder, awarenessUpdate); -- return this.encoder; -- } --} -+/** -+ * Core Yjs defines two message types: -+ * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2. -+ * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it -+ * received all information from the remote client. -+ * -+ * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection -+ * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both -+ * SyncStep2 and SyncDone, it is assured that it is synced to the remote client. -+ * -+ * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1. -+ * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies -+ * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the -+ * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can -+ * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them. -+ * Therefore it is necesarry that the client initiates the sync. -+ * -+ * Construction of a message: -+ * [messageType : varUint, message definition..] -+ * -+ * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol! -+ * -+ * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer) -+ */ - --class UpdateMessage extends OutgoingMessage { -- constructor() { -- super(...arguments); -- this.type = MessageType.Sync; -- this.description = 'A document update'; -- } -- get(args) { -- writeVarString(this.encoder, args.documentName); -- writeVarUint(this.encoder, this.type); -- writeUpdate(this.encoder, args.update); -- return this.encoder; -- } --} -+const messageYjsSyncStep1 = 0; -+const messageYjsSyncStep2 = 1; -+const messageYjsUpdate = 2; -+ -+/** -+ * Create a sync step 1 message based on the state of the current shared document. -+ * -+ * @param {encoding.Encoder} encoder -+ * @param {Y.Doc} doc -+ */ -+const writeSyncStep1 = (encoder, doc) => { -+ writeVarUint(encoder, messageYjsSyncStep1); -+ const sv = Y.encodeStateVector(doc); -+ writeVarUint8Array(encoder, sv); -+}; -+ -+/** -+ * @param {encoding.Encoder} encoder -+ * @param {Y.Doc} doc -+ * @param {Uint8Array} [encodedStateVector] -+ */ -+const writeSyncStep2 = (encoder, doc, encodedStateVector) => { -+ writeVarUint(encoder, messageYjsSyncStep2); -+ writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector)); -+}; -+ -+/** -+ * Read SyncStep1 message and reply with SyncStep2. -+ * -+ * @param {decoding.Decoder} decoder The reply to the received message -+ * @param {encoding.Encoder} encoder The received message -+ * @param {Y.Doc} doc -+ */ -+const readSyncStep1 = (decoder, encoder, doc) => -+ writeSyncStep2(encoder, doc, readVarUint8Array(decoder)); -+ -+/** -+ * Read and apply Structs and then DeleteStore to a y instance. -+ * -+ * @param {decoding.Decoder} decoder -+ * @param {Y.Doc} doc -+ * @param {any} transactionOrigin -+ */ -+const readSyncStep2 = (decoder, doc, transactionOrigin) => { -+ try { -+ Y.applyUpdate(doc, readVarUint8Array(decoder), transactionOrigin); -+ } catch (error) { -+ // This catches errors that are thrown by event handlers -+ console.error('Caught error while handling a Yjs update', error); -+ } -+}; -+ -+/** -+ * @param {encoding.Encoder} encoder -+ * @param {Uint8Array} update -+ */ -+const writeUpdate = (encoder, update) => { -+ writeVarUint(encoder, messageYjsUpdate); -+ writeVarUint8Array(encoder, update); -+}; - - /** -- * Utility module to work with urls. -+ * Read and apply Structs and then DeleteStore to a y instance. - * -- * @module url -+ * @param {decoding.Decoder} decoder -+ * @param {Y.Doc} doc -+ * @param {any} transactionOrigin - */ -+const readUpdate = readSyncStep2; - - /** -- * @param {Object} params -- * @return {string} -+ * @param {decoding.Decoder} decoder A message received from another client -+ * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty. -+ * @param {Y.Doc} doc -+ * @param {any} transactionOrigin - */ --const encodeQueryParams = params => -- map(params, (val, key) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&'); -+const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => { -+ const messageType = readVarUint(decoder); -+ switch (messageType) { -+ case messageYjsSyncStep1: -+ readSyncStep1(decoder, encoder, doc); -+ break -+ case messageYjsSyncStep2: -+ readSyncStep2(decoder, doc, transactionOrigin); -+ break -+ case messageYjsUpdate: -+ readUpdate(decoder, doc, transactionOrigin); -+ break -+ default: -+ throw new Error('Unknown message type') -+ } -+ return messageType -+}; - --class HocuspocusProviderWebsocket extends EventEmitter { -- constructor(configuration) { -- super(); -- this.configuration = { -- url: '', -- // @ts-ignore -- document: undefined, -- // @ts-ignore -- awareness: undefined, -- WebSocketPolyfill: undefined, -- parameters: {}, -- connect: true, -- broadcast: true, -- forceSyncInterval: false, -- // TODO: this should depend on awareness.outdatedTime -- messageReconnectTimeout: 30000, -- // 1 second -- delay: 1000, -- // instant -- initialDelay: 0, -- // double the delay each time -- factor: 2, -- // unlimited retries -- maxAttempts: 0, -- // wait at least 1 second -- minDelay: 1000, -- // at least every 30 seconds -- maxDelay: 30000, -- // randomize -- jitter: true, -- // retry forever -- timeout: 0, -- onOpen: () => null, -- onConnect: () => null, -- onMessage: () => null, -- onOutgoingMessage: () => null, -- onStatus: () => null, -- onDisconnect: () => null, -- onClose: () => null, -- onDestroy: () => null, -- onAwarenessUpdate: () => null, -- onAwarenessChange: () => null, -- quiet: false, -- }; -- this.subscribedToBroadcastChannel = false; -- this.webSocket = null; -- this.shouldConnect = true; -- this.status = WebSocketStatus.Disconnected; -- this.lastMessageReceived = 0; -- this.mux = createMutex(); -- this.intervals = { -- forceSync: null, -- connectionChecker: null, -- }; -- this.connectionAttempt = null; -- this.receivedOnOpenPayload = undefined; -- this.receivedOnStatusPayload = undefined; -- this.boundConnect = this.connect.bind(this); -- this.setConfiguration(configuration); -- this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill ? configuration.WebSocketPolyfill : WebSocket; -- this.on('open', this.configuration.onOpen); -- this.on('open', this.onOpen.bind(this)); -- this.on('connect', this.configuration.onConnect); -- this.on('message', this.configuration.onMessage); -- this.on('outgoingMessage', this.configuration.onOutgoingMessage); -- this.on('status', this.configuration.onStatus); -- this.on('status', this.onStatus.bind(this)); -- this.on('disconnect', this.configuration.onDisconnect); -- this.on('close', this.configuration.onClose); -- this.on('destroy', this.configuration.onDestroy); -- this.on('awarenessUpdate', this.configuration.onAwarenessUpdate); -- this.on('awarenessChange', this.configuration.onAwarenessChange); -- this.on('close', this.onClose.bind(this)); -- this.on('message', this.onMessage.bind(this)); -- this.registerEventListeners(); -- this.intervals.connectionChecker = setInterval(this.checkConnection.bind(this), this.configuration.messageReconnectTimeout / 10); -- if (typeof configuration.connect !== 'undefined') { -- this.shouldConnect = configuration.connect; -- } -- if (!this.shouldConnect) { -- return; -- } -- this.connect(); -- } -- async onOpen(event) { -- this.receivedOnOpenPayload = event; -+class OutgoingMessage { -+ constructor() { -+ this.encoder = createEncoder(); - } -- async onStatus(data) { -- this.receivedOnStatusPayload = data; -+ get(args) { -+ return args.encoder; - } -- attach(provider) { -- if (this.receivedOnOpenPayload) { -- provider.onOpen(this.receivedOnOpenPayload); -- } -- if (this.receivedOnStatusPayload) { -- provider.onStatus(this.receivedOnStatusPayload); -- } -+ toUint8Array() { -+ return toUint8Array(this.encoder); - } -- detach(provider) { -- // tell the server to remove the listener -+} -+ -+class MessageReceiver { -+ constructor(message) { -+ this.broadcasted = false; -+ this.message = message; - } -- setConfiguration(configuration = {}) { -- this.configuration = { ...this.configuration, ...configuration }; -+ setBroadcasted(value) { -+ this.broadcasted = value; -+ return this; - } -- async connect() { -- if (this.status === WebSocketStatus.Connected) { -- return; -- } -- // Always cancel any previously initiated connection retryer instances -- if (this.cancelWebsocketRetry) { -- this.cancelWebsocketRetry(); -- this.cancelWebsocketRetry = undefined; -+ apply(provider, emitSynced) { -+ const { message } = this; -+ const type = message.readVarUint(); -+ const emptyMessageLength = message.length(); -+ switch (type) { -+ case MessageType.Sync: -+ this.applySyncMessage(provider, emitSynced); -+ break; -+ case MessageType.Awareness: -+ this.applyAwarenessMessage(provider); -+ break; -+ case MessageType.Auth: -+ this.applyAuthMessage(provider); -+ break; -+ case MessageType.QueryAwareness: -+ this.applyQueryAwarenessMessage(provider); -+ break; -+ case MessageType.Stateless: -+ provider.receiveStateless(readVarString(message.decoder)); -+ break; -+ case MessageType.SyncStatus: -+ this.applySyncStatusMessage(provider, readVarInt(message.decoder) === 1); -+ break; -+ default: -+ throw new Error(`Can’t apply message of unknown type: ${type}`); - } -- this.shouldConnect = true; -- const abortableRetry = () => { -- let cancelAttempt = false; -- const retryPromise = retry(this.createWebSocketConnection.bind(this), { -- delay: this.configuration.delay, -- initialDelay: this.configuration.initialDelay, -- factor: this.configuration.factor, -- maxAttempts: this.configuration.maxAttempts, -- minDelay: this.configuration.minDelay, -- maxDelay: this.configuration.maxDelay, -- jitter: this.configuration.jitter, -- timeout: this.configuration.timeout, -- beforeAttempt: context => { -- if (!this.shouldConnect || cancelAttempt) { -- context.abort(); -- } -- }, -- }).catch((error) => { -- // If we aborted the connection attempt then don’t throw an error -- // ref: https://github.com/lifeomic/attempt/blob/master/src/index.ts#L136 -- if (error && error.code !== 'ATTEMPT_ABORTED') { -- throw error; -- } -- }); -- return { -- retryPromise, -- cancelFunc: () => { -- cancelAttempt = true; -- }, -- }; -- }; -- const { retryPromise, cancelFunc } = abortableRetry(); -- this.cancelWebsocketRetry = cancelFunc; -- return retryPromise; -- } -- createWebSocketConnection() { -- return new Promise((resolve, reject) => { -- if (this.webSocket) { -- this.webSocket.close(); -- this.webSocket = null; -+ // Reply -+ if (message.length() > emptyMessageLength + 1) { // length of documentName (considered in emptyMessageLength plus length of yjs sync type, set in applySyncMessage) -+ if (this.broadcasted) { -+ // TODO: Some weird TypeScript error -+ // @ts-ignore -+ provider.broadcast(OutgoingMessage, { encoder: message.encoder }); - } -- // Init the WebSocket connection -- const ws = new this.configuration.WebSocketPolyfill(this.url); -- ws.binaryType = 'arraybuffer'; -- ws.onmessage = (payload) => this.emit('message', payload); -- ws.onclose = (payload) => this.emit('close', { event: payload }); -- ws.onopen = (payload) => this.emit('open', payload); -- ws.onerror = (err) => { -- reject(err); -- }; -- this.webSocket = ws; -- // Reset the status -- this.status = WebSocketStatus.Connecting; -- this.emit('status', { status: WebSocketStatus.Connecting }); -- // Store resolve/reject for later use -- this.connectionAttempt = { -- resolve, -- reject, -- }; -- }); -+ else { -+ // TODO: Some weird TypeScript error -+ // @ts-ignore -+ provider.send(OutgoingMessage, { encoder: message.encoder }); -+ } -+ } - } -- onMessage(event) { -- this.resolveConnectionAttempt(); -+ applySyncMessage(provider, emitSynced) { -+ const { message } = this; -+ message.writeVarUint(MessageType.Sync); -+ // Apply update -+ const syncMessageType = readSyncMessage(message.decoder, message.encoder, provider.document, provider); -+ // Synced once we receive Step2 -+ if (emitSynced && syncMessageType === messageYjsSyncStep2) { -+ provider.synced = true; -+ } - } -- resolveConnectionAttempt() { -- if (this.connectionAttempt) { -- this.connectionAttempt.resolve(); -- this.connectionAttempt = null; -- this.status = WebSocketStatus.Connected; -- this.emit('status', { status: WebSocketStatus.Connected }); -- this.emit('connect'); -+ applySyncStatusMessage(provider, applied) { -+ if (applied) { -+ provider.decrementUnsyncedChanges(); - } - } -- stopConnectionAttempt() { -- this.connectionAttempt = null; -+ applyAwarenessMessage(provider) { -+ const { message } = this; -+ applyAwarenessUpdate(provider.awareness, message.readVarUint8Array(), provider); - } -- rejectConnectionAttempt() { -- var _a; -- (_a = this.connectionAttempt) === null || _a === void 0 ? void 0 : _a.reject(); -- this.connectionAttempt = null; -+ applyAuthMessage(provider) { -+ const { message } = this; -+ readAuthMessage(message.decoder, provider.permissionDeniedHandler.bind(provider), provider.authenticatedHandler.bind(provider)); - } -- checkConnection() { -- var _a; -- // Don’t check the connection when it’s not even established -- if (this.status !== WebSocketStatus.Connected) { -- return; -- } -- // Don’t close then connection while waiting for the first message -- if (!this.lastMessageReceived) { -- return; -- } -- // Don’t close the connection when a message was received recently -- if (this.configuration.messageReconnectTimeout >= getUnixTime() - this.lastMessageReceived) { -- return; -- } -- // No message received in a long time, not even your own -- // Awareness updates, which are updated every 15 seconds. -- (_a = this.webSocket) === null || _a === void 0 ? void 0 : _a.close(); -+ applyQueryAwarenessMessage(provider) { -+ const { message } = this; -+ message.writeVarUint(MessageType.Awareness); -+ message.writeVarUint8Array(encodeAwarenessUpdate(provider.awareness, Array.from(provider.awareness.getStates().keys()))); - } -- registerEventListeners() { -- if (typeof window === 'undefined') { -- return; -- } -- window.addEventListener('online', this.boundConnect); -+} -+ -+class MessageSender { -+ constructor(Message, args = {}) { -+ this.message = new Message(); -+ this.encoder = this.message.get(args); - } -- // Ensure that the URL always ends with / -- get serverUrl() { -- while (this.configuration.url[this.configuration.url.length - 1] === '/') { -- return this.configuration.url.slice(0, this.configuration.url.length - 1); -- } -- return this.configuration.url; -+ create() { -+ return toUint8Array(this.encoder); - } -- get url() { -- const encodedParams = encodeQueryParams(this.configuration.parameters); -- return `${this.serverUrl}${encodedParams.length === 0 ? '' : `?${encodedParams}`}`; -+ send(webSocket) { -+ webSocket === null || webSocket === void 0 ? void 0 : webSocket.send(this.create()); - } -- disconnect() { -- this.shouldConnect = false; -- if (this.webSocket === null) { -- return; -- } -- try { -- this.webSocket.close(); -- } -- catch { -- // -- } -+ broadcast(channel) { -+ publish(channel, this.create()); - } -- send(message) { -- var _a; -- if (((_a = this.webSocket) === null || _a === void 0 ? void 0 : _a.readyState) === WsReadyStates.Open) { -- this.webSocket.send(message); -- } -+} -+ -+class AuthenticationMessage extends OutgoingMessage { -+ constructor() { -+ super(...arguments); -+ this.type = MessageType.Auth; -+ this.description = 'Authentication'; - } -- onClose({ event }) { -- this.webSocket = null; -- if (this.status === WebSocketStatus.Connected) { -- this.status = WebSocketStatus.Disconnected; -- this.emit('status', { status: WebSocketStatus.Disconnected }); -- this.emit('disconnect', { event }); -- } -- if (event.code === Unauthorized.code) { -- if (event.reason === Unauthorized.reason) { -- console.warn('[HocuspocusProvider] An authentication token is required, but you didn’t send one. Try adding a `token` to your HocuspocusProvider configuration. Won’t try again.'); -- } -- else { -- console.warn(`[HocuspocusProvider] Connection closed with status Unauthorized: ${event.reason}`); -- } -- this.shouldConnect = false; -- } -- if (event.code === Forbidden.code) { -- if (!this.configuration.quiet) { -- console.warn('[HocuspocusProvider] The provided authentication token isn’t allowed to connect to this server. Will try again.'); -- return; // TODO REMOVE ME -- } -- } -- if (event.code === MessageTooBig.code) { -- console.warn(`[HocuspocusProvider] Connection closed with status MessageTooBig: ${event.reason}`); -- this.shouldConnect = false; -+ get(args) { -+ if (typeof args.token === 'undefined') { -+ throw new Error('The authentication message requires `token` as an argument.'); - } -- if (this.connectionAttempt) { -- // That connection attempt failed. -- this.rejectConnectionAttempt(); -+ writeVarString(this.encoder, args.documentName); -+ writeVarUint(this.encoder, this.type); -+ writeAuthentication(this.encoder, args.token); -+ return this.encoder; -+ } -+} -+ -+class AwarenessMessage extends OutgoingMessage { -+ constructor() { -+ super(...arguments); -+ this.type = MessageType.Awareness; -+ this.description = 'Awareness states update'; -+ } -+ get(args) { -+ if (typeof args.awareness === 'undefined') { -+ throw new Error('The awareness message requires awareness as an argument'); - } -- else if (this.shouldConnect) { -- // The connection was closed by the server. Let’s just try again. -- this.connect(); -+ if (typeof args.clients === 'undefined') { -+ throw new Error('The awareness message requires clients as an argument'); - } -- // If we’ll reconnect, we’re done for now. -- if (this.shouldConnect) { -- return; -+ writeVarString(this.encoder, args.documentName); -+ writeVarUint(this.encoder, this.type); -+ let awarenessUpdate; -+ if (args.states === undefined) { -+ awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients); - } -- // The status is set correctly already. -- if (this.status === WebSocketStatus.Disconnected) { -- return; -+ else { -+ awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients, args.states); - } -- // Let’s update the connection status. -- this.status = WebSocketStatus.Disconnected; -- this.emit('status', { status: WebSocketStatus.Disconnected }); -- this.emit('disconnect', { event }); -+ writeVarUint8Array(this.encoder, awarenessUpdate); -+ return this.encoder; - } -- destroy() { -- this.emit('destroy'); -- if (this.intervals.forceSync) { -- clearInterval(this.intervals.forceSync); -- } -- clearInterval(this.intervals.connectionChecker); -- // If there is still a connection attempt outstanding then we should stop -- // it before calling disconnect, otherwise it will be rejected in the onClose -- // handler and trigger a retry -- this.stopConnectionAttempt(); -- this.disconnect(); -- this.removeAllListeners(); -- if (typeof window === 'undefined') { -- return; -- } -- window.removeEventListener('online', this.boundConnect); -+} -+ -+class CloseMessage extends OutgoingMessage { -+ constructor() { -+ super(...arguments); -+ this.type = MessageType.CLOSE; -+ this.description = 'Ask the server to close the connection'; -+ } -+ get(args) { -+ writeVarString(this.encoder, args.documentName); -+ writeVarUint(this.encoder, this.type); -+ return this.encoder; -+ } -+} -+ -+class QueryAwarenessMessage extends OutgoingMessage { -+ constructor() { -+ super(...arguments); -+ this.type = MessageType.QueryAwareness; -+ this.description = 'Queries awareness states'; -+ } -+ get(args) { -+ console.log('queryAwareness: writing string docName', args.documentName); -+ console.log(this.encoder.cpos); -+ writeVarString(this.encoder, args.documentName); -+ writeVarUint(this.encoder, this.type); -+ return this.encoder; - } - } - -@@ -2265,15 +2282,50 @@ class StatelessMessage extends OutgoingMessage { - } - } - --class CloseMessage extends OutgoingMessage { -+class SyncStepOneMessage extends OutgoingMessage { - constructor() { - super(...arguments); -- this.type = MessageType.CLOSE; -- this.description = 'Ask the server to close the connection'; -+ this.type = MessageType.Sync; -+ this.description = 'First sync step'; -+ } -+ get(args) { -+ if (typeof args.document === 'undefined') { -+ throw new Error('The sync step one message requires document as an argument'); -+ } -+ writeVarString(this.encoder, args.documentName); -+ writeVarUint(this.encoder, this.type); -+ writeSyncStep1(this.encoder, args.document); -+ return this.encoder; -+ } -+} -+ -+class SyncStepTwoMessage extends OutgoingMessage { -+ constructor() { -+ super(...arguments); -+ this.type = MessageType.Sync; -+ this.description = 'Second sync step'; -+ } -+ get(args) { -+ if (typeof args.document === 'undefined') { -+ throw new Error('The sync step two message requires document as an argument'); -+ } -+ writeVarString(this.encoder, args.documentName); -+ writeVarUint(this.encoder, this.type); -+ writeSyncStep2(this.encoder, args.document); -+ return this.encoder; -+ } -+} -+ -+class UpdateMessage extends OutgoingMessage { -+ constructor() { -+ super(...arguments); -+ this.type = MessageType.Sync; -+ this.description = 'A document update'; - } - get(args) { - writeVarString(this.encoder, args.documentName); - writeVarUint(this.encoder, this.type); -+ writeUpdate(this.encoder, args.update); - return this.encoder; - } - } -@@ -2384,8 +2436,15 @@ class HocuspocusProvider extends EventEmitter { - get hasUnsyncedChanges() { - return this.unsyncedChanges > 0; - } -- updateUnsyncedChanges(unsyncedChanges = 0) { -- this.unsyncedChanges += unsyncedChanges; -+ incrementUnsyncedChanges() { -+ this.unsyncedChanges += 1; -+ this.emit('unsyncedChanges', this.unsyncedChanges); -+ } -+ decrementUnsyncedChanges() { -+ this.unsyncedChanges -= 1; -+ if (this.unsyncedChanges === 0) { -+ this.synced = true; -+ } - this.emit('unsyncedChanges', this.unsyncedChanges); - } - forceSync() { -@@ -2407,7 +2466,7 @@ class HocuspocusProvider extends EventEmitter { - if (origin === this) { - return; - } -- this.updateUnsyncedChanges(1); -+ this.incrementUnsyncedChanges(); - this.send(UpdateMessage, { update, documentName: this.configuration.name }, true); - } - awarenessUpdateHandler({ added, updated, removed }, origin) { -@@ -2425,9 +2484,6 @@ class HocuspocusProvider extends EventEmitter { - if (this.isSynced === state) { - return; - } -- if (state && this.unsyncedChanges > 0) { -- this.updateUnsyncedChanges(-1 * this.unsyncedChanges); -- } - this.isSynced = state; - this.emit('synced', { state }); - this.emit('sync', { state }); -@@ -2465,6 +2521,7 @@ class HocuspocusProvider extends EventEmitter { - return this.configuration.token; - } - startSync() { -+ this.incrementUnsyncedChanges(); - this.send(SyncStepOneMessage, { document: this.document, documentName: this.configuration.name }); - if (this.awareness.getLocalState() !== null) { - this.send(AwarenessMessage, { -@@ -2475,8 +2532,9 @@ class HocuspocusProvider extends EventEmitter { - } - } - send(message, args, broadcast = false) { -- if (!this.isConnected) -+ if (!this.isConnected) { - return; -+ } - if (broadcast) { - this.mux(() => { this.broadcast(message, args); }); - } -@@ -2492,7 +2550,7 @@ class HocuspocusProvider extends EventEmitter { - } - message.writeVarString(documentName); - this.emit('message', { event, message: new IncomingMessage(event.data) }); -- new MessageReceiver(message).apply(this); -+ new MessageReceiver(message).apply(this, true); - } - onClose(event) { - this.isAuthenticated = false; -diff --git a/node_modules/@hocuspocus/provider/dist/hocuspocus-provider.esm.js.map b/node_modules/@hocuspocus/provider/dist/hocuspocus-provider.esm.js.map -index a18b6bc..8578e37 100644 ---- a/node_modules/@hocuspocus/provider/dist/hocuspocus-provider.esm.js.map -+++ b/node_modules/@hocuspocus/provider/dist/hocuspocus-provider.esm.js.map -@@ -1 +1 @@ --{"version":3,"file":"hocuspocus-provider.esm.js","sources":["../../../node_modules/lib0/map.js","../../../node_modules/lib0/set.js","../../../node_modules/lib0/string.js","../../../node_modules/lib0/conditions.js","../../../node_modules/lib0/storage.js","../../../node_modules/lib0/array.js","../../../node_modules/lib0/object.js","../../../node_modules/lib0/function.js","../../../node_modules/lib0/environment.js","../../../node_modules/lib0/math.js","../../../node_modules/lib0/binary.js","../../../node_modules/lib0/number.js","../../../node_modules/lib0/encoding.js","../../../node_modules/lib0/error.js","../../../node_modules/lib0/decoding.js","../../../node_modules/lib0/buffer.js","../../../node_modules/lib0/broadcastchannel.js","../../../node_modules/lib0/time.js","../../../node_modules/lib0/observable.js","../../../node_modules/y-protocols/awareness.js","../../../node_modules/lib0/mutex.js","../src/EventEmitter.ts","../src/IncomingMessage.ts","../../../node_modules/y-protocols/sync.js","../src/types.ts","../src/OutgoingMessage.ts","../src/MessageReceiver.ts","../src/MessageSender.ts","../src/OutgoingMessages/SyncStepOneMessage.ts","../src/OutgoingMessages/SyncStepTwoMessage.ts","../src/OutgoingMessages/QueryAwarenessMessage.ts","../src/OutgoingMessages/AuthenticationMessage.ts","../src/OutgoingMessages/AwarenessMessage.ts","../src/OutgoingMessages/UpdateMessage.ts","../../../node_modules/lib0/url.js","../src/HocuspocusProviderWebsocket.ts","../src/OutgoingMessages/StatelessMessage.ts","../src/OutgoingMessages/CloseMessage.ts","../src/HocuspocusProvider.ts","../src/TiptapCollabProviderWebsocket.ts","../src/TiptapCollabProvider.ts"],"sourcesContent":["/**\n * Utility module to work with key-value stores.\n *\n * @module map\n */\n\n/**\n * Creates a new Map instance.\n *\n * @function\n * @return {Map}\n *\n * @function\n */\nexport const create = () => new Map()\n\n/**\n * Copy a Map object into a fresh Map object.\n *\n * @function\n * @template X,Y\n * @param {Map} m\n * @return {Map}\n */\nexport const copy = m => {\n const r = create()\n m.forEach((v, k) => { r.set(k, v) })\n return r\n}\n\n/**\n * Get map property. Create T if property is undefined and set T on map.\n *\n * ```js\n * const listeners = map.setIfUndefined(events, 'eventName', set.create)\n * listeners.add(listener)\n * ```\n *\n * @function\n * @template V,K\n * @template {Map} MAP\n * @param {MAP} map\n * @param {K} key\n * @param {function():V} createT\n * @return {V}\n */\nexport const setIfUndefined = (map, key, createT) => {\n let set = map.get(key)\n if (set === undefined) {\n map.set(key, set = createT())\n }\n return set\n}\n\n/**\n * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function.\n *\n * @function\n * @template K\n * @template V\n * @template R\n * @param {Map} m\n * @param {function(V,K):R} f\n * @return {Array}\n */\nexport const map = (m, f) => {\n const res = []\n for (const [key, value] of m) {\n res.push(f(value, key))\n }\n return res\n}\n\n/**\n * Tests whether any key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @todo should rename to some - similarly to Array.some\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const any = (m, f) => {\n for (const [key, value] of m) {\n if (f(value, key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * Tests whether all key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const all = (m, f) => {\n for (const [key, value] of m) {\n if (!f(value, key)) {\n return false\n }\n }\n return true\n}\n","/**\n * Utility module to work with sets.\n *\n * @module set\n */\n\nexport const create = () => new Set()\n\n/**\n * @template T\n * @param {Set} set\n * @return {Array}\n */\nexport const toArray = set => Array.from(set)\n\n/**\n * @template T\n * @param {Set} set\n * @return {T}\n */\nexport const first = set =>\n set.values().next().value || undefined\n\n/**\n * @template T\n * @param {Iterable} entries\n * @return {Set}\n */\nexport const from = entries => new Set(entries)\n","/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* c8 ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* c8 ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* c8 ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* c8 ignore start */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* c8 ignore next */\n utf8TextDecoder = null\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* c8 ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n","/**\n * Often used conditions.\n *\n * @module conditions\n */\n\n/**\n * @template T\n * @param {T|null|undefined} v\n * @return {T|null}\n */\n/* c8 ignore next */\nexport const undefinedToNull = v => v === undefined ? null : v\n","/* eslint-env browser */\n\n/**\n * Isomorphic variable storage.\n *\n * Uses LocalStorage in the browser and falls back to in-memory storage.\n *\n * @module storage\n */\n\n/* c8 ignore start */\nclass VarStoragePolyfill {\n constructor () {\n this.map = new Map()\n }\n\n /**\n * @param {string} key\n * @param {any} newValue\n */\n setItem (key, newValue) {\n this.map.set(key, newValue)\n }\n\n /**\n * @param {string} key\n */\n getItem (key) {\n return this.map.get(key)\n }\n}\n/* c8 ignore stop */\n\n/**\n * @type {any}\n */\nlet _localStorage = new VarStoragePolyfill()\nlet usePolyfill = true\n\n/* c8 ignore start */\ntry {\n // if the same-origin rule is violated, accessing localStorage might thrown an error\n if (typeof localStorage !== 'undefined') {\n _localStorage = localStorage\n usePolyfill = false\n }\n} catch (e) { }\n/* c8 ignore stop */\n\n/**\n * This is basically localStorage in browser, or a polyfill in nodejs\n */\n/* c8 ignore next */\nexport const varStorage = _localStorage\n\n/**\n * A polyfill for `addEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler))\n\n/**\n * A polyfill for `removeEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler))\n","/**\n * Utility module to work with Arrays.\n *\n * @module array\n */\n\nimport * as set from './set.js'\n\n/**\n * Return the last element of an array. The element must exist\n *\n * @template L\n * @param {ArrayLike} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array}\n */\nexport const create = () => /** @type {Array} */ ([])\n\n/**\n * @template D\n * @param {Array} a\n * @return {Array}\n */\nexport const copy = a => /** @type {Array} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array} dest\n * @param {Array} src\n */\nexport const appendTo = (dest, src) => {\n for (let i = 0; i < src.length; i++) {\n dest.push(src[i])\n }\n}\n\n/**\n * Transforms something array-like to an actual Array.\n *\n * @function\n * @template T\n * @param {ArrayLike|Iterable} arraylike\n * @return {T}\n */\nexport const from = Array.from\n\n/**\n * True iff condition holds on every element in the Array.\n *\n * @function\n * @template ITEM\n * @template {ArrayLike} ARR\n *\n * @param {ARR} arr\n * @param {function(ITEM, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const every = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (!f(arr[i], i, arr)) {\n return false\n }\n }\n return true\n}\n\n/**\n * True iff condition holds on some element in the Array.\n *\n * @function\n * @template S\n * @template {ArrayLike} ARR\n * @param {ARR} arr\n * @param {function(S, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const some = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (f(arr[i], i, arr)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @template ELEM\n *\n * @param {ArrayLike} a\n * @param {ArrayLike} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a.length === b.length && every(a, (item, index) => item === b[index])\n\n/**\n * @template ELEM\n * @param {Array>} arr\n * @return {Array}\n */\nexport const flatten = arr => arr.reduce((acc, val) => acc.concat(val), [])\n\nexport const isArray = Array.isArray\n\n/**\n * @template T\n * @param {Array} arr\n * @return {Array}\n */\nexport const unique = arr => from(set.from(arr))\n\n/**\n * @template T\n * @template M\n * @param {ArrayLike} arr\n * @param {function(T):M} mapper\n * @return {Array}\n */\nexport const uniqueBy = (arr, mapper) => {\n /**\n * @type {Set}\n */\n const happened = set.create()\n /**\n * @type {Array}\n */\n const result = []\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i]\n const mapped = mapper(el)\n if (!happened.has(mapped)) {\n happened.add(mapped)\n result.push(el)\n }\n }\n return result\n}\n","/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object} obj\n */\nexport const keys = Object.keys\n\n/**\n * @template V\n * @param {{[k:string]:V}} obj\n * @param {function(V,string):any} f\n */\nexport const forEach = (obj, f) => {\n for (const key in obj) {\n f(obj[key], key)\n }\n}\n\n/**\n * @todo implement mapToArray & map\n *\n * @template R\n * @param {Object} obj\n * @param {function(any,string):R} f\n * @return {Array}\n */\nexport const map = (obj, f) => {\n const results = []\n for (const key in obj) {\n results.push(f(obj[key], key))\n }\n return results\n}\n\n/**\n * @param {Object} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n for (const key in obj) {\n if (f(obj[key], key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {Object|undefined} obj\n */\nexport const isEmpty = obj => {\n for (const _k in obj) {\n return false\n }\n return true\n}\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n for (const key in obj) {\n if (!f(obj[key], key)) {\n return false\n }\n }\n return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object} a\n * @param {Object} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val))\n","/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array} fs\n * @param {Array} args\n */\nexport const callAll = (fs, args, i = 0) => {\n try {\n for (; i < fs.length; i++) {\n fs[i](...args)\n }\n } finally {\n if (i < fs.length) {\n callAll(fs, args, i + 1)\n }\n }\n}\n\nexport const nop = () => {}\n\n/**\n * @template T\n * @param {function():T} f\n * @return {T}\n */\nexport const apply = f => f()\n\n/**\n * @template A\n *\n * @param {A} a\n * @return {A}\n */\nexport const id = a => a\n\n/**\n * @template T\n *\n * @param {T} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equalityStrict = (a, b) => a === b\n\n/**\n * @template T\n *\n * @param {Array|object} a\n * @param {Array|object} b\n * @return {boolean}\n */\nexport const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((a instanceof Array && array.equalFlat(a, /** @type {Array} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/* c8 ignore start */\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a == null || b == null) {\n return equalityStrict(a, b)\n }\n if (a.constructor !== b.constructor) {\n return false\n }\n if (a === b) {\n return true\n }\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n break\n }\n case Map: {\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n return false\n }\n }\n break\n }\n case Object:\n if (object.length(a) !== object.length(b)) {\n return false\n }\n for (const key in a) {\n if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n return false\n }\n }\n break\n case Array:\n if (a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!equalityDeep(a[i], b[i])) {\n return false\n }\n }\n break\n default:\n return false\n }\n return true\n}\n\n/**\n * @template V\n * @template {V} OPTS\n *\n * @param {V} value\n * @param {Array} options\n */\n// @ts-ignore\nexport const isOneOf = (value, options) => options.includes(value)\n/* c8 ignore stop */\n","/**\n * Isomorphic module to work access the environment (query params, env variables).\n *\n * @module map\n */\n\nimport * as map from './map.js'\nimport * as string from './string.js'\nimport * as conditions from './conditions.js'\nimport * as storage from './storage.js'\nimport * as f from './function.js'\n\n/* c8 ignore next */\n// @ts-ignore\nexport const isNode = typeof process !== 'undefined' && process.release &&\n /node|io\\.js/.test(process.release.name)\n/* c8 ignore next */\nexport const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && !isNode\n/* c8 ignore next 3 */\nexport const isMac = typeof navigator !== 'undefined'\n ? /Mac/.test(navigator.platform)\n : false\n\n/**\n * @type {Map}\n */\nlet params\nconst args = []\n\n/* c8 ignore start */\nconst computeParams = () => {\n if (params === undefined) {\n if (isNode) {\n params = map.create()\n const pargs = process.argv\n let currParamName = null\n for (let i = 0; i < pargs.length; i++) {\n const parg = pargs[i]\n if (parg[0] === '-') {\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n currParamName = parg\n } else {\n if (currParamName !== null) {\n params.set(currParamName, parg)\n currParamName = null\n } else {\n args.push(parg)\n }\n }\n }\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n // in ReactNative for example this would not be true (unless connected to the Remote Debugger)\n } else if (typeof location === 'object') {\n params = map.create(); // eslint-disable-next-line no-undef\n (location.search || '?').slice(1).split('&').forEach((kv) => {\n if (kv.length !== 0) {\n const [key, value] = kv.split('=')\n params.set(`--${string.fromCamelCase(key, '-')}`, value)\n params.set(`-${string.fromCamelCase(key, '-')}`, value)\n }\n })\n } else {\n params = map.create()\n }\n }\n return params\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next */\nexport const hasParam = (name) => computeParams().has(name)\n\n/**\n * @param {string} name\n * @param {string} defaultVal\n * @return {string}\n */\n/* c8 ignore next 2 */\nexport const getParam = (name, defaultVal) =>\n computeParams().get(name) || defaultVal\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 4 */\nexport const getVariable = (name) =>\n isNode\n ? conditions.undefinedToNull(process.env[name.toUpperCase()])\n : conditions.undefinedToNull(storage.varStorage.getItem(name))\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 2 */\nexport const getConf = (name) =>\n computeParams().get('--' + name) || getVariable(name)\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next 2 */\nexport const hasConf = (name) =>\n hasParam('--' + name) || getVariable(name) !== null\n\n/* c8 ignore next */\nexport const production = hasConf('production')\n\n/* c8 ignore next 2 */\nconst forceColor = isNode &&\n f.isOneOf(process.env.FORCE_COLOR, ['true', '1', '2'])\n\n/* c8 ignore start */\nexport const supportsColor = !hasParam('no-colors') &&\n (!isNode || process.stdout.isTTY || forceColor) && (\n !isNode || hasParam('color') || forceColor ||\n getVariable('COLORTERM') !== null ||\n (getVariable('TERM') || '').includes('color')\n)\n/* c8 ignore stop */\n","/**\n * Common Math expressions.\n *\n * @module math\n */\n\nexport const floor = Math.floor\nexport const ceil = Math.ceil\nexport const abs = Math.abs\nexport const imul = Math.imul\nexport const round = Math.round\nexport const log10 = Math.log10\nexport const log2 = Math.log2\nexport const log = Math.log\nexport const sqrt = Math.sqrt\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The sum of a and b\n */\nexport const add = (a, b) => a + b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The smaller element of a and b\n */\nexport const min = (a, b) => a < b ? a : b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The bigger element of a and b\n */\nexport const max = (a, b) => a > b ? a : b\n\nexport const isNaN = Number.isNaN\n\nexport const pow = Math.pow\n/**\n * Base 10 exponential function. Returns the value of 10 raised to the power of pow.\n *\n * @param {number} exp\n * @return {number}\n */\nexport const exp10 = exp => Math.pow(10, exp)\n\nexport const sign = Math.sign\n\n/**\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\n/**\n * @type {number}\n */\nexport const HIGHEST_INT32 = binary.BITS31\n\n/**\n * @module number\n */\n\n/* c8 ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n","/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\nimport * as string from './string.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nexport const verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer. Max encodable integer is 2^53.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num = math.floor(num / 64) // shift >>> 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n}\n\n/**\n * A cache to store strings temporarily\n */\nconst _strBuffer = new Uint8Array(30000)\nconst _maxStrBSize = _strBuffer.length / 3\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringNative = (encoder, str) => {\n if (str.length < _maxStrBSize) {\n // We can encode the string into the existing buffer\n /* c8 ignore next */\n const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0\n writeVarUint(encoder, written)\n for (let i = 0; i < written; i++) {\n write(encoder, _strBuffer[i])\n }\n } else {\n writeVarUint8Array(encoder, string.encodeUtf8(str))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringPolyfill = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\n/* c8 ignore next */\nexport const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && math.abs(data) <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (data instanceof Array) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n","/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* c8 ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n","/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as binary from './binary.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as string from './string.js'\nimport * as error from './error.js'\n\nconst errorUnexpectedEndOfArray = error.create('Unexpected end of array')\nconst errorIntegerOutOfRange = error.create('Integer out of Range')\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n */\nexport class Decoder {\n /**\n * @param {Uint8Array} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @param {Uint8Array} uint8Array\n * @return {Decoder}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = buffer.createUint8ArrayViewFromArrayBuffer(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let mult = 1\n const len = decoder.arr.length\n while (decoder.pos < len) {\n const r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num\n mult *= 128 // next iteration, shift 7 \"more\" to the left\n if (r < binary.BIT8) {\n return num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let mult = 64\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n const len = decoder.arr.length\n while (decoder.pos < len) {\n r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult\n mult *= 128\n if (r < binary.BIT8) {\n return sign * num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * We don't test this function anymore as we use native decoding/encoding by default now.\n * Better not modify this anymore..\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\n/* c8 ignore start */\nexport const _readVarStringPolyfill = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n/* c8 ignore stop */\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n */\nexport const _readVarStringNative = decoder =>\n /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder))\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n *\n */\n/* c8 ignore next */\nexport const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object\n const len = readVarUint(decoder)\n /**\n * @type {Object}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = math.floor(diff / 2) // shift >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n","/**\n * Utility functions to work with buffers (Uint8Array).\n *\n * @module buffer\n */\n\nimport * as string from './string.js'\nimport * as env from './environment.js'\nimport * as encoding from './encoding.js'\nimport * as decoding from './decoding.js'\n\n/**\n * @param {number} len\n */\nexport const createUint8ArrayFromLen = len => new Uint8Array(len)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n * @param {number} byteOffset\n * @param {number} length\n */\nexport const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n */\nexport const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer)\n\n/* c8 ignore start */\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Browser = bytes => {\n let s = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n s += string.fromCharCode(bytes[i])\n }\n // eslint-disable-next-line no-undef\n return btoa(s)\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')\n\n/* c8 ignore start */\n/**\n * @param {string} s\n * @return {Uint8Array}\n */\nconst fromBase64Browser = s => {\n // eslint-disable-next-line no-undef\n const a = atob(s)\n const bytes = createUint8ArrayFromLen(a.length)\n for (let i = 0; i < a.length; i++) {\n bytes[i] = a.charCodeAt(i)\n }\n return bytes\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} s\n */\nconst fromBase64Node = s => {\n const buf = Buffer.from(s, 'base64')\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n}\n\n/* c8 ignore next */\nexport const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node\n\n/* c8 ignore next */\nexport const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node\n\n/**\n * Copy the content of an Uint8Array view to a new ArrayBuffer.\n *\n * @param {Uint8Array} uint8Array\n * @return {Uint8Array}\n */\nexport const copyUint8Array = uint8Array => {\n const newBuf = createUint8ArrayFromLen(uint8Array.byteLength)\n newBuf.set(uint8Array)\n return newBuf\n}\n\n/**\n * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type.\n * See encoding.writeAny for more information.\n *\n * @param {any} data\n * @return {Uint8Array}\n */\nexport const encodeAny = data => {\n const encoder = encoding.createEncoder()\n encoding.writeAny(encoder, data)\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Decode an any-encoded value.\n *\n * @param {Uint8Array} buf\n * @return {any}\n */\nexport const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf))\n","/* eslint-env browser */\n\n/**\n * Helpers for cross-tab communication using broadcastchannel with LocalStorage fallback.\n *\n * ```js\n * // In browser window A:\n * broadcastchannel.subscribe('my events', data => console.log(data))\n * broadcastchannel.publish('my events', 'Hello world!') // => A: 'Hello world!' fires synchronously in same tab\n *\n * // In browser window B:\n * broadcastchannel.publish('my events', 'hello from tab B') // => A: 'hello from tab B'\n * ```\n *\n * @module broadcastchannel\n */\n\n// @todo before next major: use Uint8Array instead as buffer object\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as buffer from './buffer.js'\nimport * as storage from './storage.js'\n\n/**\n * @typedef {Object} Channel\n * @property {Set} Channel.subs\n * @property {any} Channel.bc\n */\n\n/**\n * @type {Map}\n */\nconst channels = new Map()\n\n/* c8 ignore start */\nclass LocalStoragePolyfill {\n /**\n * @param {string} room\n */\n constructor (room) {\n this.room = room\n /**\n * @type {null|function({data:ArrayBuffer}):void}\n */\n this.onmessage = null\n /**\n * @param {any} e\n */\n this._onChange = e => e.key === room && this.onmessage !== null && this.onmessage({ data: buffer.fromBase64(e.newValue || '') })\n storage.onChange(this._onChange)\n }\n\n /**\n * @param {ArrayBuffer} buf\n */\n postMessage (buf) {\n storage.varStorage.setItem(this.room, buffer.toBase64(buffer.createUint8ArrayFromArrayBuffer(buf)))\n }\n\n close () {\n storage.offChange(this._onChange)\n }\n}\n/* c8 ignore stop */\n\n// Use BroadcastChannel or Polyfill\n/* c8 ignore next */\nconst BC = typeof BroadcastChannel === 'undefined' ? LocalStoragePolyfill : BroadcastChannel\n\n/**\n * @param {string} room\n * @return {Channel}\n */\nconst getChannel = room =>\n map.setIfUndefined(channels, room, () => {\n const subs = set.create()\n const bc = new BC(room)\n /**\n * @param {{data:ArrayBuffer}} e\n */\n /* c8 ignore next */\n bc.onmessage = e => subs.forEach(sub => sub(e.data, 'broadcastchannel'))\n return {\n bc, subs\n }\n })\n\n/**\n * Subscribe to global `publish` events.\n *\n * @function\n * @param {string} room\n * @param {function(any, any):any} f\n */\nexport const subscribe = (room, f) => {\n getChannel(room).subs.add(f)\n return f\n}\n\n/**\n * Unsubscribe from `publish` global events.\n *\n * @function\n * @param {string} room\n * @param {function(any, any):any} f\n */\nexport const unsubscribe = (room, f) => {\n const channel = getChannel(room)\n const unsubscribed = channel.subs.delete(f)\n if (unsubscribed && channel.subs.size === 0) {\n channel.bc.close()\n channels.delete(room)\n }\n return unsubscribed\n}\n\n/**\n * Publish data to all subscribers (including subscribers on this tab)\n *\n * @function\n * @param {string} room\n * @param {any} data\n * @param {any} [origin]\n */\nexport const publish = (room, data, origin = null) => {\n const c = getChannel(room)\n c.bc.postMessage(data)\n c.subs.forEach(sub => sub(data, origin))\n}\n","/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* c8 ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n","/**\n * Observable class prototype.\n *\n * @module observable\n */\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as array from './array.js'\n\n/**\n * Handles named events.\n *\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map}\n */\n this._observers = map.create()\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, name, set.create).add(f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, _f)\n f(...args)\n }\n this.on(name, _f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @param {N} name The event name.\n * @param {Array} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // 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.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n","/**\n * @module awareness-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as time from 'lib0/time'\nimport * as math from 'lib0/math'\nimport { Observable } from 'lib0/observable'\nimport * as f from 'lib0/function'\nimport * as Y from 'yjs' // eslint-disable-line\n\nexport const outdatedTimeout = 30000\n\n/**\n * @typedef {Object} MetaClientState\n * @property {number} MetaClientState.clock\n * @property {number} MetaClientState.lastUpdated unix timestamp\n */\n\n/**\n * The Awareness class implements a simple shared state protocol that can be used for non-persistent data like awareness information\n * (cursor, username, status, ..). Each client can update its own local state and listen to state changes of\n * remote clients. Every client may set a state of a remote peer to `null` to mark the client as offline.\n *\n * Each client is identified by a unique client id (something we borrow from `doc.clientID`). A client can override\n * its own state by propagating a message with an increasing timestamp (`clock`). If such a message is received, it is\n * applied if the known state of that client is older than the new state (`clock < newClock`). If a client thinks that\n * a remote client is offline, it may propagate a message with\n * `{ clock: currentClientClock, state: null, client: remoteClient }`. If such a\n * message is received, and the known clock of that client equals the received clock, it will override the state with `null`.\n *\n * Before a client disconnects, it should propagate a `null` state with an updated clock.\n *\n * Awareness states must be updated every 30 seconds. Otherwise the Awareness instance will delete the client state.\n *\n * @extends {Observable}\n */\nexport class Awareness extends Observable {\n /**\n * @param {Y.Doc} doc\n */\n constructor (doc) {\n super()\n this.doc = doc\n /**\n * @type {number}\n */\n this.clientID = doc.clientID\n /**\n * Maps from client id to client state\n * @type {Map>}\n */\n this.states = new Map()\n /**\n * @type {Map}\n */\n this.meta = new Map()\n this._checkInterval = /** @type {any} */ (setInterval(() => {\n const now = time.getUnixTime()\n if (this.getLocalState() !== null && (outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ (this.meta.get(this.clientID)).lastUpdated)) {\n // renew local clock\n this.setLocalState(this.getLocalState())\n }\n /**\n * @type {Array}\n */\n const remove = []\n this.meta.forEach((meta, clientid) => {\n if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) {\n remove.push(clientid)\n }\n })\n if (remove.length > 0) {\n removeAwarenessStates(this, remove, 'timeout')\n }\n }, math.floor(outdatedTimeout / 10)))\n doc.on('destroy', () => {\n this.destroy()\n })\n this.setLocalState({})\n }\n\n destroy () {\n this.emit('destroy', [this])\n this.setLocalState(null)\n super.destroy()\n clearInterval(this._checkInterval)\n }\n\n /**\n * @return {Object|null}\n */\n getLocalState () {\n return this.states.get(this.clientID) || null\n }\n\n /**\n * @param {Object|null} state\n */\n setLocalState (state) {\n const clientID = this.clientID\n const currLocalMeta = this.meta.get(clientID)\n const clock = currLocalMeta === undefined ? 0 : currLocalMeta.clock + 1\n const prevState = this.states.get(clientID)\n if (state === null) {\n this.states.delete(clientID)\n } else {\n this.states.set(clientID, state)\n }\n this.meta.set(clientID, {\n clock,\n lastUpdated: time.getUnixTime()\n })\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n if (state === null) {\n removed.push(clientID)\n } else if (prevState == null) {\n if (state != null) {\n added.push(clientID)\n }\n } else {\n updated.push(clientID)\n if (!f.equalityDeep(prevState, state)) {\n filteredUpdated.push(clientID)\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n this.emit('change', [{ added, updated: filteredUpdated, removed }, 'local'])\n }\n this.emit('update', [{ added, updated, removed }, 'local'])\n }\n\n /**\n * @param {string} field\n * @param {any} value\n */\n setLocalStateField (field, value) {\n const state = this.getLocalState()\n if (state !== null) {\n this.setLocalState({\n ...state,\n [field]: value\n })\n }\n }\n\n /**\n * @return {Map>}\n */\n getStates () {\n return this.states\n }\n}\n\n/**\n * Mark (remote) clients as inactive and remove them from the list of active peers.\n * This change will be propagated to remote clients.\n *\n * @param {Awareness} awareness\n * @param {Array} clients\n * @param {any} origin\n */\nexport const removeAwarenessStates = (awareness, clients, origin) => {\n const removed = []\n for (let i = 0; i < clients.length; i++) {\n const clientID = clients[i]\n if (awareness.states.has(clientID)) {\n awareness.states.delete(clientID)\n if (clientID === awareness.clientID) {\n const curMeta = /** @type {MetaClientState} */ (awareness.meta.get(clientID))\n awareness.meta.set(clientID, {\n clock: curMeta.clock + 1,\n lastUpdated: time.getUnixTime()\n })\n }\n removed.push(clientID)\n }\n }\n if (removed.length > 0) {\n awareness.emit('change', [{ added: [], updated: [], removed }, origin])\n awareness.emit('update', [{ added: [], updated: [], removed }, origin])\n }\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Array} clients\n * @return {Uint8Array}\n */\nexport const encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {\n const len = clients.length\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = clients[i]\n const state = states.get(clientID) || null\n const clock = /** @type {MetaClientState} */ (awareness.meta.get(clientID)).clock\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(state))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Modify the content of an awareness update before re-encoding it to an awareness update.\n *\n * This might be useful when you have a central server that wants to ensure that clients\n * cant hijack somebody elses identity.\n *\n * @param {Uint8Array} update\n * @param {function(any):any} modify\n * @return {Uint8Array}\n */\nexport const modifyAwarenessUpdate = (update, modify) => {\n const decoder = decoding.createDecoder(update)\n const encoder = encoding.createEncoder()\n const len = decoding.readVarUint(decoder)\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n const clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const modifiedState = modify(state)\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(modifiedState))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Uint8Array} update\n * @param {any} origin This will be added to the emitted change event\n */\nexport const applyAwarenessUpdate = (awareness, update, origin) => {\n const decoder = decoding.createDecoder(update)\n const timestamp = time.getUnixTime()\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n const len = decoding.readVarUint(decoder)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n let clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const clientMeta = awareness.meta.get(clientID)\n const prevState = awareness.states.get(clientID)\n const currClock = clientMeta === undefined ? 0 : clientMeta.clock\n if (currClock < clock || (currClock === clock && state === null && awareness.states.has(clientID))) {\n if (state === null) {\n // never let a remote client remove this local state\n if (clientID === awareness.clientID && awareness.getLocalState() != null) {\n // remote client removed the local state. Do not remote state. Broadcast a message indicating\n // that this client still exists by increasing the clock\n clock++\n } else {\n awareness.states.delete(clientID)\n }\n } else {\n awareness.states.set(clientID, state)\n }\n awareness.meta.set(clientID, {\n clock,\n lastUpdated: timestamp\n })\n if (clientMeta === undefined && state !== null) {\n added.push(clientID)\n } else if (clientMeta !== undefined && state === null) {\n removed.push(clientID)\n } else if (state !== null) {\n if (!f.equalityDeep(state, prevState)) {\n filteredUpdated.push(clientID)\n }\n updated.push(clientID)\n }\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n awareness.emit('change', [{\n added, updated: filteredUpdated, removed\n }, origin])\n }\n if (added.length > 0 || updated.length > 0 || removed.length > 0) {\n awareness.emit('update', [{\n added, updated, removed\n }, origin])\n }\n}\n","/**\n * Mutual exclude for JavaScript.\n *\n * @module mutex\n */\n\n/**\n * @callback mutex\n * @param {function():void} cb Only executed when this mutex is not in the current stack\n * @param {function():void} [elseCb] Executed when this mutex is in the current stack\n */\n\n/**\n * Creates a mutual exclude function with the following property:\n *\n * ```js\n * const mutex = createMutex()\n * mutex(() => {\n * // This function is immediately executed\n * mutex(() => {\n * // This function is not executed, as the mutex is already active.\n * })\n * })\n * ```\n *\n * @return {mutex} A mutual exclude function\n * @public\n */\nexport const createMutex = () => {\n let token = true\n return (f, g) => {\n if (token) {\n token = false\n try {\n f()\n } finally {\n token = true\n }\n } else if (g !== undefined) {\n g()\n }\n }\n}\n","export default class EventEmitter {\n\n public callbacks: { [key: string]: Function[] } = {}\n\n public on(event: string, fn: Function): this {\n if (!this.callbacks[event]) {\n this.callbacks[event] = []\n }\n\n this.callbacks[event].push(fn)\n\n return this\n }\n\n protected emit(event: string, ...args: any): this {\n const callbacks = this.callbacks[event]\n\n if (callbacks) {\n callbacks.forEach(callback => callback.apply(this, args))\n }\n\n return this\n }\n\n public off(event: string, fn?: Function): this {\n const callbacks = this.callbacks[event]\n\n if (callbacks) {\n if (fn) {\n this.callbacks[event] = callbacks.filter(callback => callback !== fn)\n } else {\n delete this.callbacks[event]\n }\n }\n\n return this\n }\n\n removeAllListeners(): void {\n this.callbacks = {}\n }\n}\n","import {\n createDecoder,\n readVarUint,\n readVarUint8Array,\n readVarString,\n Decoder,\n} from 'lib0/decoding'\nimport {\n Encoder,\n createEncoder,\n writeVarUint,\n writeVarUint8Array,\n writeVarString,\n length,\n} from 'lib0/encoding'\nimport { MessageType } from './types.js'\n\nexport class IncomingMessage {\n\n data: any\n\n encoder: Encoder\n\n decoder: Decoder\n\n constructor(data: any) {\n this.data = data\n this.encoder = createEncoder()\n this.decoder = createDecoder(new Uint8Array(this.data))\n }\n\n readVarUint(): MessageType {\n return readVarUint(this.decoder)\n }\n\n readVarString(): string {\n return readVarString(this.decoder)\n }\n\n readVarUint8Array() {\n return readVarUint8Array(this.decoder)\n }\n\n writeVarUint(type: MessageType) {\n return writeVarUint(this.encoder, type)\n }\n\n writeVarString(string: string) {\n return writeVarString(this.encoder, string)\n }\n\n writeVarUint8Array(data: Uint8Array) {\n return writeVarUint8Array(this.encoder, data)\n }\n\n length() {\n return length(this.encoder)\n }\n}\n","/**\n * @module sync-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as Y from 'yjs'\n\n/**\n * @typedef {Map} StateMap\n */\n\n/**\n * Core Yjs defines two message types:\n * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.\n * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it\n * received all information from the remote client.\n *\n * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection\n * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both\n * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.\n *\n * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.\n * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies\n * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the\n * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can\n * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them.\n * Therefore it is necesarry that the client initiates the sync.\n *\n * Construction of a message:\n * [messageType : varUint, message definition..]\n *\n * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!\n *\n * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)\n */\n\nexport const messageYjsSyncStep1 = 0\nexport const messageYjsSyncStep2 = 1\nexport const messageYjsUpdate = 2\n\n/**\n * Create a sync step 1 message based on the state of the current shared document.\n *\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n */\nexport const writeSyncStep1 = (encoder, doc) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep1)\n const sv = Y.encodeStateVector(doc)\n encoding.writeVarUint8Array(encoder, sv)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n * @param {Uint8Array} [encodedStateVector]\n */\nexport const writeSyncStep2 = (encoder, doc, encodedStateVector) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep2)\n encoding.writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector))\n}\n\n/**\n * Read SyncStep1 message and reply with SyncStep2.\n *\n * @param {decoding.Decoder} decoder The reply to the received message\n * @param {encoding.Encoder} encoder The received message\n * @param {Y.Doc} doc\n */\nexport const readSyncStep1 = (decoder, encoder, doc) =>\n writeSyncStep2(encoder, doc, decoding.readVarUint8Array(decoder))\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin) => {\n try {\n Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n } catch (error) {\n // This catches errors that are thrown by event handlers\n console.error('Caught error while handling a Yjs update', error)\n }\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Uint8Array} update\n */\nexport const writeUpdate = (encoder, update) => {\n encoding.writeVarUint(encoder, messageYjsUpdate)\n encoding.writeVarUint8Array(encoder, update)\n}\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readUpdate = readSyncStep2\n\n/**\n * @param {decoding.Decoder} decoder A message received from another client\n * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => {\n const messageType = decoding.readVarUint(decoder)\n switch (messageType) {\n case messageYjsSyncStep1:\n readSyncStep1(decoder, encoder, doc)\n break\n case messageYjsSyncStep2:\n readSyncStep2(decoder, doc, transactionOrigin)\n break\n case messageYjsUpdate:\n readUpdate(decoder, doc, transactionOrigin)\n break\n default:\n throw new Error('Unknown message type')\n }\n return messageType\n}\n","import { Awareness } from 'y-protocols/awareness'\nimport * as Y from 'yjs'\nimport { Encoder } from 'lib0/encoding'\nimport type { Event, CloseEvent, MessageEvent } from 'ws'\nimport { AuthenticationMessage } from './OutgoingMessages/AuthenticationMessage.js'\nimport { AwarenessMessage } from './OutgoingMessages/AwarenessMessage.js'\nimport { QueryAwarenessMessage } from './OutgoingMessages/QueryAwarenessMessage.js'\nimport { SyncStepOneMessage } from './OutgoingMessages/SyncStepOneMessage.js'\nimport { SyncStepTwoMessage } from './OutgoingMessages/SyncStepTwoMessage.js'\nimport { UpdateMessage } from './OutgoingMessages/UpdateMessage.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\n\nexport enum MessageType {\n Sync = 0,\n Awareness = 1,\n Auth = 2,\n QueryAwareness = 3,\n Stateless = 5,\n CLOSE = 7,\n}\n\nexport enum WebSocketStatus {\n Connecting = 'connecting',\n Connected = 'connected',\n Disconnected = 'disconnected',\n}\n\nexport interface OutgoingMessageInterface {\n encoder: Encoder\n type?: MessageType\n}\n\nexport interface OutgoingMessageArguments {\n documentName: string,\n token: string,\n document: Y.Doc,\n awareness: Awareness,\n clients: number[],\n states: Map,\n update: any,\n payload: string,\n encoder: Encoder,\n}\n\nexport interface Constructable {\n new(...args: any) : T\n}\n\nexport type ConstructableOutgoingMessage =\n Constructable |\n Constructable |\n Constructable |\n Constructable |\n Constructable |\n Constructable\n\nexport type onAuthenticationFailedParameters = {\n reason: string,\n}\n\nexport type onOpenParameters = {\n event: Event,\n}\n\nexport type onMessageParameters = {\n event: MessageEvent,\n message: IncomingMessage,\n}\n\nexport type onOutgoingMessageParameters = {\n message: OutgoingMessage,\n}\n\nexport type onStatusParameters = {\n status: WebSocketStatus,\n}\n\nexport type onSyncedParameters = {\n state: boolean,\n}\n\nexport type onDisconnectParameters = {\n event: CloseEvent,\n}\n\nexport type onCloseParameters = {\n event: CloseEvent,\n}\n\nexport type onAwarenessUpdateParameters = {\n states: StatesArray\n}\n\nexport type onAwarenessChangeParameters = {\n states: StatesArray\n}\n\nexport type onStatelessParameters = {\n payload: string\n}\n\nexport type StatesArray = { clientId: number, [key: string | number]: any }[]\n","import { Encoder, createEncoder, toUint8Array } from 'lib0/encoding'\nimport { MessageType, OutgoingMessageArguments, OutgoingMessageInterface } from './types.js'\n\nexport class OutgoingMessage implements OutgoingMessageInterface {\n encoder: Encoder\n\n type?: MessageType\n\n constructor() {\n this.encoder = createEncoder()\n }\n\n get(args: Partial) {\n return args.encoder\n }\n\n toUint8Array() {\n return toUint8Array(this.encoder)\n }\n}\n","import * as awarenessProtocol from 'y-protocols/awareness'\nimport { readSyncMessage, messageYjsSyncStep2, messageYjsUpdate } from 'y-protocols/sync'\nimport { readAuthMessage } from '@hocuspocus/common'\nimport { readVarString } from 'lib0/decoding'\nimport { MessageType } from './types.js'\nimport { HocuspocusProvider } from './HocuspocusProvider.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\n\nexport class MessageReceiver {\n\n message: IncomingMessage\n\n broadcasted = false\n\n constructor(message: IncomingMessage) {\n this.message = message\n }\n\n public setBroadcasted(value: boolean) {\n this.broadcasted = value\n\n return this\n }\n\n public apply(provider: HocuspocusProvider, emitSynced = true) {\n const { message } = this\n const type = message.readVarUint()\n\n const emptyMessageLength = message.length()\n\n switch (type) {\n case MessageType.Sync:\n this.applySyncMessage(provider, emitSynced)\n break\n\n case MessageType.Awareness:\n this.applyAwarenessMessage(provider)\n break\n\n case MessageType.Auth:\n this.applyAuthMessage(provider)\n break\n\n case MessageType.QueryAwareness:\n this.applyQueryAwarenessMessage(provider)\n break\n\n case MessageType.Stateless:\n provider.receiveStateless(readVarString(message.decoder))\n break\n\n default:\n throw new Error(`Can’t apply message of unknown type: ${type}`)\n }\n\n // Reply\n if (message.length() > emptyMessageLength + 1) { // length of documentName (considered in emptyMessageLength plus length of yjs sync type, set in applySyncMessage)\n if (this.broadcasted) {\n // TODO: Some weird TypeScript error\n // @ts-ignore\n provider.broadcast(OutgoingMessage, { encoder: message.encoder })\n } else {\n // TODO: Some weird TypeScript error\n // @ts-ignore\n provider.send(OutgoingMessage, { encoder: message.encoder })\n }\n }\n }\n\n private applySyncMessage(provider: HocuspocusProvider, emitSynced: boolean) {\n const { message } = this\n\n message.writeVarUint(MessageType.Sync)\n\n // Apply update\n const syncMessageType = readSyncMessage(\n message.decoder,\n message.encoder,\n provider.document,\n provider,\n )\n\n // Synced once we receive Step2\n if (emitSynced && syncMessageType === messageYjsSyncStep2) {\n provider.synced = true\n }\n\n if (syncMessageType === messageYjsUpdate || syncMessageType === messageYjsSyncStep2) {\n if (provider.unsyncedChanges > 0) {\n provider.updateUnsyncedChanges(-1)\n }\n }\n }\n\n private applyAwarenessMessage(provider: HocuspocusProvider) {\n const { message } = this\n\n awarenessProtocol.applyAwarenessUpdate(\n provider.awareness,\n message.readVarUint8Array(),\n provider,\n )\n }\n\n private applyAuthMessage(provider: HocuspocusProvider) {\n const { message } = this\n\n readAuthMessage(\n message.decoder,\n provider.permissionDeniedHandler.bind(provider),\n provider.authenticatedHandler.bind(provider),\n )\n }\n\n private applyQueryAwarenessMessage(provider: HocuspocusProvider) {\n const { message } = this\n\n message.writeVarUint(MessageType.Awareness)\n message.writeVarUint8Array(\n awarenessProtocol.encodeAwarenessUpdate(\n provider.awareness,\n Array.from(provider.awareness.getStates().keys()),\n ),\n )\n }\n}\n","import { Encoder, toUint8Array } from 'lib0/encoding'\nimport * as bc from 'lib0/broadcastchannel'\nimport { ConstructableOutgoingMessage } from './types.js'\n\nexport class MessageSender {\n\n encoder: Encoder\n\n message: any\n\n constructor(Message: ConstructableOutgoingMessage, args: any = {}) {\n this.message = new Message()\n this.encoder = this.message.get(args)\n }\n\n create() {\n return toUint8Array(this.encoder)\n }\n\n send(webSocket: any) {\n webSocket?.send(this.create())\n }\n\n broadcast(channel: string) {\n bc.publish(channel, this.create())\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport * as syncProtocol from 'y-protocols/sync'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class SyncStepOneMessage extends OutgoingMessage {\n type = MessageType.Sync\n\n description = 'First sync step'\n\n get(args: Partial) {\n if (typeof args.document === 'undefined') {\n throw new Error('The sync step one message requires document as an argument')\n }\n\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n syncProtocol.writeSyncStep1(this.encoder, args.document)\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport * as syncProtocol from 'y-protocols/sync'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class SyncStepTwoMessage extends OutgoingMessage {\n type = MessageType.Sync\n\n description = 'Second sync step'\n\n get(args: Partial) {\n if (typeof args.document === 'undefined') {\n throw new Error('The sync step two message requires document as an argument')\n }\n\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n syncProtocol.writeSyncStep2(this.encoder, args.document)\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class QueryAwarenessMessage extends OutgoingMessage {\n type = MessageType.QueryAwareness\n\n description = 'Queries awareness states'\n\n get(args: Partial) {\n\n console.log('queryAwareness: writing string docName', args.documentName)\n console.log(this.encoder.cpos)\n\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n\n return this.encoder\n }\n}\n","import { writeVarString, writeVarUint } from 'lib0/encoding'\nimport { writeAuthentication } from '@hocuspocus/common'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class AuthenticationMessage extends OutgoingMessage {\n type = MessageType.Auth\n\n description = 'Authentication'\n\n get(args: Partial) {\n if (typeof args.token === 'undefined') {\n throw new Error('The authentication message requires `token` as an argument.')\n }\n\n writeVarString(this.encoder, args.documentName!)\n writeVarUint(this.encoder, this.type)\n writeAuthentication(this.encoder, args.token)\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport { encodeAwarenessUpdate } from 'y-protocols/awareness'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class AwarenessMessage extends OutgoingMessage {\n type = MessageType.Awareness\n\n description = 'Awareness states update'\n\n get(args: Partial) {\n if (typeof args.awareness === 'undefined') {\n throw new Error('The awareness message requires awareness as an argument')\n }\n\n if (typeof args.clients === 'undefined') {\n throw new Error('The awareness message requires clients as an argument')\n }\n\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n\n let awarenessUpdate\n if (args.states === undefined) {\n awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients)\n } else {\n awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients, args.states)\n }\n\n encoding.writeVarUint8Array(this.encoder, awarenessUpdate)\n\n return this.encoder\n }\n}\n","import { writeVarString, writeVarUint } from 'lib0/encoding'\nimport { writeUpdate } from 'y-protocols/sync'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class UpdateMessage extends OutgoingMessage {\n type = MessageType.Sync\n\n description = 'A document update'\n\n get(args: Partial) {\n writeVarString(this.encoder, args.documentName!)\n writeVarUint(this.encoder, this.type)\n\n writeUpdate(this.encoder, args.update)\n\n return this.encoder\n }\n}\n","/**\n * Utility module to work with urls.\n *\n * @module url\n */\n\nimport * as object from './object.js'\n\n/**\n * Parse query parameters from an url.\n *\n * @param {string} url\n * @return {Object}\n */\nexport const decodeQueryParams = url => {\n /**\n * @type {Object}\n */\n const query = {}\n const urlQuerySplit = url.split('?')\n const pairs = urlQuerySplit[urlQuerySplit.length - 1].split('&')\n for (let i = 0; i < pairs.length; i++) {\n const item = pairs[i]\n if (item.length > 0) {\n const pair = item.split('=')\n query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '')\n }\n }\n return query\n}\n\n/**\n * @param {Object} params\n * @return {string}\n */\nexport const encodeQueryParams = params =>\n object.map(params, (val, key) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&')\n","import * as time from 'lib0/time'\nimport * as mutex from 'lib0/mutex'\nimport * as url from 'lib0/url'\nimport type { MessageEvent } from 'ws'\nimport { retry } from '@lifeomic/attempt'\nimport {\n Forbidden, MessageTooBig, Unauthorized, WsReadyStates,\n} from '@hocuspocus/common'\nimport { Event } from 'ws'\nimport EventEmitter from './EventEmitter.js'\nimport {\n onCloseParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onStatusParameters, WebSocketStatus,\n onAwarenessChangeParameters, onAwarenessUpdateParameters,\n} from './types.js'\nimport { HocuspocusProvider } from './HocuspocusProvider.js'\n\nexport type HocuspocusProviderWebsocketConfiguration =\n Required>\n & Partial\n\nexport interface CompleteHocuspocusProviderWebsocketConfiguration {\n /**\n * URL of your @hocuspocus/server instance\n */\n url: string,\n\n /**\n * Pass `false` to start the connection manually.\n */\n connect: boolean,\n\n /**\n * URL parameters that should be added.\n */\n parameters: { [key: string]: any },\n /**\n * An optional WebSocket polyfill, for example for Node.js\n */\n WebSocketPolyfill: any,\n\n /**\n * Disconnect when no message is received for the defined amount of milliseconds.\n */\n messageReconnectTimeout: number,\n /**\n * The delay between each attempt in milliseconds. You can provide a factor to have the delay grow exponentially.\n */\n delay: number,\n /**\n * The intialDelay is the amount of time to wait before making the first attempt. This option should typically be 0 since you typically want the first attempt to happen immediately.\n */\n initialDelay: number,\n /**\n * The factor option is used to grow the delay exponentially.\n */\n factor: number,\n /**\n * The maximum number of attempts or 0 if there is no limit on number of attempts.\n */\n maxAttempts: number,\n /**\n * minDelay is used to set a lower bound of delay when jitter is enabled. This property has no effect if jitter is disabled.\n */\n minDelay: number,\n /**\n * The maxDelay option is used to set an upper bound for the delay when factor is enabled. A value of 0 can be provided if there should be no upper bound when calculating delay.\n */\n maxDelay: number,\n /**\n * If jitter is true then the calculated delay will be a random integer value between minDelay and the calculated delay for the current iteration.\n */\n jitter: boolean,\n /**\n * A timeout in milliseconds. If timeout is non-zero then a timer is set using setTimeout. If the timeout is triggered then future attempts will be aborted.\n */\n timeout: number,\n onOpen: (data: onOpenParameters) => void,\n onConnect: () => void,\n onMessage: (data: onMessageParameters) => void,\n onOutgoingMessage: (data: onOutgoingMessageParameters) => void,\n onStatus: (data: onStatusParameters) => void,\n onDisconnect: (data: onDisconnectParameters) => void,\n onClose: (data: onCloseParameters) => void,\n onDestroy: () => void,\n onAwarenessUpdate: (data: onAwarenessUpdateParameters) => void,\n onAwarenessChange: (data: onAwarenessChangeParameters) => void,\n /**\n * Don’t output any warnings.\n */\n quiet: boolean,\n}\n\nexport class HocuspocusProviderWebsocket extends EventEmitter {\n public configuration: CompleteHocuspocusProviderWebsocketConfiguration = {\n url: '',\n // @ts-ignore\n document: undefined,\n // @ts-ignore\n awareness: undefined,\n WebSocketPolyfill: undefined,\n parameters: {},\n connect: true,\n broadcast: true,\n forceSyncInterval: false,\n // TODO: this should depend on awareness.outdatedTime\n messageReconnectTimeout: 30000,\n // 1 second\n delay: 1000,\n // instant\n initialDelay: 0,\n // double the delay each time\n factor: 2,\n // unlimited retries\n maxAttempts: 0,\n // wait at least 1 second\n minDelay: 1000,\n // at least every 30 seconds\n maxDelay: 30000,\n // randomize\n jitter: true,\n // retry forever\n timeout: 0,\n onOpen: () => null,\n onConnect: () => null,\n onMessage: () => null,\n onOutgoingMessage: () => null,\n onStatus: () => null,\n onDisconnect: () => null,\n onClose: () => null,\n onDestroy: () => null,\n onAwarenessUpdate: () => null,\n onAwarenessChange: () => null,\n quiet: false,\n }\n\n subscribedToBroadcastChannel = false\n\n webSocket: WebSocket | null = null\n\n shouldConnect = true\n\n status = WebSocketStatus.Disconnected\n\n lastMessageReceived = 0\n\n mux = mutex.createMutex()\n\n intervals: any = {\n forceSync: null,\n connectionChecker: null,\n }\n\n connectionAttempt: {\n resolve: (value?: any) => void\n reject: (reason?: any) => void\n } | null = null\n\n constructor(configuration: HocuspocusProviderWebsocketConfiguration) {\n super()\n this.setConfiguration(configuration)\n\n this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill ? configuration.WebSocketPolyfill : WebSocket\n\n this.on('open', this.configuration.onOpen)\n this.on('open', this.onOpen.bind(this))\n this.on('connect', this.configuration.onConnect)\n this.on('message', this.configuration.onMessage)\n this.on('outgoingMessage', this.configuration.onOutgoingMessage)\n this.on('status', this.configuration.onStatus)\n this.on('status', this.onStatus.bind(this))\n this.on('disconnect', this.configuration.onDisconnect)\n this.on('close', this.configuration.onClose)\n this.on('destroy', this.configuration.onDestroy)\n this.on('awarenessUpdate', this.configuration.onAwarenessUpdate)\n this.on('awarenessChange', this.configuration.onAwarenessChange)\n\n this.on('close', this.onClose.bind(this))\n this.on('message', this.onMessage.bind(this))\n\n this.registerEventListeners()\n\n this.intervals.connectionChecker = setInterval(\n this.checkConnection.bind(this),\n this.configuration.messageReconnectTimeout / 10,\n )\n\n if (typeof configuration.connect !== 'undefined') {\n this.shouldConnect = configuration.connect\n }\n\n if (!this.shouldConnect) {\n return\n }\n\n this.connect()\n }\n\n receivedOnOpenPayload?: Event | undefined = undefined\n\n receivedOnStatusPayload?: onStatusParameters | undefined = undefined\n\n async onOpen(event: Event) {\n this.receivedOnOpenPayload = event\n }\n\n async onStatus(data: onStatusParameters) {\n this.receivedOnStatusPayload = data\n }\n\n attach(provider: HocuspocusProvider) {\n if (this.receivedOnOpenPayload) {\n provider.onOpen(this.receivedOnOpenPayload)\n }\n\n if (this.receivedOnStatusPayload) {\n provider.onStatus(this.receivedOnStatusPayload)\n }\n }\n\n detach(provider: HocuspocusProvider) {\n // tell the server to remove the listener\n\n }\n\n public setConfiguration(configuration: Partial = {}): void {\n this.configuration = { ...this.configuration, ...configuration }\n }\n\n boundConnect = this.connect.bind(this)\n\n cancelWebsocketRetry?: () => void\n\n async connect() {\n if (this.status === WebSocketStatus.Connected) {\n return\n }\n\n // Always cancel any previously initiated connection retryer instances\n if (this.cancelWebsocketRetry) {\n this.cancelWebsocketRetry()\n this.cancelWebsocketRetry = undefined\n }\n\n this.shouldConnect = true\n\n const abortableRetry = () => {\n let cancelAttempt = false\n\n const retryPromise = retry(this.createWebSocketConnection.bind(this), {\n delay: this.configuration.delay,\n initialDelay: this.configuration.initialDelay,\n factor: this.configuration.factor,\n maxAttempts: this.configuration.maxAttempts,\n minDelay: this.configuration.minDelay,\n maxDelay: this.configuration.maxDelay,\n jitter: this.configuration.jitter,\n timeout: this.configuration.timeout,\n beforeAttempt: context => {\n if (!this.shouldConnect || cancelAttempt) {\n context.abort()\n }\n },\n }).catch((error: any) => {\n // If we aborted the connection attempt then don’t throw an error\n // ref: https://github.com/lifeomic/attempt/blob/master/src/index.ts#L136\n if (error && error.code !== 'ATTEMPT_ABORTED') {\n throw error\n }\n })\n\n return {\n retryPromise,\n cancelFunc: () => {\n cancelAttempt = true\n },\n }\n }\n\n const { retryPromise, cancelFunc } = abortableRetry()\n this.cancelWebsocketRetry = cancelFunc\n\n return retryPromise\n }\n\n createWebSocketConnection() {\n return new Promise((resolve, reject) => {\n if (this.webSocket) {\n this.webSocket.close()\n this.webSocket = null\n }\n\n // Init the WebSocket connection\n const ws = new this.configuration.WebSocketPolyfill(this.url)\n ws.binaryType = 'arraybuffer'\n ws.onmessage = (payload: any) => this.emit('message', payload)\n ws.onclose = (payload: any) => this.emit('close', { event: payload })\n ws.onopen = (payload: any) => this.emit('open', payload)\n ws.onerror = (err: any) => {\n reject(err)\n }\n this.webSocket = ws\n\n // Reset the status\n this.status = WebSocketStatus.Connecting\n this.emit('status', { status: WebSocketStatus.Connecting })\n\n // Store resolve/reject for later use\n this.connectionAttempt = {\n resolve,\n reject,\n }\n })\n }\n\n onMessage(event: MessageEvent) {\n this.resolveConnectionAttempt()\n }\n\n resolveConnectionAttempt() {\n if (this.connectionAttempt) {\n this.connectionAttempt.resolve()\n this.connectionAttempt = null\n\n this.status = WebSocketStatus.Connected\n this.emit('status', { status: WebSocketStatus.Connected })\n this.emit('connect')\n }\n }\n\n stopConnectionAttempt() {\n this.connectionAttempt = null\n }\n\n rejectConnectionAttempt() {\n this.connectionAttempt?.reject()\n this.connectionAttempt = null\n }\n\n checkConnection() {\n // Don’t check the connection when it’s not even established\n if (this.status !== WebSocketStatus.Connected) {\n return\n }\n\n // Don’t close then connection while waiting for the first message\n if (!this.lastMessageReceived) {\n return\n }\n\n // Don’t close the connection when a message was received recently\n if (this.configuration.messageReconnectTimeout >= time.getUnixTime() - this.lastMessageReceived) {\n return\n }\n\n // No message received in a long time, not even your own\n // Awareness updates, which are updated every 15 seconds.\n this.webSocket?.close()\n }\n\n registerEventListeners() {\n if (typeof window === 'undefined') {\n return\n }\n\n window.addEventListener('online', this.boundConnect)\n }\n\n // Ensure that the URL always ends with /\n get serverUrl() {\n while (this.configuration.url[this.configuration.url.length - 1] === '/') {\n return this.configuration.url.slice(0, this.configuration.url.length - 1)\n }\n\n return this.configuration.url\n }\n\n get url() {\n const encodedParams = url.encodeQueryParams(this.configuration.parameters)\n\n return `${this.serverUrl}${encodedParams.length === 0 ? '' : `?${encodedParams}`}`\n }\n\n disconnect() {\n this.shouldConnect = false\n\n if (this.webSocket === null) {\n return\n }\n\n try {\n this.webSocket.close()\n } catch {\n //\n }\n }\n\n send(message: any) {\n if (this.webSocket?.readyState === WsReadyStates.Open) {\n this.webSocket.send(message)\n }\n }\n\n onClose({ event }: onCloseParameters) {\n this.webSocket = null\n\n if (this.status === WebSocketStatus.Connected) {\n this.status = WebSocketStatus.Disconnected\n this.emit('status', { status: WebSocketStatus.Disconnected })\n this.emit('disconnect', { event })\n }\n\n if (event.code === Unauthorized.code) {\n if (event.reason === Unauthorized.reason) {\n console.warn('[HocuspocusProvider] An authentication token is required, but you didn’t send one. Try adding a `token` to your HocuspocusProvider configuration. Won’t try again.')\n } else {\n console.warn(`[HocuspocusProvider] Connection closed with status Unauthorized: ${event.reason}`)\n }\n\n this.shouldConnect = false\n }\n\n if (event.code === Forbidden.code) {\n if (!this.configuration.quiet) {\n console.warn('[HocuspocusProvider] The provided authentication token isn’t allowed to connect to this server. Will try again.')\n return // TODO REMOVE ME\n }\n }\n\n if (event.code === MessageTooBig.code) {\n console.warn(`[HocuspocusProvider] Connection closed with status MessageTooBig: ${event.reason}`)\n this.shouldConnect = false\n }\n\n if (this.connectionAttempt) {\n // That connection attempt failed.\n this.rejectConnectionAttempt()\n } else if (this.shouldConnect) {\n // The connection was closed by the server. Let’s just try again.\n this.connect()\n }\n\n // If we’ll reconnect, we’re done for now.\n if (this.shouldConnect) {\n return\n }\n\n // The status is set correctly already.\n if (this.status === WebSocketStatus.Disconnected) {\n return\n }\n\n // Let’s update the connection status.\n this.status = WebSocketStatus.Disconnected\n this.emit('status', { status: WebSocketStatus.Disconnected })\n this.emit('disconnect', { event })\n }\n\n destroy() {\n this.emit('destroy')\n\n if (this.intervals.forceSync) {\n clearInterval(this.intervals.forceSync)\n }\n\n clearInterval(this.intervals.connectionChecker)\n\n // If there is still a connection attempt outstanding then we should stop\n // it before calling disconnect, otherwise it will be rejected in the onClose\n // handler and trigger a retry\n this.stopConnectionAttempt()\n\n this.disconnect()\n\n this.removeAllListeners()\n\n if (typeof window === 'undefined') {\n return\n }\n\n window.removeEventListener('online', this.boundConnect)\n }\n\n}\n","import { writeVarString, writeVarUint } from 'lib0/encoding'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class StatelessMessage extends OutgoingMessage {\n type = MessageType.Stateless\n\n description = 'A stateless message'\n\n get(args: Partial) {\n writeVarString(this.encoder, args.documentName!)\n writeVarUint(this.encoder, this.type)\n writeVarString(this.encoder, args.payload ?? '')\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class CloseMessage extends OutgoingMessage {\n type = MessageType.CLOSE\n\n description = 'Ask the server to close the connection'\n\n get(args: Partial) {\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n\n return this.encoder\n }\n}\n","import * as Y from 'yjs'\nimport * as bc from 'lib0/broadcastchannel'\nimport { Awareness, removeAwarenessStates } from 'y-protocols/awareness'\nimport * as mutex from 'lib0/mutex'\nimport type { CloseEvent, Event, MessageEvent } from 'ws'\nimport { awarenessStatesToArray } from '@hocuspocus/common'\nimport EventEmitter from './EventEmitter.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { MessageReceiver } from './MessageReceiver.js'\nimport { MessageSender } from './MessageSender.js'\nimport { SyncStepOneMessage } from './OutgoingMessages/SyncStepOneMessage.js'\nimport { SyncStepTwoMessage } from './OutgoingMessages/SyncStepTwoMessage.js'\nimport { QueryAwarenessMessage } from './OutgoingMessages/QueryAwarenessMessage.js'\nimport { AuthenticationMessage } from './OutgoingMessages/AuthenticationMessage.js'\nimport { AwarenessMessage } from './OutgoingMessages/AwarenessMessage.js'\nimport { UpdateMessage } from './OutgoingMessages/UpdateMessage.js'\nimport {\n ConstructableOutgoingMessage,\n onAuthenticationFailedParameters,\n onCloseParameters,\n onDisconnectParameters,\n onMessageParameters,\n onOpenParameters,\n onOutgoingMessageParameters, onStatelessParameters,\n onStatusParameters,\n onSyncedParameters,\n WebSocketStatus,\n onAwarenessChangeParameters,\n onAwarenessUpdateParameters,\n} from './types.js'\nimport {\n CompleteHocuspocusProviderWebsocketConfiguration,\n HocuspocusProviderWebsocket,\n} from './HocuspocusProviderWebsocket.js'\nimport { StatelessMessage } from './OutgoingMessages/StatelessMessage.js'\nimport { CloseMessage } from './OutgoingMessages/CloseMessage.js'\n\nexport type HocuspocusProviderConfiguration =\n Required>\n & Partial & (\n Required> |\n Required>\n )\n\nexport interface CompleteHocuspocusProviderConfiguration {\n /**\n * The identifier/name of your document\n */\n name: string,\n /**\n * The actual Y.js document\n */\n document: Y.Doc,\n\n /**\n * Pass false to disable broadcasting between browser tabs.\n */\n broadcast: boolean,\n /**\n * An Awareness instance to keep the presence state of all clients.\n */\n awareness: Awareness,\n /**\n * A token that’s sent to the backend for authentication purposes.\n */\n token: string | (() => string) | (() => Promise) | null,\n /**\n * URL parameters that should be added.\n */\n parameters: { [key: string]: any },\n /**\n * Hocuspocus websocket provider\n */\n websocketProvider: HocuspocusProviderWebsocket,\n /**\n * Force syncing the document in the defined interval.\n */\n forceSyncInterval: false | number,\n\n onAuthenticated: () => void,\n onAuthenticationFailed: (data: onAuthenticationFailedParameters) => void,\n onOpen: (data: onOpenParameters) => void,\n onConnect: () => void,\n onMessage: (data: onMessageParameters) => void,\n onOutgoingMessage: (data: onOutgoingMessageParameters) => void,\n onStatus: (data: onStatusParameters) => void,\n onSynced: (data: onSyncedParameters) => void,\n onDisconnect: (data: onDisconnectParameters) => void,\n onClose: (data: onCloseParameters) => void,\n onDestroy: () => void,\n onAwarenessUpdate: (data: onAwarenessUpdateParameters) => void,\n onAwarenessChange: (data: onAwarenessChangeParameters) => void,\n onStateless: (data: onStatelessParameters) => void\n\n /**\n * Don’t output any warnings.\n */\n quiet: boolean,\n}\n\nexport class HocuspocusProvider extends EventEmitter {\n public configuration: CompleteHocuspocusProviderConfiguration = {\n name: '',\n // @ts-ignore\n document: undefined,\n // @ts-ignore\n awareness: undefined,\n token: null,\n parameters: {},\n broadcast: true,\n forceSyncInterval: false,\n onAuthenticated: () => null,\n onAuthenticationFailed: () => null,\n onOpen: () => null,\n onConnect: () => null,\n onMessage: () => null,\n onOutgoingMessage: () => null,\n onStatus: () => null,\n onSynced: () => null,\n onDisconnect: () => null,\n onClose: () => null,\n onDestroy: () => null,\n onAwarenessUpdate: () => null,\n onAwarenessChange: () => null,\n onStateless: () => null,\n quiet: false,\n }\n\n subscribedToBroadcastChannel = false\n\n isSynced = false\n\n unsyncedChanges = 0\n\n status = WebSocketStatus.Disconnected\n\n isAuthenticated = false\n\n authorizedScope: string | undefined = undefined\n\n mux = mutex.createMutex()\n\n intervals: any = {\n forceSync: null,\n }\n\n isConnected = true\n\n constructor(configuration: HocuspocusProviderConfiguration) {\n super()\n this.setConfiguration(configuration)\n\n this.configuration.document = configuration.document ? configuration.document : new Y.Doc()\n this.configuration.awareness = configuration.awareness ? configuration.awareness : new Awareness(this.document)\n\n this.on('open', this.configuration.onOpen)\n this.on('message', this.configuration.onMessage)\n this.on('outgoingMessage', this.configuration.onOutgoingMessage)\n this.on('synced', this.configuration.onSynced)\n this.on('destroy', this.configuration.onDestroy)\n this.on('awarenessUpdate', this.configuration.onAwarenessUpdate)\n this.on('awarenessChange', this.configuration.onAwarenessChange)\n this.on('stateless', this.configuration.onStateless)\n\n this.on('authenticated', this.configuration.onAuthenticated)\n this.on('authenticationFailed', this.configuration.onAuthenticationFailed)\n\n this.configuration.websocketProvider.on('connect', this.configuration.onConnect)\n this.configuration.websocketProvider.on('connect', (e: Event) => this.emit('connect', e))\n\n this.configuration.websocketProvider.on('open', this.onOpen.bind(this))\n this.configuration.websocketProvider.on('open', (e: Event) => this.emit('open', e))\n\n this.configuration.websocketProvider.on('message', this.onMessage.bind(this))\n\n this.configuration.websocketProvider.on('close', this.onClose.bind(this))\n this.configuration.websocketProvider.on('close', this.configuration.onClose)\n this.configuration.websocketProvider.on('close', (e: Event) => this.emit('close', e))\n\n this.configuration.websocketProvider.on('status', this.onStatus.bind(this))\n\n this.configuration.websocketProvider.on('disconnect', this.configuration.onDisconnect)\n this.configuration.websocketProvider.on('disconnect', (e: Event) => this.emit('disconnect', e))\n\n this.configuration.websocketProvider.on('destroy', this.configuration.onDestroy)\n this.configuration.websocketProvider.on('destroy', (e: Event) => this.emit('destroy', e))\n\n this.awareness.on('update', () => {\n this.emit('awarenessUpdate', { states: awarenessStatesToArray(this.awareness.getStates()) })\n })\n\n this.awareness.on('change', () => {\n this.emit('awarenessChange', { states: awarenessStatesToArray(this.awareness.getStates()) })\n })\n\n this.document.on('update', this.documentUpdateHandler.bind(this))\n this.awareness.on('update', this.awarenessUpdateHandler.bind(this))\n this.registerEventListeners()\n\n if (this.configuration.forceSyncInterval) {\n this.intervals.forceSync = setInterval(\n this.forceSync.bind(this),\n this.configuration.forceSyncInterval,\n )\n }\n\n this.configuration.websocketProvider.attach(this)\n }\n\n public onStatus({ status } : onStatusParameters) {\n this.status = status\n\n this.configuration.onStatus({ status })\n this.emit('status', { status })\n }\n\n public setConfiguration(configuration: Partial = {}): void {\n if (!configuration.websocketProvider && (configuration as CompleteHocuspocusProviderWebsocketConfiguration).url) {\n const websocketProviderConfig = configuration as CompleteHocuspocusProviderWebsocketConfiguration\n\n this.configuration.websocketProvider = new HocuspocusProviderWebsocket({\n url: websocketProviderConfig.url,\n parameters: websocketProviderConfig.parameters,\n })\n }\n\n this.configuration = { ...this.configuration, ...configuration }\n }\n\n get document() {\n return this.configuration.document\n }\n\n get awareness() {\n return this.configuration.awareness\n }\n\n get hasUnsyncedChanges(): boolean {\n return this.unsyncedChanges > 0\n }\n\n updateUnsyncedChanges(unsyncedChanges = 0) {\n this.unsyncedChanges += unsyncedChanges\n this.emit('unsyncedChanges', this.unsyncedChanges)\n }\n\n forceSync() {\n this.send(SyncStepOneMessage, { document: this.document, documentName: this.configuration.name })\n }\n\n boundBeforeUnload = this.beforeUnload.bind(this)\n\n beforeUnload() {\n removeAwarenessStates(this.awareness, [this.document.clientID], 'window unload')\n }\n\n registerEventListeners() {\n if (typeof window === 'undefined') {\n return\n }\n\n window.addEventListener('beforeunload', this.boundBeforeUnload)\n }\n\n sendStateless(payload: string) {\n this.send(StatelessMessage, { documentName: this.configuration.name, payload })\n }\n\n documentUpdateHandler(update: Uint8Array, origin: any) {\n if (origin === this) {\n return\n }\n\n this.updateUnsyncedChanges(1)\n this.send(UpdateMessage, { update, documentName: this.configuration.name }, true)\n }\n\n awarenessUpdateHandler({ added, updated, removed }: any, origin: any) {\n const changedClients = added.concat(updated).concat(removed)\n\n this.send(AwarenessMessage, {\n awareness: this.awareness,\n clients: changedClients,\n documentName: this.configuration.name,\n }, true)\n }\n\n get synced(): boolean {\n return this.isSynced\n }\n\n set synced(state) {\n if (this.isSynced === state) {\n return\n }\n\n if (state && this.unsyncedChanges > 0) {\n this.updateUnsyncedChanges(-1 * this.unsyncedChanges)\n }\n\n this.isSynced = state\n this.emit('synced', { state })\n this.emit('sync', { state })\n }\n\n receiveStateless(payload: string) {\n this.emit('stateless', { payload })\n }\n\n get isAuthenticationRequired(): boolean {\n return !!this.configuration.token && !this.isAuthenticated\n }\n\n // not needed, but provides backward compatibility with e.g. lexicla/yjs\n async connect() {\n return this.configuration.websocketProvider.connect()\n }\n\n disconnect() {\n this.disconnectBroadcastChannel()\n this.configuration.websocketProvider.detach(this)\n }\n\n async onOpen(event: Event) {\n this.isAuthenticated = false\n\n this.emit('open', { event })\n\n if (this.isAuthenticationRequired) {\n this.send(AuthenticationMessage, {\n token: await this.getToken(),\n documentName: this.configuration.name,\n })\n }\n\n this.startSync()\n }\n\n async getToken() {\n if (typeof this.configuration.token === 'function') {\n const token = await this.configuration.token()\n return token\n }\n\n return this.configuration.token\n }\n\n startSync() {\n this.send(SyncStepOneMessage, { document: this.document, documentName: this.configuration.name })\n\n if (this.awareness.getLocalState() !== null) {\n this.send(AwarenessMessage, {\n awareness: this.awareness,\n clients: [this.document.clientID],\n documentName: this.configuration.name,\n })\n }\n }\n\n send(message: ConstructableOutgoingMessage, args: any, broadcast = false) {\n if (!this.isConnected) return\n\n if (broadcast) {\n this.mux(() => { this.broadcast(message, args) })\n }\n\n const messageSender = new MessageSender(message, args)\n\n this.emit('outgoingMessage', { message: messageSender.message })\n messageSender.send(this.configuration.websocketProvider)\n }\n\n onMessage(event: MessageEvent) {\n const message = new IncomingMessage(event.data)\n\n const documentName = message.readVarString()\n\n if (documentName !== this.configuration.name) {\n return // message is meant for another provider\n }\n\n message.writeVarString(documentName)\n\n this.emit('message', { event, message: new IncomingMessage(event.data) })\n\n new MessageReceiver(message).apply(this)\n }\n\n onClose(event: CloseEvent) {\n this.isAuthenticated = false\n this.synced = false\n\n // update awareness (all users except local left)\n removeAwarenessStates(\n this.awareness,\n Array.from(this.awareness.getStates().keys()).filter(client => client !== this.document.clientID),\n this,\n )\n }\n\n destroy() {\n this.emit('destroy')\n\n if (this.intervals.forceSync) {\n clearInterval(this.intervals.forceSync)\n }\n\n removeAwarenessStates(this.awareness, [this.document.clientID], 'provider destroy')\n\n this.disconnect()\n\n this.awareness.off('update', this.awarenessUpdateHandler)\n this.document.off('update', this.documentUpdateHandler)\n\n this.removeAllListeners()\n\n this.send(CloseMessage, { documentName: this.configuration.name })\n this.isConnected = false\n\n if (typeof window === 'undefined') {\n return\n }\n\n window.removeEventListener('beforeunload', this.boundBeforeUnload)\n }\n\n permissionDeniedHandler(reason: string) {\n this.emit('authenticationFailed', { reason })\n this.isAuthenticated = false\n this.disconnect()\n this.status = WebSocketStatus.Disconnected\n }\n\n authenticatedHandler(scope: string) {\n this.isAuthenticated = true\n this.authorizedScope = scope\n\n this.emit('authenticated')\n this.startSync()\n }\n\n get broadcastChannel() {\n return `${this.configuration.name}`\n }\n\n boundBroadcastChannelSubscriber = this.broadcastChannelSubscriber.bind(this)\n\n broadcastChannelSubscriber(data: ArrayBuffer) {\n this.mux(() => {\n const message = new IncomingMessage(data)\n\n const documentName = message.readVarString()\n\n message.writeVarString(documentName)\n\n new MessageReceiver(message)\n .setBroadcasted(true)\n .apply(this, false)\n })\n }\n\n subscribeToBroadcastChannel() {\n if (!this.subscribedToBroadcastChannel) {\n bc.subscribe(this.broadcastChannel, this.boundBroadcastChannelSubscriber)\n this.subscribedToBroadcastChannel = true\n }\n\n this.mux(() => {\n this.broadcast(SyncStepOneMessage, { document: this.document })\n this.broadcast(SyncStepTwoMessage, { document: this.document })\n this.broadcast(QueryAwarenessMessage, { document: this.document })\n this.broadcast(AwarenessMessage, { awareness: this.awareness, clients: [this.document.clientID], document: this.document })\n })\n }\n\n disconnectBroadcastChannel() {\n // broadcast message with local awareness state set to null (indicating disconnect)\n this.send(AwarenessMessage, {\n awareness: this.awareness,\n clients: [this.document.clientID],\n states: new Map(),\n documentName: this.configuration.name,\n }, true)\n\n if (this.subscribedToBroadcastChannel) {\n bc.unsubscribe(this.broadcastChannel, this.boundBroadcastChannelSubscriber)\n this.subscribedToBroadcastChannel = false\n }\n }\n\n broadcast(Message: ConstructableOutgoingMessage, args?: any) {\n if (!this.configuration.broadcast) {\n return\n }\n\n if (!this.subscribedToBroadcastChannel) {\n return\n }\n\n new MessageSender(Message, args).broadcast(this.broadcastChannel)\n }\n\n setAwarenessField(key: string, value: any) {\n this.awareness.setLocalStateField(key, value)\n }\n}\n","import {\n CompleteHocuspocusProviderWebsocketConfiguration,\n HocuspocusProviderWebsocket, HocuspocusProviderWebsocketConfiguration,\n} from './HocuspocusProviderWebsocket.js'\n\nexport type TiptapCollabProviderWebsocketConfiguration =\n Partial &\n AdditionalTiptapCollabProviderWebsocketConfiguration\n\nexport interface AdditionalTiptapCollabProviderWebsocketConfiguration {\n /**\n * A Hocuspocus Cloud App ID, get one here: https://collab.tiptap.dev\n */\n appId: string,\n}\n\nexport class TiptapCollabProviderWebsocket extends HocuspocusProviderWebsocket {\n constructor(configuration: TiptapCollabProviderWebsocketConfiguration) {\n super({ ...configuration as HocuspocusProviderWebsocketConfiguration, url: `wss://${configuration.appId}.collab.tiptap.cloud` })\n }\n}\n","import {\n HocuspocusProvider,\n HocuspocusProviderConfiguration,\n} from './HocuspocusProvider.js'\n\nimport { TiptapCollabProviderWebsocket } from './TiptapCollabProviderWebsocket.js'\n\nexport type TiptapCollabProviderConfiguration =\n Required> &\n Partial &\n AdditionalTiptapCollabProviderConfiguration\n\nexport interface AdditionalTiptapCollabProviderConfiguration {\n /**\n * A Hocuspocus Cloud App ID, get one here: https://collab.tiptap.dev\n */\n appId: string,\n}\n\nexport class TiptapCollabProvider extends HocuspocusProvider {\n constructor(configuration: TiptapCollabProviderConfiguration) {\n if (!configuration.websocketProvider) {\n configuration.websocketProvider = new TiptapCollabProviderWebsocket({ appId: configuration.appId })\n }\n\n if (!configuration.token) {\n configuration.token = 'notoken' // need to send a token anyway (which will be ignored)\n }\n\n super(configuration as HocuspocusProviderConfiguration)\n }\n}\n"],"names":["create","length","object.length","object.hasProperty","map.create","string.fromCamelCase","conditions.undefinedToNull","storage.varStorage","f.isOneOf","buffer.createUint8ArrayViewFromArrayBuffer","binary.BITS7","binary.BIT8","math.floor","string.utf8TextEncoder","string.encodeUtf8","math.min","math.max","error.create","number.MAX_SAFE_INTEGER","string.utf8TextDecoder","string.fromCharCode","env.isBrowser","buffer.fromBase64","storage.onChange","buffer.toBase64","buffer.createUint8ArrayFromArrayBuffer","storage.offChange","map.setIfUndefined","set.create","array.from","time.getUnixTime","f.equalityDeep","encoding.createEncoder","encoding.writeVarUint","encoding.writeVarString","encoding.toUint8Array","decoding.createDecoder","decoding.readVarUint","decoding.readVarString","encoding.writeVarUint8Array","decoding.readVarUint8Array","awarenessProtocol.applyAwarenessUpdate","awarenessProtocol.encodeAwarenessUpdate","bc.publish","syncProtocol.writeSyncStep1","syncProtocol.writeSyncStep2","object.map","mutex.createMutex","url.encodeQueryParams","bc.subscribe","bc.unsubscribe"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMA,QAAM,GAAG,MAAM,IAAI,GAAG,GAAE;AAerC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,cAAc,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,KAAK;AACrD,EAAE,IAAI,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,EAAC;AACxB,EAAE,IAAI,GAAG,KAAK,SAAS,EAAE;AACzB,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,GAAG,OAAO,EAAE,EAAC;AACjC,GAAG;AACH,EAAE,OAAO,GAAG;AACZ;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMA,QAAM,GAAG,MAAM,IAAI,GAAG;;ACNnC;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,YAAY,GAAG,MAAM,CAAC,aAAY;AAE/C;AACA;AACA;AACA;AACA;AACA,MAAM,WAAW,GAAG,CAAC,IAAI,CAAC,CAAC,WAAW,GAAE;AACxC;AACA,MAAM,aAAa,GAAG,QAAO;AAC7B;AACA;AACA;AACA;AACA;AACO,MAAM,QAAQ,GAAG,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,aAAa,EAAE,EAAE,EAAC;AACzD;AACA,MAAM,kBAAkB,GAAG,WAAU;AACrC;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,aAAa,GAAG,CAAC,CAAC,EAAE,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,kBAAkB,EAAE,KAAK,IAAI,CAAC,EAAE,SAAS,CAAC,EAAE,WAAW,CAAC,K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,EAAE;AACpC,YAAA,aAAa,CAAC,iBAAiB,GAAG,IAAI,6BAA6B,CAAC,EAAE,KAAK,EAAE,aAAa,CAAC,KAAK,EAAE,CAAC,CAAA;AACpG,SAAA;AAED,QAAA,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE;AACxB,YAAA,aAAa,CAAC,KAAK,GAAG,SAAS,CAAA;AAChC,SAAA;QAED,KAAK,CAAC,aAAgD,CAAC,CAAA;KACxD;AACF;;;;"} -\ No newline at end of file -+{"version":3,"file":"hocuspocus-provider.esm.js","sources":["../../../node_modules/lib0/map.js","../../../node_modules/lib0/set.js","../../../node_modules/lib0/array.js","../../../node_modules/lib0/string.js","../../../node_modules/lib0/conditions.js","../../../node_modules/lib0/storage.js","../../../node_modules/lib0/object.js","../../../node_modules/lib0/function.js","../../../node_modules/lib0/environment.js","../../../node_modules/lib0/math.js","../../../node_modules/lib0/binary.js","../../../node_modules/lib0/number.js","../../../node_modules/lib0/encoding.js","../../../node_modules/lib0/error.js","../../../node_modules/lib0/decoding.js","../../../node_modules/lib0/buffer.js","../../../node_modules/lib0/broadcastchannel.js","../../../node_modules/lib0/mutex.js","../../../node_modules/lib0/time.js","../../../node_modules/lib0/observable.js","../../../node_modules/y-protocols/awareness.js","../src/EventEmitter.ts","../../../node_modules/lib0/url.js","../src/types.ts","../src/HocuspocusProviderWebsocket.ts","../src/IncomingMessage.ts","../../../node_modules/y-protocols/sync.js","../src/OutgoingMessage.ts","../src/MessageReceiver.ts","../src/MessageSender.ts","../src/OutgoingMessages/AuthenticationMessage.ts","../src/OutgoingMessages/AwarenessMessage.ts","../src/OutgoingMessages/CloseMessage.ts","../src/OutgoingMessages/QueryAwarenessMessage.ts","../src/OutgoingMessages/StatelessMessage.ts","../src/OutgoingMessages/SyncStepOneMessage.ts","../src/OutgoingMessages/SyncStepTwoMessage.ts","../src/OutgoingMessages/UpdateMessage.ts","../src/HocuspocusProvider.ts","../src/TiptapCollabProviderWebsocket.ts","../src/TiptapCollabProvider.ts"],"sourcesContent":["/**\n * Utility module to work with key-value stores.\n *\n * @module map\n */\n\n/**\n * Creates a new Map instance.\n *\n * @function\n * @return {Map}\n *\n * @function\n */\nexport const create = () => new Map()\n\n/**\n * Copy a Map object into a fresh Map object.\n *\n * @function\n * @template X,Y\n * @param {Map} m\n * @return {Map}\n */\nexport const copy = m => {\n const r = create()\n m.forEach((v, k) => { r.set(k, v) })\n return r\n}\n\n/**\n * Get map property. Create T if property is undefined and set T on map.\n *\n * ```js\n * const listeners = map.setIfUndefined(events, 'eventName', set.create)\n * listeners.add(listener)\n * ```\n *\n * @function\n * @template V,K\n * @template {Map} MAP\n * @param {MAP} map\n * @param {K} key\n * @param {function():V} createT\n * @return {V}\n */\nexport const setIfUndefined = (map, key, createT) => {\n let set = map.get(key)\n if (set === undefined) {\n map.set(key, set = createT())\n }\n return set\n}\n\n/**\n * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function.\n *\n * @function\n * @template K\n * @template V\n * @template R\n * @param {Map} m\n * @param {function(V,K):R} f\n * @return {Array}\n */\nexport const map = (m, f) => {\n const res = []\n for (const [key, value] of m) {\n res.push(f(value, key))\n }\n return res\n}\n\n/**\n * Tests whether any key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @todo should rename to some - similarly to Array.some\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const any = (m, f) => {\n for (const [key, value] of m) {\n if (f(value, key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * Tests whether all key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const all = (m, f) => {\n for (const [key, value] of m) {\n if (!f(value, key)) {\n return false\n }\n }\n return true\n}\n","/**\n * Utility module to work with sets.\n *\n * @module set\n */\n\nexport const create = () => new Set()\n\n/**\n * @template T\n * @param {Set} set\n * @return {Array}\n */\nexport const toArray = set => Array.from(set)\n\n/**\n * @template T\n * @param {Set} set\n * @return {T}\n */\nexport const first = set =>\n set.values().next().value || undefined\n\n/**\n * @template T\n * @param {Iterable} entries\n * @return {Set}\n */\nexport const from = entries => new Set(entries)\n","/**\n * Utility module to work with Arrays.\n *\n * @module array\n */\n\nimport * as set from './set.js'\n\n/**\n * Return the last element of an array. The element must exist\n *\n * @template L\n * @param {ArrayLike} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array}\n */\nexport const create = () => /** @type {Array} */ ([])\n\n/**\n * @template D\n * @param {Array} a\n * @return {Array}\n */\nexport const copy = a => /** @type {Array} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array} dest\n * @param {Array} src\n */\nexport const appendTo = (dest, src) => {\n for (let i = 0; i < src.length; i++) {\n dest.push(src[i])\n }\n}\n\n/**\n * Transforms something array-like to an actual Array.\n *\n * @function\n * @template T\n * @param {ArrayLike|Iterable} arraylike\n * @return {T}\n */\nexport const from = Array.from\n\n/**\n * True iff condition holds on every element in the Array.\n *\n * @function\n * @template ITEM\n * @template {ArrayLike} ARR\n *\n * @param {ARR} arr\n * @param {function(ITEM, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const every = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (!f(arr[i], i, arr)) {\n return false\n }\n }\n return true\n}\n\n/**\n * True iff condition holds on some element in the Array.\n *\n * @function\n * @template S\n * @template {ArrayLike} ARR\n * @param {ARR} arr\n * @param {function(S, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const some = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (f(arr[i], i, arr)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @template ELEM\n *\n * @param {ArrayLike} a\n * @param {ArrayLike} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a.length === b.length && every(a, (item, index) => item === b[index])\n\n/**\n * @template ELEM\n * @param {Array>} arr\n * @return {Array}\n */\nexport const flatten = arr => fold(arr, /** @type {Array} */ ([]), (acc, val) => acc.concat(val))\n\n/**\n * @template T\n * @param {number} len\n * @param {function(number, Array):T} f\n * @return {Array}\n */\nexport const unfold = (len, f) => {\n const array = new Array(len)\n for (let i = 0; i < len; i++) {\n array[i] = f(i, array)\n }\n return array\n}\n\n/**\n * @template T\n * @template RESULT\n * @param {Array} arr\n * @param {RESULT} seed\n * @param {function(RESULT, T, number):RESULT} folder\n */\nexport const fold = (arr, seed, folder) => arr.reduce(folder, seed)\n\nexport const isArray = Array.isArray\n\n/**\n * @template T\n * @param {Array} arr\n * @return {Array}\n */\nexport const unique = arr => from(set.from(arr))\n\n/**\n * @template T\n * @template M\n * @param {ArrayLike} arr\n * @param {function(T):M} mapper\n * @return {Array}\n */\nexport const uniqueBy = (arr, mapper) => {\n /**\n * @type {Set}\n */\n const happened = set.create()\n /**\n * @type {Array}\n */\n const result = []\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i]\n const mapped = mapper(el)\n if (!happened.has(mapped)) {\n happened.add(mapped)\n result.push(el)\n }\n }\n return result\n}\n","import * as array from './array.js'\n\n/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * The largest utf16 character.\n * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8)\n */\nexport const MAX_UTF16_CHARACTER = fromCharCode(65535)\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* c8 ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* c8 ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* c8 ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* c8 ignore start */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* c8 ignore next */\n utf8TextDecoder = null\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* c8 ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n\n/**\n * @param {string} source\n * @param {number} n\n */\nexport const repeat = (source, n) => array.unfold(n, () => source).join('')\n","/**\n * Often used conditions.\n *\n * @module conditions\n */\n\n/**\n * @template T\n * @param {T|null|undefined} v\n * @return {T|null}\n */\n/* c8 ignore next */\nexport const undefinedToNull = v => v === undefined ? null : v\n","/* eslint-env browser */\n\n/**\n * Isomorphic variable storage.\n *\n * Uses LocalStorage in the browser and falls back to in-memory storage.\n *\n * @module storage\n */\n\n/* c8 ignore start */\nclass VarStoragePolyfill {\n constructor () {\n this.map = new Map()\n }\n\n /**\n * @param {string} key\n * @param {any} newValue\n */\n setItem (key, newValue) {\n this.map.set(key, newValue)\n }\n\n /**\n * @param {string} key\n */\n getItem (key) {\n return this.map.get(key)\n }\n}\n/* c8 ignore stop */\n\n/**\n * @type {any}\n */\nlet _localStorage = new VarStoragePolyfill()\nlet usePolyfill = true\n\n/* c8 ignore start */\ntry {\n // if the same-origin rule is violated, accessing localStorage might thrown an error\n if (typeof localStorage !== 'undefined') {\n _localStorage = localStorage\n usePolyfill = false\n }\n} catch (e) { }\n/* c8 ignore stop */\n\n/**\n * This is basically localStorage in browser, or a polyfill in nodejs\n */\n/* c8 ignore next */\nexport const varStorage = _localStorage\n\n/**\n * A polyfill for `addEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler))\n\n/**\n * A polyfill for `removeEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler))\n","/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object} obj\n */\nexport const keys = Object.keys\n\n/**\n * @template V\n * @param {{[k:string]:V}} obj\n * @param {function(V,string):any} f\n */\nexport const forEach = (obj, f) => {\n for (const key in obj) {\n f(obj[key], key)\n }\n}\n\n/**\n * @todo implement mapToArray & map\n *\n * @template R\n * @param {Object} obj\n * @param {function(any,string):R} f\n * @return {Array}\n */\nexport const map = (obj, f) => {\n const results = []\n for (const key in obj) {\n results.push(f(obj[key], key))\n }\n return results\n}\n\n/**\n * @param {Object} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n for (const key in obj) {\n if (f(obj[key], key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {Object|undefined} obj\n */\nexport const isEmpty = obj => {\n for (const _k in obj) {\n return false\n }\n return true\n}\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n for (const key in obj) {\n if (!f(obj[key], key)) {\n return false\n }\n }\n return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object} a\n * @param {Object} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val))\n","/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array} fs\n * @param {Array} args\n */\nexport const callAll = (fs, args, i = 0) => {\n try {\n for (; i < fs.length; i++) {\n fs[i](...args)\n }\n } finally {\n if (i < fs.length) {\n callAll(fs, args, i + 1)\n }\n }\n}\n\nexport const nop = () => {}\n\n/**\n * @template T\n * @param {function():T} f\n * @return {T}\n */\nexport const apply = f => f()\n\n/**\n * @template A\n *\n * @param {A} a\n * @return {A}\n */\nexport const id = a => a\n\n/**\n * @template T\n *\n * @param {T} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equalityStrict = (a, b) => a === b\n\n/**\n * @template T\n *\n * @param {Array|object} a\n * @param {Array|object} b\n * @return {boolean}\n */\nexport const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((array.isArray(a) && array.equalFlat(a, /** @type {Array} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/* c8 ignore start */\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a == null || b == null) {\n return equalityStrict(a, b)\n }\n if (a.constructor !== b.constructor) {\n return false\n }\n if (a === b) {\n return true\n }\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n break\n }\n case Map: {\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n return false\n }\n }\n break\n }\n case Object:\n if (object.length(a) !== object.length(b)) {\n return false\n }\n for (const key in a) {\n if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n return false\n }\n }\n break\n case Array:\n if (a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!equalityDeep(a[i], b[i])) {\n return false\n }\n }\n break\n default:\n return false\n }\n return true\n}\n\n/**\n * @template V\n * @template {V} OPTS\n *\n * @param {V} value\n * @param {Array} options\n */\n// @ts-ignore\nexport const isOneOf = (value, options) => options.includes(value)\n/* c8 ignore stop */\n\nexport const isArray = array.isArray\n\n/**\n * @param {any} s\n * @return {s is String}\n */\nexport const isString = (s) => s && s.constructor === String\n\n/**\n * @param {any} n\n * @return {n is Number}\n */\nexport const isNumber = n => n != null && n.constructor === Number\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {any} n\n * @param {TYPE} T\n * @return {n is InstanceType}\n */\nexport const is = (n, T) => n && n.constructor === T\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {TYPE} T\n */\nexport const isTemplate = (T) =>\n /**\n * @param {any} n\n * @return {n is InstanceType}\n **/\n n => n && n.constructor === T\n","/**\n * Isomorphic module to work access the environment (query params, env variables).\n *\n * @module map\n */\n\nimport * as map from './map.js'\nimport * as string from './string.js'\nimport * as conditions from './conditions.js'\nimport * as storage from './storage.js'\nimport * as f from './function.js'\n\n/* c8 ignore next */\n// @ts-ignore\nexport const isNode = typeof process !== 'undefined' && process.release &&\n /node|io\\.js/.test(process.release.name)\n/* c8 ignore next */\nexport const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && !isNode\n/* c8 ignore next 3 */\nexport const isMac = typeof navigator !== 'undefined'\n ? /Mac/.test(navigator.platform)\n : false\n\n/**\n * @type {Map}\n */\nlet params\nconst args = []\n\n/* c8 ignore start */\nconst computeParams = () => {\n if (params === undefined) {\n if (isNode) {\n params = map.create()\n const pargs = process.argv\n let currParamName = null\n for (let i = 0; i < pargs.length; i++) {\n const parg = pargs[i]\n if (parg[0] === '-') {\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n currParamName = parg\n } else {\n if (currParamName !== null) {\n params.set(currParamName, parg)\n currParamName = null\n } else {\n args.push(parg)\n }\n }\n }\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n // in ReactNative for example this would not be true (unless connected to the Remote Debugger)\n } else if (typeof location === 'object') {\n params = map.create(); // eslint-disable-next-line no-undef\n (location.search || '?').slice(1).split('&').forEach((kv) => {\n if (kv.length !== 0) {\n const [key, value] = kv.split('=')\n params.set(`--${string.fromCamelCase(key, '-')}`, value)\n params.set(`-${string.fromCamelCase(key, '-')}`, value)\n }\n })\n } else {\n params = map.create()\n }\n }\n return params\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next */\nexport const hasParam = (name) => computeParams().has(name)\n\n/**\n * @param {string} name\n * @param {string} defaultVal\n * @return {string}\n */\n/* c8 ignore next 2 */\nexport const getParam = (name, defaultVal) =>\n computeParams().get(name) || defaultVal\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 4 */\nexport const getVariable = (name) =>\n isNode\n ? conditions.undefinedToNull(process.env[name.toUpperCase()])\n : conditions.undefinedToNull(storage.varStorage.getItem(name))\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 2 */\nexport const getConf = (name) =>\n computeParams().get('--' + name) || getVariable(name)\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next 2 */\nexport const hasConf = (name) =>\n hasParam('--' + name) || getVariable(name) !== null\n\n/* c8 ignore next */\nexport const production = hasConf('production')\n\n/* c8 ignore next 2 */\nconst forceColor = isNode &&\n f.isOneOf(process.env.FORCE_COLOR, ['true', '1', '2'])\n\n/* c8 ignore start */\nexport const supportsColor = !hasParam('no-colors') &&\n (!isNode || process.stdout.isTTY || forceColor) && (\n !isNode || hasParam('color') || forceColor ||\n getVariable('COLORTERM') !== null ||\n (getVariable('TERM') || '').includes('color')\n)\n/* c8 ignore stop */\n","/**\n * Common Math expressions.\n *\n * @module math\n */\n\nexport const floor = Math.floor\nexport const ceil = Math.ceil\nexport const abs = Math.abs\nexport const imul = Math.imul\nexport const round = Math.round\nexport const log10 = Math.log10\nexport const log2 = Math.log2\nexport const log = Math.log\nexport const sqrt = Math.sqrt\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The sum of a and b\n */\nexport const add = (a, b) => a + b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The smaller element of a and b\n */\nexport const min = (a, b) => a < b ? a : b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The bigger element of a and b\n */\nexport const max = (a, b) => a > b ? a : b\n\nexport const isNaN = Number.isNaN\n\nexport const pow = Math.pow\n/**\n * Base 10 exponential function. Returns the value of 10 raised to the power of pow.\n *\n * @param {number} exp\n * @return {number}\n */\nexport const exp10 = exp => Math.pow(10, exp)\n\nexport const sign = Math.sign\n\n/**\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\nexport const HIGHEST_INT32 = binary.BITS31\nexport const HIGHEST_UINT32 = binary.BITS32\n\n/* c8 ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n","/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\nimport * as string from './string.js'\nimport * as array from './array.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * @param {function(Encoder):void} f\n */\nexport const encode = (f) => {\n const encoder = createEncoder()\n f(encoder)\n return toUint8Array(encoder)\n}\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Check whether encoder is empty.\n *\n * @function\n * @param {Encoder} encoder\n * @return {boolean}\n */\nexport const hasContent = encoder => encoder.cpos > 0 || encoder.bufs.length > 0\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nexport const verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer. Max encodable integer is 2^53.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num = math.floor(num / 64) // shift >>> 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n}\n\n/**\n * A cache to store strings temporarily\n */\nconst _strBuffer = new Uint8Array(30000)\nconst _maxStrBSize = _strBuffer.length / 3\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringNative = (encoder, str) => {\n if (str.length < _maxStrBSize) {\n // We can encode the string into the existing buffer\n /* c8 ignore next */\n const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0\n writeVarUint(encoder, written)\n for (let i = 0; i < written; i++) {\n write(encoder, _strBuffer[i])\n }\n } else {\n writeVarUint8Array(encoder, string.encodeUtf8(str))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringPolyfill = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\n/* c8 ignore next */\nexport const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill\n\n/**\n * Write a string terminated by a special byte sequence. This is not very performant and is\n * generally discouraged. However, the resulting byte arrays are lexiographically ordered which\n * makes this a nice feature for databases.\n *\n * The string will be encoded using utf8 and then terminated and escaped using writeTerminatingUint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const writeTerminatedString = (encoder, str) =>\n writeTerminatedUint8Array(encoder, string.encodeUtf8(str))\n\n/**\n * Write a terminating Uint8Array. Note that this is not performant and is generally\n * discouraged. There are few situations when this is needed.\n *\n * We use 0x0 as a terminating character. 0x1 serves as an escape character for 0x0 and 0x1.\n *\n * Example: [0,1,2] is encoded to [1,0,1,1,2,0]. 0x0, and 0x1 needed to be escaped using 0x1. Then\n * the result is terminated using the 0x0 character.\n *\n * This is basically how many systems implement null terminated strings. However, we use an escape\n * character 0x1 to avoid issues and potenial attacks on our database (if this is used as a key\n * encoder for NoSql databases).\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} buf The string that is to be encoded.\n */\nexport const writeTerminatedUint8Array = (encoder, buf) => {\n for (let i = 0; i < buf.length; i++) {\n const b = buf[i]\n if (b === 0 || b === 1) {\n write(encoder, 1)\n }\n write(encoder, buf[i])\n }\n write(encoder, 0)\n}\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && math.abs(data) <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (array.isArray(data)) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n","/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* c8 ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n","/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as binary from './binary.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as string from './string.js'\nimport * as error from './error.js'\nimport * as encoding from './encoding.js'\n\nconst errorUnexpectedEndOfArray = error.create('Unexpected end of array')\nconst errorIntegerOutOfRange = error.create('Integer out of Range')\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n */\nexport class Decoder {\n /**\n * @param {Uint8Array} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @param {Uint8Array} uint8Array\n * @return {Decoder}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = buffer.createUint8ArrayViewFromArrayBuffer(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let mult = 1\n const len = decoder.arr.length\n while (decoder.pos < len) {\n const r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num\n mult *= 128 // next iteration, shift 7 \"more\" to the left\n if (r < binary.BIT8) {\n return num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let mult = 64\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n const len = decoder.arr.length\n while (decoder.pos < len) {\n r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult\n mult *= 128\n if (r < binary.BIT8) {\n return sign * num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * We don't test this function anymore as we use native decoding/encoding by default now.\n * Better not modify this anymore..\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\n/* c8 ignore start */\nexport const _readVarStringPolyfill = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n/* c8 ignore stop */\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n */\nexport const _readVarStringNative = decoder =>\n /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder))\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n *\n */\n/* c8 ignore next */\nexport const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill\n\n/**\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTerminatedUint8Array = decoder => {\n const encoder = encoding.createEncoder()\n let b\n while (true) {\n b = readUint8(decoder)\n if (b === 0) {\n return encoding.toUint8Array(encoder)\n }\n if (b === 1) {\n b = readUint8(decoder)\n }\n encoding.write(encoder, b)\n }\n}\n\n/**\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const readTerminatedString = decoder => string.decodeUtf8(readTerminatedUint8Array(decoder))\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object\n const len = readVarUint(decoder)\n /**\n * @type {Object}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = math.floor(diff / 2) // shift >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n","/**\n * Utility functions to work with buffers (Uint8Array).\n *\n * @module buffer\n */\n\nimport * as string from './string.js'\nimport * as env from './environment.js'\nimport * as encoding from './encoding.js'\nimport * as decoding from './decoding.js'\n\n/**\n * @param {number} len\n */\nexport const createUint8ArrayFromLen = len => new Uint8Array(len)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n * @param {number} byteOffset\n * @param {number} length\n */\nexport const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n */\nexport const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer)\n\n/* c8 ignore start */\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Browser = bytes => {\n let s = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n s += string.fromCharCode(bytes[i])\n }\n // eslint-disable-next-line no-undef\n return btoa(s)\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')\n\n/* c8 ignore start */\n/**\n * @param {string} s\n * @return {Uint8Array}\n */\nconst fromBase64Browser = s => {\n // eslint-disable-next-line no-undef\n const a = atob(s)\n const bytes = createUint8ArrayFromLen(a.length)\n for (let i = 0; i < a.length; i++) {\n bytes[i] = a.charCodeAt(i)\n }\n return bytes\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} s\n */\nconst fromBase64Node = s => {\n const buf = Buffer.from(s, 'base64')\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n}\n\n/* c8 ignore next */\nexport const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node\n\n/* c8 ignore next */\nexport const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node\n\n/**\n * Copy the content of an Uint8Array view to a new ArrayBuffer.\n *\n * @param {Uint8Array} uint8Array\n * @return {Uint8Array}\n */\nexport const copyUint8Array = uint8Array => {\n const newBuf = createUint8ArrayFromLen(uint8Array.byteLength)\n newBuf.set(uint8Array)\n return newBuf\n}\n\n/**\n * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type.\n * See encoding.writeAny for more information.\n *\n * @param {any} data\n * @return {Uint8Array}\n */\nexport const encodeAny = data => {\n const encoder = encoding.createEncoder()\n encoding.writeAny(encoder, data)\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Decode an any-encoded value.\n *\n * @param {Uint8Array} buf\n * @return {any}\n */\nexport const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf))\n","/* eslint-env browser */\n\n/**\n * Helpers for cross-tab communication using broadcastchannel with LocalStorage fallback.\n *\n * ```js\n * // In browser window A:\n * broadcastchannel.subscribe('my events', data => console.log(data))\n * broadcastchannel.publish('my events', 'Hello world!') // => A: 'Hello world!' fires synchronously in same tab\n *\n * // In browser window B:\n * broadcastchannel.publish('my events', 'hello from tab B') // => A: 'hello from tab B'\n * ```\n *\n * @module broadcastchannel\n */\n\n// @todo before next major: use Uint8Array instead as buffer object\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as buffer from './buffer.js'\nimport * as storage from './storage.js'\n\n/**\n * @typedef {Object} Channel\n * @property {Set} Channel.subs\n * @property {any} Channel.bc\n */\n\n/**\n * @type {Map}\n */\nconst channels = new Map()\n\n/* c8 ignore start */\nclass LocalStoragePolyfill {\n /**\n * @param {string} room\n */\n constructor (room) {\n this.room = room\n /**\n * @type {null|function({data:ArrayBuffer}):void}\n */\n this.onmessage = null\n /**\n * @param {any} e\n */\n this._onChange = e => e.key === room && this.onmessage !== null && this.onmessage({ data: buffer.fromBase64(e.newValue || '') })\n storage.onChange(this._onChange)\n }\n\n /**\n * @param {ArrayBuffer} buf\n */\n postMessage (buf) {\n storage.varStorage.setItem(this.room, buffer.toBase64(buffer.createUint8ArrayFromArrayBuffer(buf)))\n }\n\n close () {\n storage.offChange(this._onChange)\n }\n}\n/* c8 ignore stop */\n\n// Use BroadcastChannel or Polyfill\n/* c8 ignore next */\nconst BC = typeof BroadcastChannel === 'undefined' ? LocalStoragePolyfill : BroadcastChannel\n\n/**\n * @param {string} room\n * @return {Channel}\n */\nconst getChannel = room =>\n map.setIfUndefined(channels, room, () => {\n const subs = set.create()\n const bc = new BC(room)\n /**\n * @param {{data:ArrayBuffer}} e\n */\n /* c8 ignore next */\n bc.onmessage = e => subs.forEach(sub => sub(e.data, 'broadcastchannel'))\n return {\n bc, subs\n }\n })\n\n/**\n * Subscribe to global `publish` events.\n *\n * @function\n * @param {string} room\n * @param {function(any, any):any} f\n */\nexport const subscribe = (room, f) => {\n getChannel(room).subs.add(f)\n return f\n}\n\n/**\n * Unsubscribe from `publish` global events.\n *\n * @function\n * @param {string} room\n * @param {function(any, any):any} f\n */\nexport const unsubscribe = (room, f) => {\n const channel = getChannel(room)\n const unsubscribed = channel.subs.delete(f)\n if (unsubscribed && channel.subs.size === 0) {\n channel.bc.close()\n channels.delete(room)\n }\n return unsubscribed\n}\n\n/**\n * Publish data to all subscribers (including subscribers on this tab)\n *\n * @function\n * @param {string} room\n * @param {any} data\n * @param {any} [origin]\n */\nexport const publish = (room, data, origin = null) => {\n const c = getChannel(room)\n c.bc.postMessage(data)\n c.subs.forEach(sub => sub(data, origin))\n}\n","/**\n * Mutual exclude for JavaScript.\n *\n * @module mutex\n */\n\n/**\n * @callback mutex\n * @param {function():void} cb Only executed when this mutex is not in the current stack\n * @param {function():void} [elseCb] Executed when this mutex is in the current stack\n */\n\n/**\n * Creates a mutual exclude function with the following property:\n *\n * ```js\n * const mutex = createMutex()\n * mutex(() => {\n * // This function is immediately executed\n * mutex(() => {\n * // This function is not executed, as the mutex is already active.\n * })\n * })\n * ```\n *\n * @return {mutex} A mutual exclude function\n * @public\n */\nexport const createMutex = () => {\n let token = true\n return (f, g) => {\n if (token) {\n token = false\n try {\n f()\n } finally {\n token = true\n }\n } else if (g !== undefined) {\n g()\n }\n }\n}\n","/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* c8 ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n","/**\n * Observable class prototype.\n *\n * @module observable\n */\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as array from './array.js'\n\n/**\n * Handles named events.\n *\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map}\n */\n this._observers = map.create()\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, name, set.create).add(f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, _f)\n f(...args)\n }\n this.on(name, _f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @param {N} name The event name.\n * @param {Array} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // 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.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n","/**\n * @module awareness-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as time from 'lib0/time'\nimport * as math from 'lib0/math'\nimport { Observable } from 'lib0/observable'\nimport * as f from 'lib0/function'\nimport * as Y from 'yjs' // eslint-disable-line\n\nexport const outdatedTimeout = 30000\n\n/**\n * @typedef {Object} MetaClientState\n * @property {number} MetaClientState.clock\n * @property {number} MetaClientState.lastUpdated unix timestamp\n */\n\n/**\n * The Awareness class implements a simple shared state protocol that can be used for non-persistent data like awareness information\n * (cursor, username, status, ..). Each client can update its own local state and listen to state changes of\n * remote clients. Every client may set a state of a remote peer to `null` to mark the client as offline.\n *\n * Each client is identified by a unique client id (something we borrow from `doc.clientID`). A client can override\n * its own state by propagating a message with an increasing timestamp (`clock`). If such a message is received, it is\n * applied if the known state of that client is older than the new state (`clock < newClock`). If a client thinks that\n * a remote client is offline, it may propagate a message with\n * `{ clock: currentClientClock, state: null, client: remoteClient }`. If such a\n * message is received, and the known clock of that client equals the received clock, it will override the state with `null`.\n *\n * Before a client disconnects, it should propagate a `null` state with an updated clock.\n *\n * Awareness states must be updated every 30 seconds. Otherwise the Awareness instance will delete the client state.\n *\n * @extends {Observable}\n */\nexport class Awareness extends Observable {\n /**\n * @param {Y.Doc} doc\n */\n constructor (doc) {\n super()\n this.doc = doc\n /**\n * @type {number}\n */\n this.clientID = doc.clientID\n /**\n * Maps from client id to client state\n * @type {Map>}\n */\n this.states = new Map()\n /**\n * @type {Map}\n */\n this.meta = new Map()\n this._checkInterval = /** @type {any} */ (setInterval(() => {\n const now = time.getUnixTime()\n if (this.getLocalState() !== null && (outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ (this.meta.get(this.clientID)).lastUpdated)) {\n // renew local clock\n this.setLocalState(this.getLocalState())\n }\n /**\n * @type {Array}\n */\n const remove = []\n this.meta.forEach((meta, clientid) => {\n if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) {\n remove.push(clientid)\n }\n })\n if (remove.length > 0) {\n removeAwarenessStates(this, remove, 'timeout')\n }\n }, math.floor(outdatedTimeout / 10)))\n doc.on('destroy', () => {\n this.destroy()\n })\n this.setLocalState({})\n }\n\n destroy () {\n this.emit('destroy', [this])\n this.setLocalState(null)\n super.destroy()\n clearInterval(this._checkInterval)\n }\n\n /**\n * @return {Object|null}\n */\n getLocalState () {\n return this.states.get(this.clientID) || null\n }\n\n /**\n * @param {Object|null} state\n */\n setLocalState (state) {\n const clientID = this.clientID\n const currLocalMeta = this.meta.get(clientID)\n const clock = currLocalMeta === undefined ? 0 : currLocalMeta.clock + 1\n const prevState = this.states.get(clientID)\n if (state === null) {\n this.states.delete(clientID)\n } else {\n this.states.set(clientID, state)\n }\n this.meta.set(clientID, {\n clock,\n lastUpdated: time.getUnixTime()\n })\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n if (state === null) {\n removed.push(clientID)\n } else if (prevState == null) {\n if (state != null) {\n added.push(clientID)\n }\n } else {\n updated.push(clientID)\n if (!f.equalityDeep(prevState, state)) {\n filteredUpdated.push(clientID)\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n this.emit('change', [{ added, updated: filteredUpdated, removed }, 'local'])\n }\n this.emit('update', [{ added, updated, removed }, 'local'])\n }\n\n /**\n * @param {string} field\n * @param {any} value\n */\n setLocalStateField (field, value) {\n const state = this.getLocalState()\n if (state !== null) {\n this.setLocalState({\n ...state,\n [field]: value\n })\n }\n }\n\n /**\n * @return {Map>}\n */\n getStates () {\n return this.states\n }\n}\n\n/**\n * Mark (remote) clients as inactive and remove them from the list of active peers.\n * This change will be propagated to remote clients.\n *\n * @param {Awareness} awareness\n * @param {Array} clients\n * @param {any} origin\n */\nexport const removeAwarenessStates = (awareness, clients, origin) => {\n const removed = []\n for (let i = 0; i < clients.length; i++) {\n const clientID = clients[i]\n if (awareness.states.has(clientID)) {\n awareness.states.delete(clientID)\n if (clientID === awareness.clientID) {\n const curMeta = /** @type {MetaClientState} */ (awareness.meta.get(clientID))\n awareness.meta.set(clientID, {\n clock: curMeta.clock + 1,\n lastUpdated: time.getUnixTime()\n })\n }\n removed.push(clientID)\n }\n }\n if (removed.length > 0) {\n awareness.emit('change', [{ added: [], updated: [], removed }, origin])\n awareness.emit('update', [{ added: [], updated: [], removed }, origin])\n }\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Array} clients\n * @return {Uint8Array}\n */\nexport const encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {\n const len = clients.length\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = clients[i]\n const state = states.get(clientID) || null\n const clock = /** @type {MetaClientState} */ (awareness.meta.get(clientID)).clock\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(state))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Modify the content of an awareness update before re-encoding it to an awareness update.\n *\n * This might be useful when you have a central server that wants to ensure that clients\n * cant hijack somebody elses identity.\n *\n * @param {Uint8Array} update\n * @param {function(any):any} modify\n * @return {Uint8Array}\n */\nexport const modifyAwarenessUpdate = (update, modify) => {\n const decoder = decoding.createDecoder(update)\n const encoder = encoding.createEncoder()\n const len = decoding.readVarUint(decoder)\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n const clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const modifiedState = modify(state)\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(modifiedState))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Uint8Array} update\n * @param {any} origin This will be added to the emitted change event\n */\nexport const applyAwarenessUpdate = (awareness, update, origin) => {\n const decoder = decoding.createDecoder(update)\n const timestamp = time.getUnixTime()\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n const len = decoding.readVarUint(decoder)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n let clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const clientMeta = awareness.meta.get(clientID)\n const prevState = awareness.states.get(clientID)\n const currClock = clientMeta === undefined ? 0 : clientMeta.clock\n if (currClock < clock || (currClock === clock && state === null && awareness.states.has(clientID))) {\n if (state === null) {\n // never let a remote client remove this local state\n if (clientID === awareness.clientID && awareness.getLocalState() != null) {\n // remote client removed the local state. Do not remote state. Broadcast a message indicating\n // that this client still exists by increasing the clock\n clock++\n } else {\n awareness.states.delete(clientID)\n }\n } else {\n awareness.states.set(clientID, state)\n }\n awareness.meta.set(clientID, {\n clock,\n lastUpdated: timestamp\n })\n if (clientMeta === undefined && state !== null) {\n added.push(clientID)\n } else if (clientMeta !== undefined && state === null) {\n removed.push(clientID)\n } else if (state !== null) {\n if (!f.equalityDeep(state, prevState)) {\n filteredUpdated.push(clientID)\n }\n updated.push(clientID)\n }\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n awareness.emit('change', [{\n added, updated: filteredUpdated, removed\n }, origin])\n }\n if (added.length > 0 || updated.length > 0 || removed.length > 0) {\n awareness.emit('update', [{\n added, updated, removed\n }, origin])\n }\n}\n","export default class EventEmitter {\n\n public callbacks: { [key: string]: Function[] } = {}\n\n public on(event: string, fn: Function): this {\n if (!this.callbacks[event]) {\n this.callbacks[event] = []\n }\n\n this.callbacks[event].push(fn)\n\n return this\n }\n\n protected emit(event: string, ...args: any): this {\n const callbacks = this.callbacks[event]\n\n if (callbacks) {\n callbacks.forEach(callback => callback.apply(this, args))\n }\n\n return this\n }\n\n public off(event: string, fn?: Function): this {\n const callbacks = this.callbacks[event]\n\n if (callbacks) {\n if (fn) {\n this.callbacks[event] = callbacks.filter(callback => callback !== fn)\n } else {\n delete this.callbacks[event]\n }\n }\n\n return this\n }\n\n removeAllListeners(): void {\n this.callbacks = {}\n }\n}\n","/**\n * Utility module to work with urls.\n *\n * @module url\n */\n\nimport * as object from './object.js'\n\n/**\n * Parse query parameters from an url.\n *\n * @param {string} url\n * @return {Object}\n */\nexport const decodeQueryParams = url => {\n /**\n * @type {Object}\n */\n const query = {}\n const urlQuerySplit = url.split('?')\n const pairs = urlQuerySplit[urlQuerySplit.length - 1].split('&')\n for (let i = 0; i < pairs.length; i++) {\n const item = pairs[i]\n if (item.length > 0) {\n const pair = item.split('=')\n query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '')\n }\n }\n return query\n}\n\n/**\n * @param {Object} params\n * @return {string}\n */\nexport const encodeQueryParams = params =>\n object.map(params, (val, key) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&')\n","import { Encoder } from 'lib0/encoding'\nimport type { CloseEvent, Event, MessageEvent } from 'ws'\nimport { Awareness } from 'y-protocols/awareness'\nimport * as Y from 'yjs'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { AuthenticationMessage } from './OutgoingMessages/AuthenticationMessage.js'\nimport { AwarenessMessage } from './OutgoingMessages/AwarenessMessage.js'\nimport { QueryAwarenessMessage } from './OutgoingMessages/QueryAwarenessMessage.js'\nimport { SyncStepOneMessage } from './OutgoingMessages/SyncStepOneMessage.js'\nimport { SyncStepTwoMessage } from './OutgoingMessages/SyncStepTwoMessage.js'\nimport { UpdateMessage } from './OutgoingMessages/UpdateMessage.js'\n\nexport enum MessageType {\n Sync = 0,\n Awareness = 1,\n Auth = 2,\n QueryAwareness = 3,\n Stateless = 5,\n CLOSE = 7,\n SyncStatus = 8,\n}\n\nexport enum WebSocketStatus {\n Connecting = 'connecting',\n Connected = 'connected',\n Disconnected = 'disconnected',\n}\n\nexport interface OutgoingMessageInterface {\n encoder: Encoder\n type?: MessageType\n}\n\nexport interface OutgoingMessageArguments {\n documentName: string,\n token: string,\n document: Y.Doc,\n awareness: Awareness,\n clients: number[],\n states: Map,\n update: any,\n payload: string,\n encoder: Encoder,\n}\n\nexport interface Constructable {\n new(...args: any) : T\n}\n\nexport type ConstructableOutgoingMessage =\n Constructable |\n Constructable |\n Constructable |\n Constructable |\n Constructable |\n Constructable\n\nexport type onAuthenticationFailedParameters = {\n reason: string,\n}\n\nexport type onOpenParameters = {\n event: Event,\n}\n\nexport type onMessageParameters = {\n event: MessageEvent,\n message: IncomingMessage,\n}\n\nexport type onOutgoingMessageParameters = {\n message: OutgoingMessage,\n}\n\nexport type onStatusParameters = {\n status: WebSocketStatus,\n}\n\nexport type onSyncedParameters = {\n state: boolean,\n}\n\nexport type onDisconnectParameters = {\n event: CloseEvent,\n}\n\nexport type onCloseParameters = {\n event: CloseEvent,\n}\n\nexport type onAwarenessUpdateParameters = {\n states: StatesArray\n}\n\nexport type onAwarenessChangeParameters = {\n states: StatesArray\n}\n\nexport type onStatelessParameters = {\n payload: string\n}\n\nexport type StatesArray = { clientId: number, [key: string | number]: any }[]\n","import {\n Forbidden, MessageTooBig, Unauthorized, WsReadyStates,\n} from '@hocuspocus/common'\nimport { retry } from '@lifeomic/attempt'\nimport * as mutex from 'lib0/mutex'\nimport * as time from 'lib0/time'\nimport * as url from 'lib0/url'\nimport type { MessageEvent } from 'ws'\nimport { Event } from 'ws'\nimport EventEmitter from './EventEmitter.js'\nimport { HocuspocusProvider } from './HocuspocusProvider.js'\nimport {\n WebSocketStatus,\n onAwarenessChangeParameters, onAwarenessUpdateParameters,\n onCloseParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onStatusParameters,\n} from './types.js'\n\nexport type HocuspocusProviderWebsocketConfiguration =\n Required>\n & Partial\n\nexport interface CompleteHocuspocusProviderWebsocketConfiguration {\n /**\n * URL of your @hocuspocus/server instance\n */\n url: string,\n\n /**\n * Pass `false` to start the connection manually.\n */\n connect: boolean,\n\n /**\n * URL parameters that should be added.\n */\n parameters: { [key: string]: any },\n /**\n * An optional WebSocket polyfill, for example for Node.js\n */\n WebSocketPolyfill: any,\n\n /**\n * Disconnect when no message is received for the defined amount of milliseconds.\n */\n messageReconnectTimeout: number,\n /**\n * The delay between each attempt in milliseconds. You can provide a factor to have the delay grow exponentially.\n */\n delay: number,\n /**\n * The intialDelay is the amount of time to wait before making the first attempt. This option should typically be 0 since you typically want the first attempt to happen immediately.\n */\n initialDelay: number,\n /**\n * The factor option is used to grow the delay exponentially.\n */\n factor: number,\n /**\n * The maximum number of attempts or 0 if there is no limit on number of attempts.\n */\n maxAttempts: number,\n /**\n * minDelay is used to set a lower bound of delay when jitter is enabled. This property has no effect if jitter is disabled.\n */\n minDelay: number,\n /**\n * The maxDelay option is used to set an upper bound for the delay when factor is enabled. A value of 0 can be provided if there should be no upper bound when calculating delay.\n */\n maxDelay: number,\n /**\n * If jitter is true then the calculated delay will be a random integer value between minDelay and the calculated delay for the current iteration.\n */\n jitter: boolean,\n /**\n * A timeout in milliseconds. If timeout is non-zero then a timer is set using setTimeout. If the timeout is triggered then future attempts will be aborted.\n */\n timeout: number,\n onOpen: (data: onOpenParameters) => void,\n onConnect: () => void,\n onMessage: (data: onMessageParameters) => void,\n onOutgoingMessage: (data: onOutgoingMessageParameters) => void,\n onStatus: (data: onStatusParameters) => void,\n onDisconnect: (data: onDisconnectParameters) => void,\n onClose: (data: onCloseParameters) => void,\n onDestroy: () => void,\n onAwarenessUpdate: (data: onAwarenessUpdateParameters) => void,\n onAwarenessChange: (data: onAwarenessChangeParameters) => void,\n /**\n * Don’t output any warnings.\n */\n quiet: boolean,\n}\n\nexport class HocuspocusProviderWebsocket extends EventEmitter {\n private messageQueue: any[] = []\n\n public configuration: CompleteHocuspocusProviderWebsocketConfiguration = {\n url: '',\n // @ts-ignore\n document: undefined,\n // @ts-ignore\n awareness: undefined,\n WebSocketPolyfill: undefined,\n parameters: {},\n connect: true,\n broadcast: true,\n forceSyncInterval: false,\n // TODO: this should depend on awareness.outdatedTime\n messageReconnectTimeout: 30000,\n // 1 second\n delay: 1000,\n // instant\n initialDelay: 0,\n // double the delay each time\n factor: 2,\n // unlimited retries\n maxAttempts: 0,\n // wait at least 1 second\n minDelay: 1000,\n // at least every 30 seconds\n maxDelay: 30000,\n // randomize\n jitter: true,\n // retry forever\n timeout: 0,\n onOpen: () => null,\n onConnect: () => null,\n onMessage: () => null,\n onOutgoingMessage: () => null,\n onStatus: () => null,\n onDisconnect: () => null,\n onClose: () => null,\n onDestroy: () => null,\n onAwarenessUpdate: () => null,\n onAwarenessChange: () => null,\n quiet: false,\n }\n\n subscribedToBroadcastChannel = false\n\n webSocket: WebSocket | null = null\n\n shouldConnect = true\n\n status = WebSocketStatus.Disconnected\n\n lastMessageReceived = 0\n\n mux = mutex.createMutex()\n\n intervals: any = {\n forceSync: null,\n connectionChecker: null,\n }\n\n connectionAttempt: {\n resolve: (value?: any) => void\n reject: (reason?: any) => void\n } | null = null\n\n constructor(configuration: HocuspocusProviderWebsocketConfiguration) {\n super()\n this.setConfiguration(configuration)\n\n this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill ? configuration.WebSocketPolyfill : WebSocket\n\n this.on('open', this.configuration.onOpen)\n this.on('open', this.onOpen.bind(this))\n this.on('connect', this.configuration.onConnect)\n this.on('message', this.configuration.onMessage)\n this.on('outgoingMessage', this.configuration.onOutgoingMessage)\n this.on('status', this.configuration.onStatus)\n this.on('status', this.onStatus.bind(this))\n this.on('disconnect', this.configuration.onDisconnect)\n this.on('close', this.configuration.onClose)\n this.on('destroy', this.configuration.onDestroy)\n this.on('awarenessUpdate', this.configuration.onAwarenessUpdate)\n this.on('awarenessChange', this.configuration.onAwarenessChange)\n\n this.on('close', this.onClose.bind(this))\n this.on('message', this.onMessage.bind(this))\n\n this.registerEventListeners()\n\n this.intervals.connectionChecker = setInterval(\n this.checkConnection.bind(this),\n this.configuration.messageReconnectTimeout / 10,\n )\n\n if (typeof configuration.connect !== 'undefined') {\n this.shouldConnect = configuration.connect\n }\n\n if (!this.shouldConnect) {\n return\n }\n\n this.connect()\n }\n\n receivedOnOpenPayload?: Event | undefined = undefined\n\n receivedOnStatusPayload?: onStatusParameters | undefined = undefined\n\n async onOpen(event: Event) {\n this.receivedOnOpenPayload = event\n }\n\n async onStatus(data: onStatusParameters) {\n this.receivedOnStatusPayload = data\n }\n\n attach(provider: HocuspocusProvider) {\n if (this.receivedOnOpenPayload) {\n provider.onOpen(this.receivedOnOpenPayload)\n }\n\n if (this.receivedOnStatusPayload) {\n provider.onStatus(this.receivedOnStatusPayload)\n }\n }\n\n detach(provider: HocuspocusProvider) {\n // tell the server to remove the listener\n\n }\n\n public setConfiguration(configuration: Partial = {}): void {\n this.configuration = { ...this.configuration, ...configuration }\n }\n\n boundConnect = this.connect.bind(this)\n\n cancelWebsocketRetry?: () => void\n\n async connect() {\n if (this.status === WebSocketStatus.Connected) {\n return\n }\n\n // Always cancel any previously initiated connection retryer instances\n if (this.cancelWebsocketRetry) {\n this.cancelWebsocketRetry()\n this.cancelWebsocketRetry = undefined\n }\n\n this.shouldConnect = true\n\n const abortableRetry = () => {\n let cancelAttempt = false\n\n const retryPromise = retry(this.createWebSocketConnection.bind(this), {\n delay: this.configuration.delay,\n initialDelay: this.configuration.initialDelay,\n factor: this.configuration.factor,\n maxAttempts: this.configuration.maxAttempts,\n minDelay: this.configuration.minDelay,\n maxDelay: this.configuration.maxDelay,\n jitter: this.configuration.jitter,\n timeout: this.configuration.timeout,\n beforeAttempt: context => {\n if (!this.shouldConnect || cancelAttempt) {\n context.abort()\n }\n },\n }).catch((error: any) => {\n // If we aborted the connection attempt then don’t throw an error\n // ref: https://github.com/lifeomic/attempt/blob/master/src/index.ts#L136\n if (error && error.code !== 'ATTEMPT_ABORTED') {\n throw error\n }\n })\n\n return {\n retryPromise,\n cancelFunc: () => {\n cancelAttempt = true\n },\n }\n }\n\n const { retryPromise, cancelFunc } = abortableRetry()\n this.cancelWebsocketRetry = cancelFunc\n\n return retryPromise\n }\n\n createWebSocketConnection() {\n return new Promise((resolve, reject) => {\n if (this.webSocket) {\n this.messageQueue = []\n this.webSocket.close()\n this.webSocket = null\n }\n\n // Init the WebSocket connection\n const ws = new this.configuration.WebSocketPolyfill(this.url)\n ws.binaryType = 'arraybuffer'\n ws.onmessage = (payload: any) => this.emit('message', payload)\n ws.onclose = (payload: any) => this.emit('close', { event: payload })\n ws.onopen = (payload: any) => this.emit('open', payload)\n ws.onerror = (err: any) => {\n reject(err)\n }\n this.webSocket = ws\n\n // Reset the status\n this.status = WebSocketStatus.Connecting\n this.emit('status', { status: WebSocketStatus.Connecting })\n\n // Store resolve/reject for later use\n this.connectionAttempt = {\n resolve,\n reject,\n }\n })\n }\n\n onMessage(event: MessageEvent) {\n this.resolveConnectionAttempt()\n }\n\n resolveConnectionAttempt() {\n if (this.connectionAttempt) {\n this.connectionAttempt.resolve()\n this.connectionAttempt = null\n\n this.status = WebSocketStatus.Connected\n this.emit('status', { status: WebSocketStatus.Connected })\n this.emit('connect')\n this.messageQueue.forEach(message => this.send(message))\n this.messageQueue = []\n }\n }\n\n stopConnectionAttempt() {\n this.connectionAttempt = null\n }\n\n rejectConnectionAttempt() {\n this.connectionAttempt?.reject()\n this.connectionAttempt = null\n }\n\n checkConnection() {\n // Don’t check the connection when it’s not even established\n if (this.status !== WebSocketStatus.Connected) {\n return\n }\n\n // Don’t close then connection while waiting for the first message\n if (!this.lastMessageReceived) {\n return\n }\n\n // Don’t close the connection when a message was received recently\n if (this.configuration.messageReconnectTimeout >= time.getUnixTime() - this.lastMessageReceived) {\n return\n }\n\n // No message received in a long time, not even your own\n // Awareness updates, which are updated every 15 seconds.\n this.webSocket?.close()\n this.messageQueue = []\n }\n\n registerEventListeners() {\n if (typeof window === 'undefined') {\n return\n }\n\n window.addEventListener('online', this.boundConnect)\n }\n\n // Ensure that the URL always ends with /\n get serverUrl() {\n while (this.configuration.url[this.configuration.url.length - 1] === '/') {\n return this.configuration.url.slice(0, this.configuration.url.length - 1)\n }\n\n return this.configuration.url\n }\n\n get url() {\n const encodedParams = url.encodeQueryParams(this.configuration.parameters)\n\n return `${this.serverUrl}${encodedParams.length === 0 ? '' : `?${encodedParams}`}`\n }\n\n disconnect() {\n this.shouldConnect = false\n\n if (this.webSocket === null) {\n return\n }\n\n try {\n this.webSocket.close()\n this.messageQueue = []\n } catch {\n //\n }\n }\n\n send(message: any) {\n if (this.webSocket?.readyState === WsReadyStates.Open) {\n this.webSocket.send(message)\n } else {\n this.messageQueue.push(message)\n }\n }\n\n onClose({ event }: onCloseParameters) {\n this.webSocket = null\n\n if (this.status === WebSocketStatus.Connected) {\n this.status = WebSocketStatus.Disconnected\n this.emit('status', { status: WebSocketStatus.Disconnected })\n this.emit('disconnect', { event })\n }\n\n if (event.code === Unauthorized.code) {\n if (event.reason === Unauthorized.reason) {\n console.warn('[HocuspocusProvider] An authentication token is required, but you didn’t send one. Try adding a `token` to your HocuspocusProvider configuration. Won’t try again.')\n } else {\n console.warn(`[HocuspocusProvider] Connection closed with status Unauthorized: ${event.reason}`)\n }\n\n this.shouldConnect = false\n }\n\n if (event.code === Forbidden.code) {\n if (!this.configuration.quiet) {\n console.warn('[HocuspocusProvider] The provided authentication token isn’t allowed to connect to this server. Will try again.')\n return // TODO REMOVE ME\n }\n }\n\n if (event.code === MessageTooBig.code) {\n console.warn(`[HocuspocusProvider] Connection closed with status MessageTooBig: ${event.reason}`)\n this.shouldConnect = false\n }\n\n if (this.connectionAttempt) {\n // That connection attempt failed.\n this.rejectConnectionAttempt()\n } else if (this.shouldConnect) {\n // The connection was closed by the server. Let’s just try again.\n this.connect()\n }\n\n // If we’ll reconnect, we’re done for now.\n if (this.shouldConnect) {\n return\n }\n\n // The status is set correctly already.\n if (this.status === WebSocketStatus.Disconnected) {\n return\n }\n\n // Let’s update the connection status.\n this.status = WebSocketStatus.Disconnected\n this.emit('status', { status: WebSocketStatus.Disconnected })\n this.emit('disconnect', { event })\n }\n\n destroy() {\n this.emit('destroy')\n\n if (this.intervals.forceSync) {\n clearInterval(this.intervals.forceSync)\n }\n\n clearInterval(this.intervals.connectionChecker)\n\n // If there is still a connection attempt outstanding then we should stop\n // it before calling disconnect, otherwise it will be rejected in the onClose\n // handler and trigger a retry\n this.stopConnectionAttempt()\n\n this.disconnect()\n\n this.removeAllListeners()\n\n if (typeof window === 'undefined') {\n return\n }\n\n window.removeEventListener('online', this.boundConnect)\n }\n\n}\n","import {\n createDecoder,\n readVarUint,\n readVarUint8Array,\n readVarString,\n Decoder,\n} from 'lib0/decoding'\nimport {\n Encoder,\n createEncoder,\n writeVarUint,\n writeVarUint8Array,\n writeVarString,\n length,\n} from 'lib0/encoding'\nimport { MessageType } from './types.js'\n\nexport class IncomingMessage {\n\n data: any\n\n encoder: Encoder\n\n decoder: Decoder\n\n constructor(data: any) {\n this.data = data\n this.encoder = createEncoder()\n this.decoder = createDecoder(new Uint8Array(this.data))\n }\n\n readVarUint(): MessageType {\n return readVarUint(this.decoder)\n }\n\n readVarString(): string {\n return readVarString(this.decoder)\n }\n\n readVarUint8Array() {\n return readVarUint8Array(this.decoder)\n }\n\n writeVarUint(type: MessageType) {\n return writeVarUint(this.encoder, type)\n }\n\n writeVarString(string: string) {\n return writeVarString(this.encoder, string)\n }\n\n writeVarUint8Array(data: Uint8Array) {\n return writeVarUint8Array(this.encoder, data)\n }\n\n length() {\n return length(this.encoder)\n }\n}\n","/**\n * @module sync-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as Y from 'yjs'\n\n/**\n * @typedef {Map} StateMap\n */\n\n/**\n * Core Yjs defines two message types:\n * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.\n * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it\n * received all information from the remote client.\n *\n * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection\n * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both\n * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.\n *\n * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.\n * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies\n * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the\n * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can\n * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them.\n * Therefore it is necesarry that the client initiates the sync.\n *\n * Construction of a message:\n * [messageType : varUint, message definition..]\n *\n * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!\n *\n * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)\n */\n\nexport const messageYjsSyncStep1 = 0\nexport const messageYjsSyncStep2 = 1\nexport const messageYjsUpdate = 2\n\n/**\n * Create a sync step 1 message based on the state of the current shared document.\n *\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n */\nexport const writeSyncStep1 = (encoder, doc) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep1)\n const sv = Y.encodeStateVector(doc)\n encoding.writeVarUint8Array(encoder, sv)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n * @param {Uint8Array} [encodedStateVector]\n */\nexport const writeSyncStep2 = (encoder, doc, encodedStateVector) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep2)\n encoding.writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector))\n}\n\n/**\n * Read SyncStep1 message and reply with SyncStep2.\n *\n * @param {decoding.Decoder} decoder The reply to the received message\n * @param {encoding.Encoder} encoder The received message\n * @param {Y.Doc} doc\n */\nexport const readSyncStep1 = (decoder, encoder, doc) =>\n writeSyncStep2(encoder, doc, decoding.readVarUint8Array(decoder))\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin) => {\n try {\n Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n } catch (error) {\n // This catches errors that are thrown by event handlers\n console.error('Caught error while handling a Yjs update', error)\n }\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Uint8Array} update\n */\nexport const writeUpdate = (encoder, update) => {\n encoding.writeVarUint(encoder, messageYjsUpdate)\n encoding.writeVarUint8Array(encoder, update)\n}\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readUpdate = readSyncStep2\n\n/**\n * @param {decoding.Decoder} decoder A message received from another client\n * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => {\n const messageType = decoding.readVarUint(decoder)\n switch (messageType) {\n case messageYjsSyncStep1:\n readSyncStep1(decoder, encoder, doc)\n break\n case messageYjsSyncStep2:\n readSyncStep2(decoder, doc, transactionOrigin)\n break\n case messageYjsUpdate:\n readUpdate(decoder, doc, transactionOrigin)\n break\n default:\n throw new Error('Unknown message type')\n }\n return messageType\n}\n","import { Encoder, createEncoder, toUint8Array } from 'lib0/encoding'\nimport { MessageType, OutgoingMessageArguments, OutgoingMessageInterface } from './types.js'\n\nexport class OutgoingMessage implements OutgoingMessageInterface {\n encoder: Encoder\n\n type?: MessageType\n\n constructor() {\n this.encoder = createEncoder()\n }\n\n get(args: Partial) {\n return args.encoder\n }\n\n toUint8Array() {\n return toUint8Array(this.encoder)\n }\n}\n","import { readAuthMessage } from '@hocuspocus/common'\nimport { readVarInt, readVarString } from 'lib0/decoding'\nimport * as awarenessProtocol from 'y-protocols/awareness'\nimport { messageYjsSyncStep2, readSyncMessage } from 'y-protocols/sync'\nimport { HocuspocusProvider } from './HocuspocusProvider.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { MessageType } from './types.js'\n\nexport class MessageReceiver {\n\n message: IncomingMessage\n\n broadcasted = false\n\n constructor(message: IncomingMessage) {\n this.message = message\n }\n\n public setBroadcasted(value: boolean) {\n this.broadcasted = value\n\n return this\n }\n\n public apply(provider: HocuspocusProvider, emitSynced: boolean) {\n const { message } = this\n const type = message.readVarUint()\n\n const emptyMessageLength = message.length()\n\n switch (type) {\n case MessageType.Sync:\n this.applySyncMessage(provider, emitSynced)\n break\n\n case MessageType.Awareness:\n this.applyAwarenessMessage(provider)\n break\n\n case MessageType.Auth:\n this.applyAuthMessage(provider)\n break\n\n case MessageType.QueryAwareness:\n this.applyQueryAwarenessMessage(provider)\n break\n\n case MessageType.Stateless:\n provider.receiveStateless(readVarString(message.decoder))\n break\n\n case MessageType.SyncStatus:\n this.applySyncStatusMessage(provider, readVarInt(message.decoder) === 1)\n break\n default:\n throw new Error(`Can’t apply message of unknown type: ${type}`)\n }\n\n // Reply\n if (message.length() > emptyMessageLength + 1) { // length of documentName (considered in emptyMessageLength plus length of yjs sync type, set in applySyncMessage)\n if (this.broadcasted) {\n // TODO: Some weird TypeScript error\n // @ts-ignore\n provider.broadcast(OutgoingMessage, { encoder: message.encoder })\n } else {\n // TODO: Some weird TypeScript error\n // @ts-ignore\n provider.send(OutgoingMessage, { encoder: message.encoder })\n }\n }\n }\n\n private applySyncMessage(provider: HocuspocusProvider, emitSynced: boolean) {\n const { message } = this\n\n message.writeVarUint(MessageType.Sync)\n\n // Apply update\n const syncMessageType = readSyncMessage(\n message.decoder,\n message.encoder,\n provider.document,\n provider,\n )\n\n // Synced once we receive Step2\n if (emitSynced && syncMessageType === messageYjsSyncStep2) {\n provider.synced = true\n }\n }\n\n applySyncStatusMessage(provider: HocuspocusProvider, applied: boolean) {\n if (applied) {\n provider.decrementUnsyncedChanges()\n }\n }\n\n private applyAwarenessMessage(provider: HocuspocusProvider) {\n const { message } = this\n\n awarenessProtocol.applyAwarenessUpdate(\n provider.awareness,\n message.readVarUint8Array(),\n provider,\n )\n }\n\n private applyAuthMessage(provider: HocuspocusProvider) {\n const { message } = this\n\n readAuthMessage(\n message.decoder,\n provider.permissionDeniedHandler.bind(provider),\n provider.authenticatedHandler.bind(provider),\n )\n }\n\n private applyQueryAwarenessMessage(provider: HocuspocusProvider) {\n const { message } = this\n\n message.writeVarUint(MessageType.Awareness)\n message.writeVarUint8Array(\n awarenessProtocol.encodeAwarenessUpdate(\n provider.awareness,\n Array.from(provider.awareness.getStates().keys()),\n ),\n )\n }\n}\n","import { Encoder, toUint8Array } from 'lib0/encoding'\nimport * as bc from 'lib0/broadcastchannel'\nimport { ConstructableOutgoingMessage } from './types.js'\n\nexport class MessageSender {\n\n encoder: Encoder\n\n message: any\n\n constructor(Message: ConstructableOutgoingMessage, args: any = {}) {\n this.message = new Message()\n this.encoder = this.message.get(args)\n }\n\n create() {\n return toUint8Array(this.encoder)\n }\n\n send(webSocket: any) {\n webSocket?.send(this.create())\n }\n\n broadcast(channel: string) {\n bc.publish(channel, this.create())\n }\n}\n","import { writeVarString, writeVarUint } from 'lib0/encoding'\nimport { writeAuthentication } from '@hocuspocus/common'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class AuthenticationMessage extends OutgoingMessage {\n type = MessageType.Auth\n\n description = 'Authentication'\n\n get(args: Partial) {\n if (typeof args.token === 'undefined') {\n throw new Error('The authentication message requires `token` as an argument.')\n }\n\n writeVarString(this.encoder, args.documentName!)\n writeVarUint(this.encoder, this.type)\n writeAuthentication(this.encoder, args.token)\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport { encodeAwarenessUpdate } from 'y-protocols/awareness'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class AwarenessMessage extends OutgoingMessage {\n type = MessageType.Awareness\n\n description = 'Awareness states update'\n\n get(args: Partial) {\n if (typeof args.awareness === 'undefined') {\n throw new Error('The awareness message requires awareness as an argument')\n }\n\n if (typeof args.clients === 'undefined') {\n throw new Error('The awareness message requires clients as an argument')\n }\n\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n\n let awarenessUpdate\n if (args.states === undefined) {\n awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients)\n } else {\n awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients, args.states)\n }\n\n encoding.writeVarUint8Array(this.encoder, awarenessUpdate)\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class CloseMessage extends OutgoingMessage {\n type = MessageType.CLOSE\n\n description = 'Ask the server to close the connection'\n\n get(args: Partial) {\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class QueryAwarenessMessage extends OutgoingMessage {\n type = MessageType.QueryAwareness\n\n description = 'Queries awareness states'\n\n get(args: Partial) {\n\n console.log('queryAwareness: writing string docName', args.documentName)\n console.log(this.encoder.cpos)\n\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n\n return this.encoder\n }\n}\n","import { writeVarString, writeVarUint } from 'lib0/encoding'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class StatelessMessage extends OutgoingMessage {\n type = MessageType.Stateless\n\n description = 'A stateless message'\n\n get(args: Partial) {\n writeVarString(this.encoder, args.documentName!)\n writeVarUint(this.encoder, this.type)\n writeVarString(this.encoder, args.payload ?? '')\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport * as syncProtocol from 'y-protocols/sync'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class SyncStepOneMessage extends OutgoingMessage {\n type = MessageType.Sync\n\n description = 'First sync step'\n\n get(args: Partial) {\n if (typeof args.document === 'undefined') {\n throw new Error('The sync step one message requires document as an argument')\n }\n\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n syncProtocol.writeSyncStep1(this.encoder, args.document)\n\n return this.encoder\n }\n}\n","import * as encoding from 'lib0/encoding'\nimport * as syncProtocol from 'y-protocols/sync'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class SyncStepTwoMessage extends OutgoingMessage {\n type = MessageType.Sync\n\n description = 'Second sync step'\n\n get(args: Partial) {\n if (typeof args.document === 'undefined') {\n throw new Error('The sync step two message requires document as an argument')\n }\n\n encoding.writeVarString(this.encoder, args.documentName!)\n encoding.writeVarUint(this.encoder, this.type)\n syncProtocol.writeSyncStep2(this.encoder, args.document)\n\n return this.encoder\n }\n}\n","import { writeVarString, writeVarUint } from 'lib0/encoding'\nimport { writeUpdate } from 'y-protocols/sync'\nimport { MessageType, OutgoingMessageArguments } from '../types.js'\nimport { OutgoingMessage } from '../OutgoingMessage.js'\n\nexport class UpdateMessage extends OutgoingMessage {\n type = MessageType.Sync\n\n description = 'A document update'\n\n get(args: Partial) {\n writeVarString(this.encoder, args.documentName!)\n writeVarUint(this.encoder, this.type)\n\n writeUpdate(this.encoder, args.update)\n\n return this.encoder\n }\n}\n","import { awarenessStatesToArray } from '@hocuspocus/common'\nimport * as bc from 'lib0/broadcastchannel'\nimport * as mutex from 'lib0/mutex'\nimport type { CloseEvent, Event, MessageEvent } from 'ws'\nimport { Awareness, removeAwarenessStates } from 'y-protocols/awareness'\nimport * as Y from 'yjs'\nimport EventEmitter from './EventEmitter.js'\nimport {\n CompleteHocuspocusProviderWebsocketConfiguration,\n HocuspocusProviderWebsocket,\n} from './HocuspocusProviderWebsocket.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { MessageReceiver } from './MessageReceiver.js'\nimport { MessageSender } from './MessageSender.js'\nimport { AuthenticationMessage } from './OutgoingMessages/AuthenticationMessage.js'\nimport { AwarenessMessage } from './OutgoingMessages/AwarenessMessage.js'\nimport { CloseMessage } from './OutgoingMessages/CloseMessage.js'\nimport { QueryAwarenessMessage } from './OutgoingMessages/QueryAwarenessMessage.js'\nimport { StatelessMessage } from './OutgoingMessages/StatelessMessage.js'\nimport { SyncStepOneMessage } from './OutgoingMessages/SyncStepOneMessage.js'\nimport { SyncStepTwoMessage } from './OutgoingMessages/SyncStepTwoMessage.js'\nimport { UpdateMessage } from './OutgoingMessages/UpdateMessage.js'\nimport {\n ConstructableOutgoingMessage,\n WebSocketStatus,\n onAuthenticationFailedParameters,\n onAwarenessChangeParameters,\n onAwarenessUpdateParameters,\n onCloseParameters,\n onDisconnectParameters,\n onMessageParameters,\n onOpenParameters,\n onOutgoingMessageParameters, onStatelessParameters,\n onStatusParameters,\n onSyncedParameters,\n} from './types.js'\n\nexport type HocuspocusProviderConfiguration =\n Required>\n & Partial & (\n Required> |\n Required>\n )\n\nexport interface CompleteHocuspocusProviderConfiguration {\n /**\n * The identifier/name of your document\n */\n name: string,\n /**\n * The actual Y.js document\n */\n document: Y.Doc,\n\n /**\n * Pass false to disable broadcasting between browser tabs.\n */\n broadcast: boolean,\n /**\n * An Awareness instance to keep the presence state of all clients.\n */\n awareness: Awareness,\n /**\n * A token that’s sent to the backend for authentication purposes.\n */\n token: string | (() => string) | (() => Promise) | null,\n /**\n * URL parameters that should be added.\n */\n parameters: { [key: string]: any },\n /**\n * Hocuspocus websocket provider\n */\n websocketProvider: HocuspocusProviderWebsocket,\n /**\n * Force syncing the document in the defined interval.\n */\n forceSyncInterval: false | number,\n\n onAuthenticated: () => void,\n onAuthenticationFailed: (data: onAuthenticationFailedParameters) => void,\n onOpen: (data: onOpenParameters) => void,\n onConnect: () => void,\n onMessage: (data: onMessageParameters) => void,\n onOutgoingMessage: (data: onOutgoingMessageParameters) => void,\n onStatus: (data: onStatusParameters) => void,\n onSynced: (data: onSyncedParameters) => void,\n onDisconnect: (data: onDisconnectParameters) => void,\n onClose: (data: onCloseParameters) => void,\n onDestroy: () => void,\n onAwarenessUpdate: (data: onAwarenessUpdateParameters) => void,\n onAwarenessChange: (data: onAwarenessChangeParameters) => void,\n onStateless: (data: onStatelessParameters) => void\n\n /**\n * Don’t output any warnings.\n */\n quiet: boolean,\n}\n\nexport class HocuspocusProvider extends EventEmitter {\n public configuration: CompleteHocuspocusProviderConfiguration = {\n name: '',\n // @ts-ignore\n document: undefined,\n // @ts-ignore\n awareness: undefined,\n token: null,\n parameters: {},\n broadcast: true,\n forceSyncInterval: false,\n onAuthenticated: () => null,\n onAuthenticationFailed: () => null,\n onOpen: () => null,\n onConnect: () => null,\n onMessage: () => null,\n onOutgoingMessage: () => null,\n onStatus: () => null,\n onSynced: () => null,\n onDisconnect: () => null,\n onClose: () => null,\n onDestroy: () => null,\n onAwarenessUpdate: () => null,\n onAwarenessChange: () => null,\n onStateless: () => null,\n quiet: false,\n }\n\n subscribedToBroadcastChannel = false\n\n isSynced = false\n\n unsyncedChanges = 0\n\n status = WebSocketStatus.Disconnected\n\n isAuthenticated = false\n\n authorizedScope: string | undefined = undefined\n\n mux = mutex.createMutex()\n\n intervals: any = {\n forceSync: null,\n }\n\n isConnected = true\n\n constructor(configuration: HocuspocusProviderConfiguration) {\n super()\n this.setConfiguration(configuration)\n\n this.configuration.document = configuration.document ? configuration.document : new Y.Doc()\n this.configuration.awareness = configuration.awareness ? configuration.awareness : new Awareness(this.document)\n\n this.on('open', this.configuration.onOpen)\n this.on('message', this.configuration.onMessage)\n this.on('outgoingMessage', this.configuration.onOutgoingMessage)\n this.on('synced', this.configuration.onSynced)\n this.on('destroy', this.configuration.onDestroy)\n this.on('awarenessUpdate', this.configuration.onAwarenessUpdate)\n this.on('awarenessChange', this.configuration.onAwarenessChange)\n this.on('stateless', this.configuration.onStateless)\n\n this.on('authenticated', this.configuration.onAuthenticated)\n this.on('authenticationFailed', this.configuration.onAuthenticationFailed)\n\n this.configuration.websocketProvider.on('connect', this.configuration.onConnect)\n this.configuration.websocketProvider.on('connect', (e: Event) => this.emit('connect', e))\n\n this.configuration.websocketProvider.on('open', this.onOpen.bind(this))\n this.configuration.websocketProvider.on('open', (e: Event) => this.emit('open', e))\n\n this.configuration.websocketProvider.on('message', this.onMessage.bind(this))\n\n this.configuration.websocketProvider.on('close', this.onClose.bind(this))\n this.configuration.websocketProvider.on('close', this.configuration.onClose)\n this.configuration.websocketProvider.on('close', (e: Event) => this.emit('close', e))\n\n this.configuration.websocketProvider.on('status', this.onStatus.bind(this))\n\n this.configuration.websocketProvider.on('disconnect', this.configuration.onDisconnect)\n this.configuration.websocketProvider.on('disconnect', (e: Event) => this.emit('disconnect', e))\n\n this.configuration.websocketProvider.on('destroy', this.configuration.onDestroy)\n this.configuration.websocketProvider.on('destroy', (e: Event) => this.emit('destroy', e))\n\n this.awareness.on('update', () => {\n this.emit('awarenessUpdate', { states: awarenessStatesToArray(this.awareness.getStates()) })\n })\n\n this.awareness.on('change', () => {\n this.emit('awarenessChange', { states: awarenessStatesToArray(this.awareness.getStates()) })\n })\n\n this.document.on('update', this.documentUpdateHandler.bind(this))\n this.awareness.on('update', this.awarenessUpdateHandler.bind(this))\n this.registerEventListeners()\n\n if (this.configuration.forceSyncInterval) {\n this.intervals.forceSync = setInterval(\n this.forceSync.bind(this),\n this.configuration.forceSyncInterval,\n )\n }\n\n this.configuration.websocketProvider.attach(this)\n }\n\n public onStatus({ status } : onStatusParameters) {\n this.status = status\n\n this.configuration.onStatus({ status })\n this.emit('status', { status })\n }\n\n public setConfiguration(configuration: Partial = {}): void {\n if (!configuration.websocketProvider && (configuration as CompleteHocuspocusProviderWebsocketConfiguration).url) {\n const websocketProviderConfig = configuration as CompleteHocuspocusProviderWebsocketConfiguration\n\n this.configuration.websocketProvider = new HocuspocusProviderWebsocket({\n url: websocketProviderConfig.url,\n parameters: websocketProviderConfig.parameters,\n })\n }\n\n this.configuration = { ...this.configuration, ...configuration }\n }\n\n get document() {\n return this.configuration.document\n }\n\n get awareness() {\n return this.configuration.awareness\n }\n\n get hasUnsyncedChanges(): boolean {\n return this.unsyncedChanges > 0\n }\n\n incrementUnsyncedChanges() {\n this.unsyncedChanges += 1\n this.emit('unsyncedChanges', this.unsyncedChanges)\n }\n\n decrementUnsyncedChanges() {\n this.unsyncedChanges -= 1\n if (this.unsyncedChanges === 0) {\n this.synced = true\n }\n this.emit('unsyncedChanges', this.unsyncedChanges)\n }\n\n forceSync() {\n this.send(SyncStepOneMessage, { document: this.document, documentName: this.configuration.name })\n }\n\n boundBeforeUnload = this.beforeUnload.bind(this)\n\n beforeUnload() {\n removeAwarenessStates(this.awareness, [this.document.clientID], 'window unload')\n }\n\n registerEventListeners() {\n if (typeof window === 'undefined') {\n return\n }\n\n window.addEventListener('beforeunload', this.boundBeforeUnload)\n }\n\n sendStateless(payload: string) {\n this.send(StatelessMessage, { documentName: this.configuration.name, payload })\n }\n\n documentUpdateHandler(update: Uint8Array, origin: any) {\n if (origin === this) {\n return\n }\n\n this.incrementUnsyncedChanges()\n this.send(UpdateMessage, { update, documentName: this.configuration.name }, true)\n }\n\n awarenessUpdateHandler({ added, updated, removed }: any, origin: any) {\n const changedClients = added.concat(updated).concat(removed)\n\n this.send(AwarenessMessage, {\n awareness: this.awareness,\n clients: changedClients,\n documentName: this.configuration.name,\n }, true)\n }\n\n get synced(): boolean {\n return this.isSynced\n }\n\n set synced(state) {\n if (this.isSynced === state) {\n return\n }\n\n this.isSynced = state\n this.emit('synced', { state })\n this.emit('sync', { state })\n }\n\n receiveStateless(payload: string) {\n this.emit('stateless', { payload })\n }\n\n get isAuthenticationRequired(): boolean {\n return !!this.configuration.token && !this.isAuthenticated\n }\n\n // not needed, but provides backward compatibility with e.g. lexicla/yjs\n async connect() {\n return this.configuration.websocketProvider.connect()\n }\n\n disconnect() {\n this.disconnectBroadcastChannel()\n this.configuration.websocketProvider.detach(this)\n }\n\n async onOpen(event: Event) {\n this.isAuthenticated = false\n\n this.emit('open', { event })\n\n if (this.isAuthenticationRequired) {\n this.send(AuthenticationMessage, {\n token: await this.getToken(),\n documentName: this.configuration.name,\n })\n }\n\n this.startSync()\n }\n\n async getToken() {\n if (typeof this.configuration.token === 'function') {\n const token = await this.configuration.token()\n return token\n }\n\n return this.configuration.token\n }\n\n startSync() {\n this.incrementUnsyncedChanges()\n this.send(SyncStepOneMessage, { document: this.document, documentName: this.configuration.name })\n\n if (this.awareness.getLocalState() !== null) {\n this.send(AwarenessMessage, {\n awareness: this.awareness,\n clients: [this.document.clientID],\n documentName: this.configuration.name,\n })\n }\n }\n\n send(message: ConstructableOutgoingMessage, args: any, broadcast = false) {\n if (!this.isConnected) {\n return\n }\n\n if (broadcast) {\n this.mux(() => { this.broadcast(message, args) })\n }\n\n const messageSender = new MessageSender(message, args)\n\n this.emit('outgoingMessage', { message: messageSender.message })\n messageSender.send(this.configuration.websocketProvider)\n }\n\n onMessage(event: MessageEvent) {\n const message = new IncomingMessage(event.data)\n\n const documentName = message.readVarString()\n\n if (documentName !== this.configuration.name) {\n return // message is meant for another provider\n }\n\n message.writeVarString(documentName)\n\n this.emit('message', { event, message: new IncomingMessage(event.data) })\n\n new MessageReceiver(message).apply(this, true)\n }\n\n onClose(event: CloseEvent) {\n this.isAuthenticated = false\n this.synced = false\n\n // update awareness (all users except local left)\n removeAwarenessStates(\n this.awareness,\n Array.from(this.awareness.getStates().keys()).filter(client => client !== this.document.clientID),\n this,\n )\n }\n\n destroy() {\n this.emit('destroy')\n\n if (this.intervals.forceSync) {\n clearInterval(this.intervals.forceSync)\n }\n\n removeAwarenessStates(this.awareness, [this.document.clientID], 'provider destroy')\n\n this.disconnect()\n\n this.awareness.off('update', this.awarenessUpdateHandler)\n this.document.off('update', this.documentUpdateHandler)\n\n this.removeAllListeners()\n\n this.send(CloseMessage, { documentName: this.configuration.name })\n this.isConnected = false\n\n if (typeof window === 'undefined') {\n return\n }\n\n window.removeEventListener('beforeunload', this.boundBeforeUnload)\n }\n\n permissionDeniedHandler(reason: string) {\n this.emit('authenticationFailed', { reason })\n this.isAuthenticated = false\n this.disconnect()\n this.status = WebSocketStatus.Disconnected\n }\n\n authenticatedHandler(scope: string) {\n this.isAuthenticated = true\n this.authorizedScope = scope\n\n this.emit('authenticated')\n this.startSync()\n }\n\n get broadcastChannel() {\n return `${this.configuration.name}`\n }\n\n boundBroadcastChannelSubscriber = this.broadcastChannelSubscriber.bind(this)\n\n broadcastChannelSubscriber(data: ArrayBuffer) {\n this.mux(() => {\n const message = new IncomingMessage(data)\n\n const documentName = message.readVarString()\n\n message.writeVarString(documentName)\n\n new MessageReceiver(message)\n .setBroadcasted(true)\n .apply(this, false)\n })\n }\n\n subscribeToBroadcastChannel() {\n if (!this.subscribedToBroadcastChannel) {\n bc.subscribe(this.broadcastChannel, this.boundBroadcastChannelSubscriber)\n this.subscribedToBroadcastChannel = true\n }\n\n this.mux(() => {\n this.broadcast(SyncStepOneMessage, { document: this.document })\n this.broadcast(SyncStepTwoMessage, { document: this.document })\n this.broadcast(QueryAwarenessMessage, { document: this.document })\n this.broadcast(AwarenessMessage, { awareness: this.awareness, clients: [this.document.clientID], document: this.document })\n })\n }\n\n disconnectBroadcastChannel() {\n // broadcast message with local awareness state set to null (indicating disconnect)\n this.send(AwarenessMessage, {\n awareness: this.awareness,\n clients: [this.document.clientID],\n states: new Map(),\n documentName: this.configuration.name,\n }, true)\n\n if (this.subscribedToBroadcastChannel) {\n bc.unsubscribe(this.broadcastChannel, this.boundBroadcastChannelSubscriber)\n this.subscribedToBroadcastChannel = false\n }\n }\n\n broadcast(Message: ConstructableOutgoingMessage, args?: any) {\n if (!this.configuration.broadcast) {\n return\n }\n\n if (!this.subscribedToBroadcastChannel) {\n return\n }\n\n new MessageSender(Message, args).broadcast(this.broadcastChannel)\n }\n\n setAwarenessField(key: string, value: any) {\n this.awareness.setLocalStateField(key, value)\n }\n}\n","import {\n CompleteHocuspocusProviderWebsocketConfiguration,\n HocuspocusProviderWebsocket, HocuspocusProviderWebsocketConfiguration,\n} from './HocuspocusProviderWebsocket.js'\n\nexport type TiptapCollabProviderWebsocketConfiguration =\n Partial &\n AdditionalTiptapCollabProviderWebsocketConfiguration\n\nexport interface AdditionalTiptapCollabProviderWebsocketConfiguration {\n /**\n * A Hocuspocus Cloud App ID, get one here: https://collab.tiptap.dev\n */\n appId: string,\n}\n\nexport class TiptapCollabProviderWebsocket extends HocuspocusProviderWebsocket {\n constructor(configuration: TiptapCollabProviderWebsocketConfiguration) {\n super({ ...configuration as HocuspocusProviderWebsocketConfiguration, url: `wss://${configuration.appId}.collab.tiptap.cloud` })\n }\n}\n","import {\n HocuspocusProvider,\n HocuspocusProviderConfiguration,\n} from './HocuspocusProvider.js'\n\nimport { TiptapCollabProviderWebsocket } from './TiptapCollabProviderWebsocket.js'\n\nexport type TiptapCollabProviderConfiguration =\n Required> &\n Partial &\n AdditionalTiptapCollabProviderConfiguration\n\nexport interface AdditionalTiptapCollabProviderConfiguration {\n /**\n * A Hocuspocus Cloud App ID, get one here: https://collab.tiptap.dev\n */\n appId: string,\n}\n\nexport class TiptapCollabProvider extends HocuspocusProvider {\n constructor(configuration: TiptapCollabProviderConfiguration) {\n if (!configuration.websocketProvider) {\n configuration.websocketProvider = new TiptapCollabProviderWebsocket({ appId: configuration.appId })\n }\n\n if (!configuration.token) {\n configuration.token = 'notoken' // need to send a token anyway (which will be ignored)\n }\n\n super(configuration as HocuspocusProviderConfiguration)\n }\n}\n"],"names":["create","length","object.length","object.hasProperty","map.create","string.fromCamelCase","conditions.undefinedToNull","storage.varStorage","f.isOneOf","buffer.createUint8ArrayViewFromArrayBuffer","binary.BITS7","binary.BIT8","math.floor","string.utf8TextEncoder","string.encodeUtf8","math.min","math.max","error.create","number.MAX_SAFE_INTEGER","binary.BITS6","binary.BIT7","string.utf8TextDecoder","string.fromCharCode","env.isBrowser","buffer.fromBase64","storage.onChange","buffer.toBase64","buffer.createUint8ArrayFromArrayBuffer","storage.offChange","map.setIfUndefined","set.create","array.from","time.getUnixTime","f.equalityDeep","encoding.createEncoder","encoding.writeVarUint","encoding.writeVarString","encoding.toUint8Array","decoding.createDecoder","decoding.readVarUint","decoding.readVarString","object.map","mutex.createMutex","url.encodeQueryParams","encoding.writeVarUint8Array","decoding.readVarUint8Array","awarenessProtocol.applyAwarenessUpdate","awarenessProtocol.encodeAwarenessUpdate","bc.publish","syncProtocol.writeSyncStep1","syncProtocol.writeSyncStep2","bc.subscribe","bc.unsubscribe"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMA,QAAM,GAAG,MAAM,IAAI,GAAG,GAAE;AAerC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,cAAc,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,KAAK;AACrD,EAAE,IAAI,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,EAAC;AACxB,E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Y,aAAgD,EAAA;AAC1D,QAAA,IAAI,CAAC,aAAa,CAAC,iBAAiB,EAAE;AACpC,YAAA,aAAa,CAAC,iBAAiB,GAAG,IAAI,6BAA6B,CAAC,EAAE,KAAK,EAAE,aAAa,CAAC,KAAK,EAAE,CAAC,CAAA;AACpG,SAAA;AAED,QAAA,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE;AACxB,YAAA,aAAa,CAAC,KAAK,GAAG,SAAS,CAAA;AAChC,SAAA;QAED,KAAK,CAAC,aAAgD,CAAC,CAAA;KACxD;AACF;;;;"} -\ No newline at end of file -diff --git a/node_modules/@hocuspocus/provider/dist/packages/provider/src/HocuspocusProvider.d.ts b/node_modules/@hocuspocus/provider/dist/packages/provider/src/HocuspocusProvider.d.ts -index dffe09b..2168445 100644 ---- a/node_modules/@hocuspocus/provider/dist/packages/provider/src/HocuspocusProvider.d.ts -+++ b/node_modules/@hocuspocus/provider/dist/packages/provider/src/HocuspocusProvider.d.ts -@@ -1,10 +1,10 @@ --import * as Y from 'yjs'; --import { Awareness } from 'y-protocols/awareness'; - import * as mutex from 'lib0/mutex'; - import type { CloseEvent, Event, MessageEvent } from 'ws'; -+import { Awareness } from 'y-protocols/awareness'; -+import * as Y from 'yjs'; - import EventEmitter from './EventEmitter.js'; --import { ConstructableOutgoingMessage, onAuthenticationFailedParameters, onCloseParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onStatelessParameters, onStatusParameters, onSyncedParameters, WebSocketStatus, onAwarenessChangeParameters, onAwarenessUpdateParameters } from './types.js'; - import { CompleteHocuspocusProviderWebsocketConfiguration, HocuspocusProviderWebsocket } from './HocuspocusProviderWebsocket.js'; -+import { ConstructableOutgoingMessage, WebSocketStatus, onAuthenticationFailedParameters, onAwarenessChangeParameters, onAwarenessUpdateParameters, onCloseParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onStatelessParameters, onStatusParameters, onSyncedParameters } from './types.js'; - export type HocuspocusProviderConfiguration = Required> & Partial & (Required> | Required>); - export interface CompleteHocuspocusProviderConfiguration { - /** -@@ -77,7 +77,8 @@ export declare class HocuspocusProvider extends EventEmitter { - get document(): Y.Doc; - get awareness(): Awareness; - get hasUnsyncedChanges(): boolean; -- updateUnsyncedChanges(unsyncedChanges?: number): void; -+ incrementUnsyncedChanges(): void; -+ decrementUnsyncedChanges(): void; - forceSync(): void; - boundBeforeUnload: () => void; - beforeUnload(): void; -diff --git a/node_modules/@hocuspocus/provider/dist/packages/provider/src/HocuspocusProviderWebsocket.d.ts b/node_modules/@hocuspocus/provider/dist/packages/provider/src/HocuspocusProviderWebsocket.d.ts -index a3abfae..866ab85 100644 ---- a/node_modules/@hocuspocus/provider/dist/packages/provider/src/HocuspocusProviderWebsocket.d.ts -+++ b/node_modules/@hocuspocus/provider/dist/packages/provider/src/HocuspocusProviderWebsocket.d.ts -@@ -2,8 +2,8 @@ import * as mutex from 'lib0/mutex'; - import type { MessageEvent } from 'ws'; - import { Event } from 'ws'; - import EventEmitter from './EventEmitter.js'; --import { onCloseParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onStatusParameters, WebSocketStatus, onAwarenessChangeParameters, onAwarenessUpdateParameters } from './types.js'; - import { HocuspocusProvider } from './HocuspocusProvider.js'; -+import { WebSocketStatus, onAwarenessChangeParameters, onAwarenessUpdateParameters, onCloseParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onStatusParameters } from './types.js'; - export type HocuspocusProviderWebsocketConfiguration = Required> & Partial; - export interface CompleteHocuspocusProviderWebsocketConfiguration { - /** -@@ -76,6 +76,7 @@ export interface CompleteHocuspocusProviderWebsocketConfiguration { - quiet: boolean; - } - export declare class HocuspocusProviderWebsocket extends EventEmitter { -+ private messageQueue; - configuration: CompleteHocuspocusProviderWebsocketConfiguration; - subscribedToBroadcastChannel: boolean; - webSocket: WebSocket | null; -diff --git a/node_modules/@hocuspocus/provider/dist/packages/provider/src/MessageReceiver.d.ts b/node_modules/@hocuspocus/provider/dist/packages/provider/src/MessageReceiver.d.ts -index 8e5d55c..4d41340 100644 ---- a/node_modules/@hocuspocus/provider/dist/packages/provider/src/MessageReceiver.d.ts -+++ b/node_modules/@hocuspocus/provider/dist/packages/provider/src/MessageReceiver.d.ts -@@ -5,8 +5,9 @@ export declare class MessageReceiver { - broadcasted: boolean; - constructor(message: IncomingMessage); - setBroadcasted(value: boolean): this; -- apply(provider: HocuspocusProvider, emitSynced?: boolean): void; -+ apply(provider: HocuspocusProvider, emitSynced: boolean): void; - private applySyncMessage; -+ applySyncStatusMessage(provider: HocuspocusProvider, applied: boolean): void; - private applyAwarenessMessage; - private applyAuthMessage; - private applyQueryAwarenessMessage; -diff --git a/node_modules/@hocuspocus/provider/dist/packages/provider/src/types.d.ts b/node_modules/@hocuspocus/provider/dist/packages/provider/src/types.d.ts -index 1a67c25..fd3379e 100644 ---- a/node_modules/@hocuspocus/provider/dist/packages/provider/src/types.d.ts -+++ b/node_modules/@hocuspocus/provider/dist/packages/provider/src/types.d.ts -@@ -1,22 +1,23 @@ -+import { Encoder } from 'lib0/encoding'; -+import type { CloseEvent, Event, MessageEvent } from 'ws'; - import { Awareness } from 'y-protocols/awareness'; - import * as Y from 'yjs'; --import { Encoder } from 'lib0/encoding'; --import type { Event, CloseEvent, MessageEvent } from 'ws'; -+import { IncomingMessage } from './IncomingMessage.js'; -+import { OutgoingMessage } from './OutgoingMessage.js'; - import { AuthenticationMessage } from './OutgoingMessages/AuthenticationMessage.js'; - import { AwarenessMessage } from './OutgoingMessages/AwarenessMessage.js'; - import { QueryAwarenessMessage } from './OutgoingMessages/QueryAwarenessMessage.js'; - import { SyncStepOneMessage } from './OutgoingMessages/SyncStepOneMessage.js'; - import { SyncStepTwoMessage } from './OutgoingMessages/SyncStepTwoMessage.js'; - import { UpdateMessage } from './OutgoingMessages/UpdateMessage.js'; --import { IncomingMessage } from './IncomingMessage.js'; --import { OutgoingMessage } from './OutgoingMessage.js'; - export declare enum MessageType { - Sync = 0, - Awareness = 1, - Auth = 2, - QueryAwareness = 3, - Stateless = 5, -- CLOSE = 7 -+ CLOSE = 7, -+ SyncStatus = 8 - } - export declare enum WebSocketStatus { - Connecting = "connecting", -diff --git a/node_modules/@hocuspocus/provider/dist/packages/server/src/ClientConnection.d.ts b/node_modules/@hocuspocus/provider/dist/packages/server/src/ClientConnection.d.ts -new file mode 100644 -index 0000000..894206f ---- /dev/null -+++ b/node_modules/@hocuspocus/provider/dist/packages/server/src/ClientConnection.d.ts -@@ -0,0 +1,55 @@ -+/// -+import { IncomingMessage } from 'http'; -+import WebSocket from 'ws'; -+import { Debugger } from './Debugger.js'; -+import Document from './Document.js'; -+import { Hocuspocus } from './Hocuspocus.js'; -+import { onDisconnectPayload } from './types.js'; -+/** -+ * The `ClientConnection` class is responsible for handling an incoming WebSocket -+ * -+ * TODO-refactor: -+ * - use event handlers instead of calling hooks directly, hooks should probably be called from Hocuspocus.ts -+ */ -+export declare class ClientConnection { -+ private readonly websocket; -+ private readonly request; -+ private readonly documentProvider; -+ private readonly hooks; -+ private readonly debuggerTool; -+ private readonly opts; -+ private readonly documentConnections; -+ private readonly incomingMessageQueue; -+ private readonly documentConnectionsEstablished; -+ private readonly hookPayloads; -+ private readonly callbacks; -+ private readonly closeIdleConnectionTimeout; -+ private readonly socketId; -+ /** -+ * The `ClientConnection` class receives incoming WebSocket connections, -+ * runs all hooks: -+ * -+ * - onConnect for all connections -+ * - onAuthenticate only if required -+ * -+ * … and if nothings fails it’ll fully establish the connection and -+ * load the Document then. -+ */ -+ constructor(websocket: WebSocket, request: IncomingMessage, documentProvider: { -+ createDocument: Hocuspocus['createDocument']; -+ }, hooks: Hocuspocus['hooks'], debuggerTool: Debugger, opts: { -+ requiresAuthentication: boolean; -+ timeout: number; -+ }); -+ /** -+ * Set a callback that will be triggered when the connection is closed -+ */ -+ onClose(callback: (document: Document, payload: onDisconnectPayload) => void): ClientConnection; -+ /** -+ * Create a new connection by the given request and document -+ */ -+ private createConnection; -+ private setUpNewConnection; -+ private handleQueueingMessage; -+ private messageHandler; -+} -diff --git a/node_modules/@hocuspocus/provider/dist/packages/server/src/Hocuspocus.d.ts b/node_modules/@hocuspocus/provider/dist/packages/server/src/Hocuspocus.d.ts -index 2709615..90d46c5 100644 ---- a/node_modules/@hocuspocus/provider/dist/packages/server/src/Hocuspocus.d.ts -+++ b/node_modules/@hocuspocus/provider/dist/packages/server/src/Hocuspocus.d.ts -@@ -1,11 +1,11 @@ - /// - /// --import { IncomingMessage, Server as HTTPServer } from 'http'; -+import { Server as HTTPServer, IncomingMessage } from 'http'; - import WebSocket, { AddressInfo, WebSocketServer } from 'ws'; --import { Configuration, HookName, HookPayload, onListenPayload, onStoreDocumentPayload } from './types.js'; --import Document from './Document.js'; - import { Debugger } from './Debugger.js'; - import { DirectConnection } from './DirectConnection.js'; -+import Document from './Document.js'; -+import { Configuration, ConnectionConfiguration, HookName, HookPayload, onListenPayload, onStoreDocumentPayload } from './types.js'; - export declare const defaultConfiguration: { - name: null; - port: number; -@@ -69,7 +69,7 @@ export declare class Hocuspocus { - * … and if nothings fails it’ll fully establish the connection and - * load the Document then. - */ -- handleConnection(incoming: WebSocket, request: IncomingMessage, context?: any): void; -+ handleConnection(incoming: WebSocket, request: IncomingMessage): void; - /** - * Handle update of the given document - */ -@@ -85,21 +85,13 @@ export declare class Hocuspocus { - /** - * Create a new document by the given request - */ -- private createDocument; -- /** -- * Create a new connection by the given request and document -- */ -- private createConnection; -+ createDocument(documentName: string, request: Partial>, socketId: string, connection: ConnectionConfiguration, context?: any): Promise; - storeDocumentHooks(document: Document, hookPayload: onStoreDocumentPayload): void; - /** - * Run the given hook on all configured extensions. - * Runs the given callback after each hook. - */ - hooks(name: HookName, payload: HookPayload, callback?: Function | null): Promise; -- /** -- * Get parameters by the given request -- */ -- private static getParameters; - enableDebugging(): void; - enableMessageLogging(): void; - disableLogging(): void; -diff --git a/node_modules/@hocuspocus/provider/dist/packages/server/src/MessageReceiver.d.ts b/node_modules/@hocuspocus/provider/dist/packages/server/src/MessageReceiver.d.ts -index 8a0a68a..7c12f51 100644 ---- a/node_modules/@hocuspocus/provider/dist/packages/server/src/MessageReceiver.d.ts -+++ b/node_modules/@hocuspocus/provider/dist/packages/server/src/MessageReceiver.d.ts -@@ -1,7 +1,7 @@ - import Connection from './Connection.js'; --import { IncomingMessage } from './IncomingMessage.js'; - import { Debugger } from './Debugger.js'; - import Document from './Document.js'; -+import { IncomingMessage } from './IncomingMessage.js'; - export declare class MessageReceiver { - message: IncomingMessage; - logger: Debugger; -diff --git a/node_modules/@hocuspocus/provider/dist/packages/server/src/OutgoingMessage.d.ts b/node_modules/@hocuspocus/provider/dist/packages/server/src/OutgoingMessage.d.ts -index dbd17e3..8cb4f13 100644 ---- a/node_modules/@hocuspocus/provider/dist/packages/server/src/OutgoingMessage.d.ts -+++ b/node_modules/@hocuspocus/provider/dist/packages/server/src/OutgoingMessage.d.ts -@@ -16,5 +16,6 @@ export declare class OutgoingMessage { - writeUpdate(update: Uint8Array): OutgoingMessage; - writeStateless(payload: string): OutgoingMessage; - writeBroadcastStateless(payload: string): OutgoingMessage; -+ writeSyncStatus(updateSaved: boolean): OutgoingMessage; - toUint8Array(): Uint8Array; - } -diff --git a/node_modules/@hocuspocus/provider/dist/packages/server/src/types.d.ts b/node_modules/@hocuspocus/provider/dist/packages/server/src/types.d.ts -index 30e719d..d905fc0 100644 ---- a/node_modules/@hocuspocus/provider/dist/packages/server/src/types.d.ts -+++ b/node_modules/@hocuspocus/provider/dist/packages/server/src/types.d.ts -@@ -4,9 +4,9 @@ - import { IncomingHttpHeaders, IncomingMessage, ServerResponse } from 'http'; - import { URLSearchParams } from 'url'; - import { Awareness } from 'y-protocols/awareness'; -+import Connection from './Connection.js'; - import Document from './Document.js'; - import { Hocuspocus } from './Hocuspocus.js'; --import Connection from './Connection.js'; - export declare enum MessageType { - Unknown = -1, - Sync = 0, -@@ -16,7 +16,8 @@ export declare enum MessageType { - SyncReply = 4, - Stateless = 5, - BroadcastStateless = 6, -- CLOSE = 7 -+ CLOSE = 7, -+ SyncStatus = 8 - } - export interface AwarenessUpdate { - added: Array; -diff --git a/node_modules/@hocuspocus/provider/dist/packages/server/src/util/getParameters.d.ts b/node_modules/@hocuspocus/provider/dist/packages/server/src/util/getParameters.d.ts -new file mode 100644 -index 0000000..9e5f4cf ---- /dev/null -+++ b/node_modules/@hocuspocus/provider/dist/packages/server/src/util/getParameters.d.ts -@@ -0,0 +1,8 @@ -+/// -+/// -+import { IncomingMessage } from 'http'; -+import { URLSearchParams } from 'url'; -+/** -+ * Get parameters by the given request -+ */ -+export declare function getParameters(request?: Pick): URLSearchParams; -diff --git a/node_modules/@hocuspocus/provider/dist/tests/provider/hasUnsyncedChanges.d.ts b/node_modules/@hocuspocus/provider/dist/tests/provider/hasUnsyncedChanges.d.ts -new file mode 100644 -index 0000000..cb0ff5c ---- /dev/null -+++ b/node_modules/@hocuspocus/provider/dist/tests/provider/hasUnsyncedChanges.d.ts -@@ -0,0 +1 @@ -+export {}; -diff --git a/node_modules/@hocuspocus/provider/src/HocuspocusProvider.ts b/node_modules/@hocuspocus/provider/src/HocuspocusProvider.ts -index 3a366e3..49b7856 100644 ---- a/node_modules/@hocuspocus/provider/src/HocuspocusProvider.ts -+++ b/node_modules/@hocuspocus/provider/src/HocuspocusProvider.ts -@@ -1,22 +1,31 @@ --import * as Y from 'yjs' -+import { awarenessStatesToArray } from '@hocuspocus/common' - import * as bc from 'lib0/broadcastchannel' --import { Awareness, removeAwarenessStates } from 'y-protocols/awareness' - import * as mutex from 'lib0/mutex' - import type { CloseEvent, Event, MessageEvent } from 'ws' --import { awarenessStatesToArray } from '@hocuspocus/common' -+import { Awareness, removeAwarenessStates } from 'y-protocols/awareness' -+import * as Y from 'yjs' - import EventEmitter from './EventEmitter.js' -+import { -+ CompleteHocuspocusProviderWebsocketConfiguration, -+ HocuspocusProviderWebsocket, -+} from './HocuspocusProviderWebsocket.js' - import { IncomingMessage } from './IncomingMessage.js' - import { MessageReceiver } from './MessageReceiver.js' - import { MessageSender } from './MessageSender.js' --import { SyncStepOneMessage } from './OutgoingMessages/SyncStepOneMessage.js' --import { SyncStepTwoMessage } from './OutgoingMessages/SyncStepTwoMessage.js' --import { QueryAwarenessMessage } from './OutgoingMessages/QueryAwarenessMessage.js' - import { AuthenticationMessage } from './OutgoingMessages/AuthenticationMessage.js' - import { AwarenessMessage } from './OutgoingMessages/AwarenessMessage.js' -+import { CloseMessage } from './OutgoingMessages/CloseMessage.js' -+import { QueryAwarenessMessage } from './OutgoingMessages/QueryAwarenessMessage.js' -+import { StatelessMessage } from './OutgoingMessages/StatelessMessage.js' -+import { SyncStepOneMessage } from './OutgoingMessages/SyncStepOneMessage.js' -+import { SyncStepTwoMessage } from './OutgoingMessages/SyncStepTwoMessage.js' - import { UpdateMessage } from './OutgoingMessages/UpdateMessage.js' - import { - ConstructableOutgoingMessage, -+ WebSocketStatus, - onAuthenticationFailedParameters, -+ onAwarenessChangeParameters, -+ onAwarenessUpdateParameters, - onCloseParameters, - onDisconnectParameters, - onMessageParameters, -@@ -24,16 +33,7 @@ import { - onOutgoingMessageParameters, onStatelessParameters, - onStatusParameters, - onSyncedParameters, -- WebSocketStatus, -- onAwarenessChangeParameters, -- onAwarenessUpdateParameters, - } from './types.js' --import { -- CompleteHocuspocusProviderWebsocketConfiguration, -- HocuspocusProviderWebsocket, --} from './HocuspocusProviderWebsocket.js' --import { StatelessMessage } from './OutgoingMessages/StatelessMessage.js' --import { CloseMessage } from './OutgoingMessages/CloseMessage.js' - - export type HocuspocusProviderConfiguration = - Required> -@@ -239,8 +239,16 @@ export class HocuspocusProvider extends EventEmitter { - return this.unsyncedChanges > 0 - } - -- updateUnsyncedChanges(unsyncedChanges = 0) { -- this.unsyncedChanges += unsyncedChanges -+ incrementUnsyncedChanges() { -+ this.unsyncedChanges += 1 -+ this.emit('unsyncedChanges', this.unsyncedChanges) -+ } -+ -+ decrementUnsyncedChanges() { -+ this.unsyncedChanges -= 1 -+ if (this.unsyncedChanges === 0) { -+ this.synced = true -+ } - this.emit('unsyncedChanges', this.unsyncedChanges) - } - -@@ -271,7 +279,7 @@ export class HocuspocusProvider extends EventEmitter { - return - } - -- this.updateUnsyncedChanges(1) -+ this.incrementUnsyncedChanges() - this.send(UpdateMessage, { update, documentName: this.configuration.name }, true) - } - -@@ -285,6 +293,12 @@ export class HocuspocusProvider extends EventEmitter { - }, true) - } - -+ /** -+ * Indicates whether a first handshake with the server has been established -+ * -+ * Note: this does not mean all updates from the client have been persisted to the backend. For this, -+ * use `hasUnsyncedChanges`. -+ */ - get synced(): boolean { - return this.isSynced - } -@@ -294,10 +308,6 @@ export class HocuspocusProvider extends EventEmitter { - return - } - -- if (state && this.unsyncedChanges > 0) { -- this.updateUnsyncedChanges(-1 * this.unsyncedChanges) -- } -- - this.isSynced = state - this.emit('synced', { state }) - this.emit('sync', { state }) -@@ -346,6 +356,7 @@ export class HocuspocusProvider extends EventEmitter { - } - - startSync() { -+ this.incrementUnsyncedChanges() - this.send(SyncStepOneMessage, { document: this.document, documentName: this.configuration.name }) - - if (this.awareness.getLocalState() !== null) { -@@ -358,7 +369,9 @@ export class HocuspocusProvider extends EventEmitter { - } - - send(message: ConstructableOutgoingMessage, args: any, broadcast = false) { -- if (!this.isConnected) return -+ if (!this.isConnected) { -+ return -+ } - - if (broadcast) { - this.mux(() => { this.broadcast(message, args) }) -@@ -383,7 +396,7 @@ export class HocuspocusProvider extends EventEmitter { - - this.emit('message', { event, message: new IncomingMessage(event.data) }) - -- new MessageReceiver(message).apply(this) -+ new MessageReceiver(message).apply(this, true) - } - - onClose(event: CloseEvent) { -diff --git a/node_modules/@hocuspocus/provider/src/HocuspocusProviderWebsocket.ts b/node_modules/@hocuspocus/provider/src/HocuspocusProviderWebsocket.ts -index eb2a7e1..82db71e 100644 ---- a/node_modules/@hocuspocus/provider/src/HocuspocusProviderWebsocket.ts -+++ b/node_modules/@hocuspocus/provider/src/HocuspocusProviderWebsocket.ts -@@ -1,18 +1,19 @@ --import * as time from 'lib0/time' --import * as mutex from 'lib0/mutex' --import * as url from 'lib0/url' --import type { MessageEvent } from 'ws' --import { retry } from '@lifeomic/attempt' - import { - Forbidden, MessageTooBig, Unauthorized, WsReadyStates, - } from '@hocuspocus/common' -+import { retry } from '@lifeomic/attempt' -+import * as mutex from 'lib0/mutex' -+import * as time from 'lib0/time' -+import * as url from 'lib0/url' -+import type { MessageEvent } from 'ws' - import { Event } from 'ws' - import EventEmitter from './EventEmitter.js' -+import { HocuspocusProvider } from './HocuspocusProvider.js' - import { -- onCloseParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onStatusParameters, WebSocketStatus, -+ WebSocketStatus, - onAwarenessChangeParameters, onAwarenessUpdateParameters, -+ onCloseParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onStatusParameters, - } from './types.js' --import { HocuspocusProvider } from './HocuspocusProvider.js' - - export type HocuspocusProviderWebsocketConfiguration = - Required> -@@ -91,6 +92,8 @@ export interface CompleteHocuspocusProviderWebsocketConfiguration { - } - - export class HocuspocusProviderWebsocket extends EventEmitter { -+ private messageQueue: any[] = [] -+ - public configuration: CompleteHocuspocusProviderWebsocketConfiguration = { - url: '', - // @ts-ignore -@@ -285,6 +288,7 @@ export class HocuspocusProviderWebsocket extends EventEmitter { - createWebSocketConnection() { - return new Promise((resolve, reject) => { - if (this.webSocket) { -+ this.messageQueue = [] - this.webSocket.close() - this.webSocket = null - } -@@ -324,6 +328,8 @@ export class HocuspocusProviderWebsocket extends EventEmitter { - this.status = WebSocketStatus.Connected - this.emit('status', { status: WebSocketStatus.Connected }) - this.emit('connect') -+ this.messageQueue.forEach(message => this.send(message)) -+ this.messageQueue = [] - } - } - -@@ -355,6 +361,7 @@ export class HocuspocusProviderWebsocket extends EventEmitter { - // No message received in a long time, not even your own - // Awareness updates, which are updated every 15 seconds. - this.webSocket?.close() -+ this.messageQueue = [] - } - - registerEventListeners() { -@@ -389,6 +396,7 @@ export class HocuspocusProviderWebsocket extends EventEmitter { - - try { - this.webSocket.close() -+ this.messageQueue = [] - } catch { - // - } -@@ -397,6 +405,8 @@ export class HocuspocusProviderWebsocket extends EventEmitter { - send(message: any) { - if (this.webSocket?.readyState === WsReadyStates.Open) { - this.webSocket.send(message) -+ } else { -+ this.messageQueue.push(message) - } - } - -diff --git a/node_modules/@hocuspocus/provider/src/MessageReceiver.ts b/node_modules/@hocuspocus/provider/src/MessageReceiver.ts -index b6847e9..08eac73 100644 ---- a/node_modules/@hocuspocus/provider/src/MessageReceiver.ts -+++ b/node_modules/@hocuspocus/provider/src/MessageReceiver.ts -@@ -1,11 +1,11 @@ --import * as awarenessProtocol from 'y-protocols/awareness' --import { readSyncMessage, messageYjsSyncStep2, messageYjsUpdate } from 'y-protocols/sync' - import { readAuthMessage } from '@hocuspocus/common' --import { readVarString } from 'lib0/decoding' --import { MessageType } from './types.js' -+import { readVarInt, readVarString } from 'lib0/decoding' -+import * as awarenessProtocol from 'y-protocols/awareness' -+import { messageYjsSyncStep2, readSyncMessage } from 'y-protocols/sync' - import { HocuspocusProvider } from './HocuspocusProvider.js' - import { IncomingMessage } from './IncomingMessage.js' - import { OutgoingMessage } from './OutgoingMessage.js' -+import { MessageType } from './types.js' - - export class MessageReceiver { - -@@ -23,7 +23,7 @@ export class MessageReceiver { - return this - } - -- public apply(provider: HocuspocusProvider, emitSynced = true) { -+ public apply(provider: HocuspocusProvider, emitSynced: boolean) { - const { message } = this - const type = message.readVarUint() - -@@ -50,6 +50,9 @@ export class MessageReceiver { - provider.receiveStateless(readVarString(message.decoder)) - break - -+ case MessageType.SyncStatus: -+ this.applySyncStatusMessage(provider, readVarInt(message.decoder) === 1) -+ break - default: - throw new Error(`Can’t apply message of unknown type: ${type}`) - } -@@ -85,11 +88,11 @@ export class MessageReceiver { - if (emitSynced && syncMessageType === messageYjsSyncStep2) { - provider.synced = true - } -+ } - -- if (syncMessageType === messageYjsUpdate || syncMessageType === messageYjsSyncStep2) { -- if (provider.unsyncedChanges > 0) { -- provider.updateUnsyncedChanges(-1) -- } -+ applySyncStatusMessage(provider: HocuspocusProvider, applied: boolean) { -+ if (applied) { -+ provider.decrementUnsyncedChanges() - } - } - -diff --git a/node_modules/@hocuspocus/provider/src/types.ts b/node_modules/@hocuspocus/provider/src/types.ts -index c7a6ede..f18eced 100644 ---- a/node_modules/@hocuspocus/provider/src/types.ts -+++ b/node_modules/@hocuspocus/provider/src/types.ts -@@ -1,15 +1,15 @@ -+import { Encoder } from 'lib0/encoding' -+import type { CloseEvent, Event, MessageEvent } from 'ws' - import { Awareness } from 'y-protocols/awareness' - import * as Y from 'yjs' --import { Encoder } from 'lib0/encoding' --import type { Event, CloseEvent, MessageEvent } from 'ws' -+import { IncomingMessage } from './IncomingMessage.js' -+import { OutgoingMessage } from './OutgoingMessage.js' - import { AuthenticationMessage } from './OutgoingMessages/AuthenticationMessage.js' - import { AwarenessMessage } from './OutgoingMessages/AwarenessMessage.js' - import { QueryAwarenessMessage } from './OutgoingMessages/QueryAwarenessMessage.js' - import { SyncStepOneMessage } from './OutgoingMessages/SyncStepOneMessage.js' - import { SyncStepTwoMessage } from './OutgoingMessages/SyncStepTwoMessage.js' - import { UpdateMessage } from './OutgoingMessages/UpdateMessage.js' --import { IncomingMessage } from './IncomingMessage.js' --import { OutgoingMessage } from './OutgoingMessage.js' - - export enum MessageType { - Sync = 0, -@@ -18,6 +18,7 @@ export enum MessageType { - QueryAwareness = 3, - Stateless = 5, - CLOSE = 7, -+ SyncStatus = 8, - } - - export enum WebSocketStatus { diff --git a/patches/@hocuspocus+server+2.1.0.patch b/patches/@hocuspocus+server+2.1.0.patch deleted file mode 100644 index 0358e03b5..000000000 --- a/patches/@hocuspocus+server+2.1.0.patch +++ /dev/null @@ -1,4862 +0,0 @@ -diff --git a/node_modules/@hocuspocus/server/CHANGELOG.md b/node_modules/@hocuspocus/server/CHANGELOG.md -new file mode 100644 -index 0000000..05afa13 ---- /dev/null -+++ b/node_modules/@hocuspocus/server/CHANGELOG.md -@@ -0,0 +1,1100 @@ -+# Change Log -+ -+All notable changes to this project will be documented in this file. -+See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. -+ -+# [2.1.0](https://github.com/ueberdosis/hocuspocus/compare/v2.0.6...v2.1.0) (2023-06-03) -+ -+ -+### Bug Fixes -+ -+* export typings for recent typescript ([#602](https://github.com/ueberdosis/hocuspocus/issues/602)) ([551d27f](https://github.com/ueberdosis/hocuspocus/commit/551d27fa6de9c746c67bf0f1e3bb56167aebbca5)), closes [/github.com/artalar/reatom/issues/560#issuecomment-1528997739](https://github.com//github.com/artalar/reatom/issues/560/issues/issuecomment-1528997739) -+ -+ -+ -+ -+ -+## [2.0.6](https://github.com/ueberdosis/hocuspocus/compare/v2.0.5...v2.0.6) (2023-04-25) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+## [2.0.5](https://github.com/ueberdosis/hocuspocus/compare/v2.0.4...v2.0.5) (2023-04-24) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+## [2.0.4](https://github.com/ueberdosis/hocuspocus/compare/v2.0.3...v2.0.4) (2023-04-23) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+## [2.0.3](https://github.com/ueberdosis/hocuspocus/compare/v2.0.2...v2.0.3) (2023-04-05) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+## [2.0.2](https://github.com/ueberdosis/hocuspocus/compare/v2.0.1...v2.0.2) (2023-04-04) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+## [2.0.1](https://github.com/ueberdosis/hocuspocus/compare/v2.0.0...v2.0.1) (2023-03-30) -+ -+ -+### Bug Fixes -+ -+* connection.sendStateless error when connections more than one ([#556](https://github.com/ueberdosis/hocuspocus/issues/556)) ([9a9260f](https://github.com/ueberdosis/hocuspocus/commit/9a9260ffd5ee559bdc4f8ba4e7c1b1c12c2944d0)) -+ -+ -+ -+ -+ -+# [2.0.0](https://github.com/ueberdosis/hocuspocus/compare/v1.1.3...v2.0.0) (2023-03-29) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [2.0.0-beta.0](https://github.com/ueberdosis/hocuspocus/compare/v1.1.1...v2.0.0-beta.0) (2023-03-28) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [2.0.0-alpha.1](https://github.com/ueberdosis/hocuspocus/compare/v2.0.0-alpha.0...v2.0.0-alpha.1) (2023-03-23) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [2.0.0-alpha.0](https://github.com/ueberdosis/hocuspocus/compare/v1.1.0...v2.0.0-alpha.0) (2023-02-28) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.1.0](https://github.com/ueberdosis/hocuspocus/compare/v1.0.2...v1.1.0) (2023-02-24) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+## [1.0.2](https://github.com/ueberdosis/hocuspocus/compare/v1.0.1...v1.0.2) (2023-02-16) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+## [1.0.1](https://github.com/ueberdosis/hocuspocus/compare/v1.0.0...v1.0.1) (2023-01-30) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0](https://github.com/ueberdosis/hocuspocus/compare/v1.0.0-beta.7...v1.0.0) (2023-01-18) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-beta.7](https://github.com/ueberdosis/hocuspocus/compare/v1.0.0-beta.6...v1.0.0-beta.7) (2023-01-11) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-beta.6](https://github.com/ueberdosis/hocuspocus/compare/v1.0.0-beta.5...v1.0.0-beta.6) (2022-12-03) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-beta.5](https://github.com/ueberdosis/hocuspocus/compare/v1.0.0-beta.3...v1.0.0-beta.5) (2022-11-25) -+ -+ -+### Bug Fixes -+ -+* Crash when websocket receives out of bound characters pre-auth ([#444](https://github.com/ueberdosis/hocuspocus/issues/444)) ([73d8a48](https://github.com/ueberdosis/hocuspocus/commit/73d8a4812a4d9a851c97a52b6d62180a1fa4b56b)) -+ -+ -+ -+ -+ -+# [1.0.0-beta.4](https://github.com/ueberdosis/hocuspocus/compare/v1.0.0-beta.3...v1.0.0-beta.4) (2022-11-25) -+ -+ -+### Bug Fixes -+ -+* Crash when websocket receives out of bound characters pre-auth ([#444](https://github.com/ueberdosis/hocuspocus/issues/444)) ([73d8a48](https://github.com/ueberdosis/hocuspocus/commit/73d8a4812a4d9a851c97a52b6d62180a1fa4b56b)) -+ -+ -+ -+ -+ -+# [1.0.0-beta.3](https://github.com/ueberdosis/hocuspocus/compare/v1.0.0-beta.2...v1.0.0-beta.3) (2022-11-03) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-beta.2](https://github.com/ueberdosis/hocuspocus/compare/v1.0.0-beta.1...v1.0.0-beta.2) (2022-09-28) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# 1.0.0-beta.111 (2022-09-28) -+ -+ -+### Bug Fixes -+ -+* Empty sync message causes error in client MessageReceiver ([#174](https://github.com/ueberdosis/hocuspocus/issues/174)) ([f9dca69](https://github.com/ueberdosis/hocuspocus/commit/f9dca69eb96d1ede37a0709bd3b7735bf1ff57ba)) -+* fix hook promise chaining ([ee5052d](https://github.com/ueberdosis/hocuspocus/commit/ee5052d236ba0b400880dc7ca1c90cefdd372003)) -+* Potential onCreateDocument race condition ([#167](https://github.com/ueberdosis/hocuspocus/issues/167)) ([b3e3e4d](https://github.com/ueberdosis/hocuspocus/commit/b3e3e4dea74f9b833ccb0c6a6521f55c001411c1)) -+* Remove event listener once unused ([#220](https://github.com/ueberdosis/hocuspocus/issues/220)) ([0422196](https://github.com/ueberdosis/hocuspocus/commit/0422196f8a4e09af530c51419742b137b9ebbc69)) -+* typescript strings ([0dd5f12](https://github.com/ueberdosis/hocuspocus/commit/0dd5f1292616e426cdb4cc79e83ab8ced0895bfa)) -+ -+ -+### Features -+ -+* Add connectionsCount and documentsCount methods to server ([8bdbcd8](https://github.com/ueberdosis/hocuspocus/commit/8bdbcd86b1f18462f6636b75a4cbd97ebefdb227)) -+* add read only mode ([7b59d52](https://github.com/ueberdosis/hocuspocus/commit/7b59d522b966b51347db35ac6a4524211e44ae9c)) -+* add request headers and parameters to onCreateDocument ([47a8b95](https://github.com/ueberdosis/hocuspocus/commit/47a8b95baf8dd22ebd71c56565420179402cdaa4)) -+* Message Authentication ([#163](https://github.com/ueberdosis/hocuspocus/issues/163)) ([a1e68d5](https://github.com/ueberdosis/hocuspocus/commit/a1e68d5a272742bd17dd92522dfc908277343849)) -+ -+ -+ -+ -+ -+# [1.0.0-alpha.107](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.106...@hocuspocus/server@1.0.0-alpha.107) (2022-09-20) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.106](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.105...@hocuspocus/server@1.0.0-alpha.106) (2022-09-02) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.105](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.104...@hocuspocus/server@1.0.0-alpha.105) (2022-08-28) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.104](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.103...@hocuspocus/server@1.0.0-alpha.104) (2022-07-13) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.103](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.102...@hocuspocus/server@1.0.0-alpha.103) (2022-06-08) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.102](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.101...@hocuspocus/server@1.0.0-alpha.102) (2022-04-05) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.101](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.100...@hocuspocus/server@1.0.0-alpha.101) (2022-04-05) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.100](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.99...@hocuspocus/server@1.0.0-alpha.100) (2022-03-30) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.99](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.98...@hocuspocus/server@1.0.0-alpha.99) (2022-03-21) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.98](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.97...@hocuspocus/server@1.0.0-alpha.98) (2022-03-21) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.97](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.96...@hocuspocus/server@1.0.0-alpha.97) (2022-03-11) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.96](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.95...@hocuspocus/server@1.0.0-alpha.96) (2022-03-02) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.95](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.94...@hocuspocus/server@1.0.0-alpha.95) (2022-02-24) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.94](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.93...@hocuspocus/server@1.0.0-alpha.94) (2022-02-24) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.93](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.92...@hocuspocus/server@1.0.0-alpha.93) (2022-02-22) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.92](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.91...@hocuspocus/server@1.0.0-alpha.92) (2022-02-18) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.91](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.90...@hocuspocus/server@1.0.0-alpha.91) (2022-01-12) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.90](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.89...@hocuspocus/server@1.0.0-alpha.90) (2021-12-13) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.89](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.88...@hocuspocus/server@1.0.0-alpha.89) (2021-12-09) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.88](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.87...@hocuspocus/server@1.0.0-alpha.88) (2021-12-08) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.87](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.86...@hocuspocus/server@1.0.0-alpha.87) (2021-12-07) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.86](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.85...@hocuspocus/server@1.0.0-alpha.86) (2021-12-03) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.85](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.84...@hocuspocus/server@1.0.0-alpha.85) (2021-12-01) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.84](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.83...@hocuspocus/server@1.0.0-alpha.84) (2021-12-01) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.83](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.82...@hocuspocus/server@1.0.0-alpha.83) (2021-11-30) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.82](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.81...@hocuspocus/server@1.0.0-alpha.82) (2021-11-30) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.81](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.80...@hocuspocus/server@1.0.0-alpha.81) (2021-11-26) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.80](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.79...@hocuspocus/server@1.0.0-alpha.80) (2021-11-24) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.79](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.78...@hocuspocus/server@1.0.0-alpha.79) (2021-11-22) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.78](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.77...@hocuspocus/server@1.0.0-alpha.78) (2021-11-10) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.77](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.76...@hocuspocus/server@1.0.0-alpha.77) (2021-11-05) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.76](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.75...@hocuspocus/server@1.0.0-alpha.76) (2021-10-31) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.75](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.74...@hocuspocus/server@1.0.0-alpha.75) (2021-10-15) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.74](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.73...@hocuspocus/server@1.0.0-alpha.74) (2021-10-08) -+ -+ -+### Bug Fixes -+ -+* Remove event listener once unused ([#220](https://github.com/ueberdosis/hocuspocus/issues/220)) ([0422196](https://github.com/ueberdosis/hocuspocus/commit/0422196f8a4e09af530c51419742b137b9ebbc69)) -+ -+ -+ -+ -+ -+# [1.0.0-alpha.73](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.71...@hocuspocus/server@1.0.0-alpha.73) (2021-09-23) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.71](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.70...@hocuspocus/server@1.0.0-alpha.71) (2021-09-23) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.70](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.69...@hocuspocus/server@1.0.0-alpha.70) (2021-09-17) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.69](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.68...@hocuspocus/server@1.0.0-alpha.69) (2021-09-14) -+ -+ -+### Features -+ -+* Add connectionsCount and documentsCount methods to server ([8bdbcd8](https://github.com/ueberdosis/hocuspocus/commit/8bdbcd86b1f18462f6636b75a4cbd97ebefdb227)) -+ -+ -+ -+ -+ -+# [1.0.0-alpha.68](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.67...@hocuspocus/server@1.0.0-alpha.68) (2021-09-01) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.67](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.66...@hocuspocus/server@1.0.0-alpha.67) (2021-09-01) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.66](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.65...@hocuspocus/server@1.0.0-alpha.66) (2021-08-31) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.65](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.64...@hocuspocus/server@1.0.0-alpha.65) (2021-08-29) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.64](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.63...@hocuspocus/server@1.0.0-alpha.64) (2021-08-27) -+ -+ -+### Bug Fixes -+ -+* Empty sync message causes error in client MessageReceiver ([#174](https://github.com/ueberdosis/hocuspocus/issues/174)) ([f9dca69](https://github.com/ueberdosis/hocuspocus/commit/f9dca69eb96d1ede37a0709bd3b7735bf1ff57ba)) -+* Potential onCreateDocument race condition ([#167](https://github.com/ueberdosis/hocuspocus/issues/167)) ([b3e3e4d](https://github.com/ueberdosis/hocuspocus/commit/b3e3e4dea74f9b833ccb0c6a6521f55c001411c1)) -+ -+ -+ -+ -+ -+# [1.0.0-alpha.63](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.62...@hocuspocus/server@1.0.0-alpha.63) (2021-08-19) -+ -+ -+### Features -+ -+* Message Authentication ([#163](https://github.com/ueberdosis/hocuspocus/issues/163)) ([a1e68d5](https://github.com/ueberdosis/hocuspocus/commit/a1e68d5a272742bd17dd92522dfc908277343849)) -+ -+ -+ -+ -+ -+# [1.0.0-alpha.62](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.61...@hocuspocus/server@1.0.0-alpha.62) (2021-08-19) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.61](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.60...@hocuspocus/server@1.0.0-alpha.61) (2021-08-13) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.60](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.59...@hocuspocus/server@1.0.0-alpha.60) (2021-07-13) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.59](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.58...@hocuspocus/server@1.0.0-alpha.59) (2021-06-22) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.58](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.57...@hocuspocus/server@1.0.0-alpha.58) (2021-06-11) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.57](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.56...@hocuspocus/server@1.0.0-alpha.57) (2021-06-09) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.56](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.55...@hocuspocus/server@1.0.0-alpha.56) (2021-06-09) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.55](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.54...@hocuspocus/server@1.0.0-alpha.55) (2021-06-08) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.54](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.53...@hocuspocus/server@1.0.0-alpha.54) (2021-06-08) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.53](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.52...@hocuspocus/server@1.0.0-alpha.53) (2021-05-15) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.52](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.51...@hocuspocus/server@1.0.0-alpha.52) (2021-04-20) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.51](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.50...@hocuspocus/server@1.0.0-alpha.51) (2021-04-20) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.50](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.49...@hocuspocus/server@1.0.0-alpha.50) (2021-04-20) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.49](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.48...@hocuspocus/server@1.0.0-alpha.49) (2021-04-20) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.48](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.47...@hocuspocus/server@1.0.0-alpha.48) (2021-04-20) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.47](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.46...@hocuspocus/server@1.0.0-alpha.47) (2021-04-15) -+ -+ -+### Features -+ -+* add request headers and parameters to onCreateDocument ([47a8b95](https://github.com/ueberdosis/hocuspocus/commit/47a8b95baf8dd22ebd71c56565420179402cdaa4)) -+ -+ -+ -+ -+ -+# [1.0.0-alpha.46](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.45...@hocuspocus/server@1.0.0-alpha.46) (2021-04-14) -+ -+ -+### Features -+ -+* add read only mode ([7b59d52](https://github.com/ueberdosis/hocuspocus/commit/7b59d522b966b51347db35ac6a4524211e44ae9c)) -+ -+ -+ -+ -+ -+# [1.0.0-alpha.45](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.44...@hocuspocus/server@1.0.0-alpha.45) (2021-04-12) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.44](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.43...@hocuspocus/server@1.0.0-alpha.44) (2021-04-08) -+ -+ -+### Bug Fixes -+ -+* typescript strings ([0dd5f12](https://github.com/ueberdosis/hocuspocus/commit/0dd5f1292616e426cdb4cc79e83ab8ced0895bfa)) -+ -+ -+ -+ -+ -+# [1.0.0-alpha.43](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.42...@hocuspocus/server@1.0.0-alpha.43) (2021-04-07) -+ -+ -+### Bug Fixes -+ -+* fix hook promise chaining ([ee5052d](https://github.com/ueberdosis/hocuspocus/commit/ee5052d236ba0b400880dc7ca1c90cefdd372003)) -+ -+ -+ -+ -+ -+# [1.0.0-alpha.42](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.41...@hocuspocus/server@1.0.0-alpha.42) (2021-04-06) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.41](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.40...@hocuspocus/server@1.0.0-alpha.41) (2021-04-06) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.40](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.39...@hocuspocus/server@1.0.0-alpha.40) (2021-03-29) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.39](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.38...@hocuspocus/server@1.0.0-alpha.39) (2021-03-29) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.38](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.37...@hocuspocus/server@1.0.0-alpha.38) (2021-03-25) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.37](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.36...@hocuspocus/server@1.0.0-alpha.37) (2021-03-18) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.36](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.35...@hocuspocus/server@1.0.0-alpha.36) (2021-03-15) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.35](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.34...@hocuspocus/server@1.0.0-alpha.35) (2021-03-10) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.34](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.33...@hocuspocus/server@1.0.0-alpha.34) (2021-03-10) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.33](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.32...@hocuspocus/server@1.0.0-alpha.33) (2021-03-10) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.32](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.31...@hocuspocus/server@1.0.0-alpha.32) (2021-03-10) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.31](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.30...@hocuspocus/server@1.0.0-alpha.31) (2021-03-10) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.30](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.29...@hocuspocus/server@1.0.0-alpha.30) (2021-03-10) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.29](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.28...@hocuspocus/server@1.0.0-alpha.29) (2021-03-10) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.28](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.27...@hocuspocus/server@1.0.0-alpha.28) (2021-03-10) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.27](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.26...@hocuspocus/server@1.0.0-alpha.27) (2021-03-10) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.26](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.25...@hocuspocus/server@1.0.0-alpha.26) (2021-03-04) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.25](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.24...@hocuspocus/server@1.0.0-alpha.25) (2021-03-04) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.24](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.23...@hocuspocus/server@1.0.0-alpha.24) (2021-03-04) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.23](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.22...@hocuspocus/server@1.0.0-alpha.23) (2021-03-04) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.22](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.21...@hocuspocus/server@1.0.0-alpha.22) (2021-03-04) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.21](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.20...@hocuspocus/server@1.0.0-alpha.21) (2021-03-04) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.20](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.19...@hocuspocus/server@1.0.0-alpha.20) (2021-03-02) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.19](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.18...@hocuspocus/server@1.0.0-alpha.19) (2021-03-02) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.18](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.17...@hocuspocus/server@1.0.0-alpha.18) (2021-03-02) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.17](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.16...@hocuspocus/server@1.0.0-alpha.17) (2021-03-02) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.16](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.15...@hocuspocus/server@1.0.0-alpha.16) (2021-03-02) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.15](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.14...@hocuspocus/server@1.0.0-alpha.15) (2021-02-22) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.14](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.13...@hocuspocus/server@1.0.0-alpha.14) (2021-02-18) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.13](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.12...@hocuspocus/server@1.0.0-alpha.13) (2021-02-15) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.12](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.11...@hocuspocus/server@1.0.0-alpha.12) (2021-02-15) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.11](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.10...@hocuspocus/server@1.0.0-alpha.11) (2021-02-01) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.10](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.9...@hocuspocus/server@1.0.0-alpha.10) (2021-01-26) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.9](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.8...@hocuspocus/server@1.0.0-alpha.9) (2021-01-21) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.8](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.7...@hocuspocus/server@1.0.0-alpha.8) (2021-01-11) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.7](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.6...@hocuspocus/server@1.0.0-alpha.7) (2021-01-11) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.6](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.5...@hocuspocus/server@1.0.0-alpha.6) (2020-12-10) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.5](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.3...@hocuspocus/server@1.0.0-alpha.5) (2020-12-09) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# [1.0.0-alpha.3](https://github.com/ueberdosis/hocuspocus/compare/@hocuspocus/server@1.0.0-alpha.1...@hocuspocus/server@1.0.0-alpha.3) (2020-12-09) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# 1.0.0-alpha.1 (2020-12-09) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# 1.0.0-alpha.1 (2020-12-09) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# 1.0.0-alpha.1 (2020-12-09) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# 1.0.0-alpha.1 (2020-12-02) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# 1.0.0-alpha.2 (2020-12-02) -+ -+**Note:** Version bump only for package @hocuspocus/server -+ -+ -+ -+ -+ -+# 1.0.0-alpha.1 (2020-12-02) -+ -+**Note:** Version bump only for package @hocuspocus/server -diff --git a/node_modules/@hocuspocus/server/dist/hocuspocus-server.cjs b/node_modules/@hocuspocus/server/dist/hocuspocus-server.cjs -index 2bb9c9f..29dd216 100644 ---- a/node_modules/@hocuspocus/server/dist/hocuspocus-server.cjs -+++ b/node_modules/@hocuspocus/server/dist/hocuspocus-server.cjs -@@ -6,10 +6,10 @@ var AsyncLock = require('async-lock'); - var common = require('@hocuspocus/common'); - var Y = require('yjs'); - var http = require('http'); --var url = require('url'); --var ws = require('ws'); --var uuid = require('uuid'); - var kleur = require('kleur'); -+var uuid = require('uuid'); -+var ws = require('ws'); -+var url = require('url'); - - function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } - -@@ -36,10 +36,28 @@ var Y__namespace = /*#__PURE__*/_interopNamespace(Y); - var kleur__default = /*#__PURE__*/_interopDefaultLegacy(kleur); - - /** -- * Utility module to work with strings. -+ * Utility module to work with sets. -+ * -+ * @module set -+ */ -+ -+const create$2 = () => new Set(); -+ -+/** -+ * Utility module to work with Arrays. -+ * -+ * @module array -+ */ -+ -+/** -+ * Transforms something array-like to an actual Array. - * -- * @module string -+ * @function -+ * @template T -+ * @param {ArrayLike|Iterable} arraylike -+ * @return {T} - */ -+const from = Array.from; - - /** - * @param {string} s -@@ -122,7 +140,7 @@ if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) { - * - * @function - */ --const create$2 = () => new Map(); -+const create$1 = () => new Map(); - - /** - * Get map property. Create T if property is undefined and set T on map. -@@ -217,30 +235,6 @@ try { - /* c8 ignore next */ - const varStorage = _localStorage; - --/** -- * Utility module to work with sets. -- * -- * @module set -- */ -- --const create$1 = () => new Set(); -- --/** -- * Utility module to work with Arrays. -- * -- * @module array -- */ -- --/** -- * Transforms something array-like to an actual Array. -- * -- * @function -- * @template T -- * @param {ArrayLike|Iterable} arraylike -- * @return {T} -- */ --const from = Array.from; -- - /** - * Utility functions for working with EcmaScript objects. - * -@@ -372,7 +366,6 @@ const equalityDeep = (a, b) => { - */ - // @ts-ignore - const isOneOf = (value, options) => options.includes(value); --/* c8 ignore stop */ - - /** - * Isomorphic module to work access the environment (query params, env variables). -@@ -398,7 +391,7 @@ let params; - const computeParams = () => { - if (params === undefined) { - if (isNode) { -- params = create$2(); -+ params = create$1(); - const pargs = process.argv; - let currParamName = null; - for (let i = 0; i < pargs.length; i++) { -@@ -420,7 +413,7 @@ const computeParams = () => { - } - // in ReactNative for example this would not be true (unless connected to the Remote Debugger) - } else if (typeof location === 'object') { -- params = create$2(); // eslint-disable-next-line no-undef -+ params = create$1(); // eslint-disable-next-line no-undef - (location.search || '?').slice(1).split('&').forEach((kv) => { - if (kv.length !== 0) { - const [key, value] = kv.split('='); -@@ -429,7 +422,7 @@ const computeParams = () => { - } - }); - } else { -- params = create$2(); -+ params = create$1(); - } - } - return params -@@ -966,109 +959,6 @@ class IncomingMessage { - } - } - --/** -- * @module sync-protocol -- */ -- --/** -- * @typedef {Map} StateMap -- */ -- --/** -- * Core Yjs defines two message types: -- * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2. -- * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it -- * received all information from the remote client. -- * -- * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection -- * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both -- * SyncStep2 and SyncDone, it is assured that it is synced to the remote client. -- * -- * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1. -- * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies -- * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the -- * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can -- * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them. -- * Therefore it is necesarry that the client initiates the sync. -- * -- * Construction of a message: -- * [messageType : varUint, message definition..] -- * -- * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol! -- * -- * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer) -- */ -- --const messageYjsSyncStep1 = 0; --const messageYjsSyncStep2 = 1; --const messageYjsUpdate = 2; -- --/** -- * Create a sync step 1 message based on the state of the current shared document. -- * -- * @param {encoding.Encoder} encoder -- * @param {Y.Doc} doc -- */ --const writeSyncStep1 = (encoder, doc) => { -- writeVarUint(encoder, messageYjsSyncStep1); -- const sv = Y__namespace.encodeStateVector(doc); -- writeVarUint8Array(encoder, sv); --}; -- --/** -- * @param {encoding.Encoder} encoder -- * @param {Y.Doc} doc -- * @param {Uint8Array} [encodedStateVector] -- */ --const writeSyncStep2 = (encoder, doc, encodedStateVector) => { -- writeVarUint(encoder, messageYjsSyncStep2); -- writeVarUint8Array(encoder, Y__namespace.encodeStateAsUpdate(doc, encodedStateVector)); --}; -- --/** -- * Read SyncStep1 message and reply with SyncStep2. -- * -- * @param {decoding.Decoder} decoder The reply to the received message -- * @param {encoding.Encoder} encoder The received message -- * @param {Y.Doc} doc -- */ --const readSyncStep1 = (decoder, encoder, doc) => -- writeSyncStep2(encoder, doc, readVarUint8Array(decoder)); -- --/** -- * Read and apply Structs and then DeleteStore to a y instance. -- * -- * @param {decoding.Decoder} decoder -- * @param {Y.Doc} doc -- * @param {any} transactionOrigin -- */ --const readSyncStep2 = (decoder, doc, transactionOrigin) => { -- try { -- Y__namespace.applyUpdate(doc, readVarUint8Array(decoder), transactionOrigin); -- } catch (error) { -- // This catches errors that are thrown by event handlers -- console.error('Caught error while handling a Yjs update', error); -- } --}; -- --/** -- * @param {encoding.Encoder} encoder -- * @param {Uint8Array} update -- */ --const writeUpdate = (encoder, update) => { -- writeVarUint(encoder, messageYjsUpdate); -- writeVarUint8Array(encoder, update); --}; -- --/** -- * Read and apply Structs and then DeleteStore to a y instance. -- * -- * @param {decoding.Decoder} decoder -- * @param {Y.Doc} doc -- * @param {any} transactionOrigin -- */ --const readUpdate = readSyncStep2; -- - /** - * Utility module to work with time. - * -@@ -1099,7 +989,7 @@ class Observable { - * Some desc. - * @type {Map} - */ -- this._observers = create$2(); -+ this._observers = create$1(); - } - - /** -@@ -1107,7 +997,7 @@ class Observable { - * @param {function} f - */ - on (name, f) { -- setIfUndefined(this._observers, name, create$1).add(f); -+ setIfUndefined(this._observers, name, create$2).add(f); - } - - /** -@@ -1150,11 +1040,11 @@ class Observable { - */ - emit (name, args) { - // 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. -- return from((this._observers.get(name) || create$2()).values()).forEach(f => f(...args)) -+ return from((this._observers.get(name) || create$1()).values()).forEach(f => f(...args)) - } - - destroy () { -- this._observers = create$2(); -+ this._observers = create$1(); - } - } - -@@ -1419,6 +1309,109 @@ const applyAwarenessUpdate = (awareness, update, origin) => { - } - }; - -+/** -+ * @module sync-protocol -+ */ -+ -+/** -+ * @typedef {Map} StateMap -+ */ -+ -+/** -+ * Core Yjs defines two message types: -+ * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2. -+ * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it -+ * received all information from the remote client. -+ * -+ * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection -+ * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both -+ * SyncStep2 and SyncDone, it is assured that it is synced to the remote client. -+ * -+ * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1. -+ * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies -+ * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the -+ * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can -+ * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them. -+ * Therefore it is necesarry that the client initiates the sync. -+ * -+ * Construction of a message: -+ * [messageType : varUint, message definition..] -+ * -+ * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol! -+ * -+ * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer) -+ */ -+ -+const messageYjsSyncStep1 = 0; -+const messageYjsSyncStep2 = 1; -+const messageYjsUpdate = 2; -+ -+/** -+ * Create a sync step 1 message based on the state of the current shared document. -+ * -+ * @param {encoding.Encoder} encoder -+ * @param {Y.Doc} doc -+ */ -+const writeSyncStep1 = (encoder, doc) => { -+ writeVarUint(encoder, messageYjsSyncStep1); -+ const sv = Y__namespace.encodeStateVector(doc); -+ writeVarUint8Array(encoder, sv); -+}; -+ -+/** -+ * @param {encoding.Encoder} encoder -+ * @param {Y.Doc} doc -+ * @param {Uint8Array} [encodedStateVector] -+ */ -+const writeSyncStep2 = (encoder, doc, encodedStateVector) => { -+ writeVarUint(encoder, messageYjsSyncStep2); -+ writeVarUint8Array(encoder, Y__namespace.encodeStateAsUpdate(doc, encodedStateVector)); -+}; -+ -+/** -+ * Read SyncStep1 message and reply with SyncStep2. -+ * -+ * @param {decoding.Decoder} decoder The reply to the received message -+ * @param {encoding.Encoder} encoder The received message -+ * @param {Y.Doc} doc -+ */ -+const readSyncStep1 = (decoder, encoder, doc) => -+ writeSyncStep2(encoder, doc, readVarUint8Array(decoder)); -+ -+/** -+ * Read and apply Structs and then DeleteStore to a y instance. -+ * -+ * @param {decoding.Decoder} decoder -+ * @param {Y.Doc} doc -+ * @param {any} transactionOrigin -+ */ -+const readSyncStep2 = (decoder, doc, transactionOrigin) => { -+ try { -+ Y__namespace.applyUpdate(doc, readVarUint8Array(decoder), transactionOrigin); -+ } catch (error) { -+ // This catches errors that are thrown by event handlers -+ console.error('Caught error while handling a Yjs update', error); -+ } -+}; -+ -+/** -+ * @param {encoding.Encoder} encoder -+ * @param {Uint8Array} update -+ */ -+const writeUpdate = (encoder, update) => { -+ writeVarUint(encoder, messageYjsUpdate); -+ writeVarUint8Array(encoder, update); -+}; -+ -+/** -+ * Read and apply Structs and then DeleteStore to a y instance. -+ * -+ * @param {decoding.Decoder} decoder -+ * @param {Y.Doc} doc -+ * @param {any} transactionOrigin -+ */ -+const readUpdate = readSyncStep2; -+ - exports.MessageType = void 0; - (function (MessageType) { - MessageType[MessageType["Unknown"] = -1] = "Unknown"; -@@ -1430,6 +1423,7 @@ exports.MessageType = void 0; - MessageType[MessageType["Stateless"] = 5] = "Stateless"; - MessageType[MessageType["BroadcastStateless"] = 6] = "BroadcastStateless"; - MessageType[MessageType["CLOSE"] = 7] = "CLOSE"; -+ MessageType[MessageType["SyncStatus"] = 8] = "SyncStatus"; - })(exports.MessageType || (exports.MessageType = {})); - - class OutgoingMessage { -@@ -1497,7 +1491,14 @@ class OutgoingMessage { - writeVarString(this.encoder, payload); - return this; - } -- toUint8Array() { -+ // TODO: should this be write* or create* as method name? -+ writeSyncStatus(updateSaved) { -+ this.category = 'SyncStatus'; -+ writeVarUint(this.encoder, exports.MessageType.SyncStatus); -+ writeVarUint(this.encoder, updateSaved ? 1 : 0); -+ return this; -+ } -+ toUint8Array() { - return toUint8Array(this.encoder); - } - } -@@ -1620,9 +1621,32 @@ class MessageReceiver { - category: 'SyncStep2', - }); - if (connection === null || connection === void 0 ? void 0 : connection.readOnly) { -+ // We're in read-only mode, so we can't apply the update. -+ // Let's use snapshotContainsUpdate to see if the update actually contains changes. -+ // If not, we can still ack the update -+ const snapshot = Y__namespace.snapshot(document); -+ const update = readVarUint8Array(message.decoder); -+ if (Y__namespace.snapshotContainsUpdate(snapshot, update)) { -+ // no new changes in update -+ const ackMessage = new OutgoingMessage(document.name) -+ .writeSyncStatus(true); -+ connection.send(ackMessage.toUint8Array()); -+ } -+ else { -+ // new changes in update that we can't apply, because readOnly -+ const ackMessage = new OutgoingMessage(document.name) -+ .writeSyncStatus(false); -+ connection.send(ackMessage.toUint8Array()); -+ } - break; - } - readSyncStep2(message.decoder, document, connection); -+ if (connection) { -+ // TODO: how should this work if connection is not set? should we use reply? -+ // reply is used by redis, but I'm unsure how that code path works -+ connection.send(new OutgoingMessage(document.name) -+ .writeSyncStatus(true).toUint8Array()); -+ } - break; - case messageYjsUpdate: - this.logger.log({ -@@ -1631,9 +1655,17 @@ class MessageReceiver { - category: 'Update', - }); - if (connection === null || connection === void 0 ? void 0 : connection.readOnly) { -+ connection.send(new OutgoingMessage(document.name) -+ .writeSyncStatus(false).toUint8Array()); - break; - } - readUpdate(message.decoder, document, connection); -+ if (connection) { -+ // TODO: how should this work if connection is not set? should we use reply? -+ // reply is used by redis, but I'm unsure how that code path works -+ connection.send(new OutgoingMessage(document.name) -+ .writeSyncStatus(true).toUint8Array()); -+ } - break; - default: - throw new Error(`Received a message with an unknown type: ${type}`); -@@ -2128,7 +2160,7 @@ var devDependencies = { - }; - var peerDependencies = { - "y-protocols": "^1.0.5", -- yjs: "^13.5.29" -+ yjs: "^13.6.4" - }; - var gitHead = "b3454a4ca289a84ddfb7fa5607a2d4b8d5c37e9d"; - var meta = { -@@ -2150,6 +2182,297 @@ var meta = { - gitHead: gitHead - }; - -+/** -+ * Get parameters by the given request -+ */ -+function getParameters(request) { -+ var _a; -+ const query = ((_a = request === null || request === void 0 ? void 0 : request.url) === null || _a === void 0 ? void 0 : _a.split('?')) || []; -+ return new url.URLSearchParams(query[1] ? query[1] : ''); -+} -+ -+/** -+ * The `ClientConnection` class is responsible for handling an incoming WebSocket -+ * -+ * TODO-refactor: -+ * - use event handlers instead of calling hooks directly, hooks should probably be called from Hocuspocus.ts -+ */ -+class ClientConnection { -+ /** -+ * The `ClientConnection` class receives incoming WebSocket connections, -+ * runs all hooks: -+ * -+ * - onConnect for all connections -+ * - onAuthenticate only if required -+ * -+ * … and if nothings fails it’ll fully establish the connection and -+ * load the Document then. -+ */ -+ constructor(websocket, request, documentProvider, -+ // TODO: change to events -+ hooks, debuggerTool, opts) { -+ this.websocket = websocket; -+ this.request = request; -+ this.documentProvider = documentProvider; -+ this.hooks = hooks; -+ this.debuggerTool = debuggerTool; -+ this.opts = opts; -+ // this map indicates whether a `Connection` instance has already taken over for incoming message for the key (i.e. documentName) -+ this.documentConnections = {}; -+ // While the connection will be establishing messages will -+ // be queued and handled later. -+ this.incomingMessageQueue = {}; -+ // While the connection is establishing, kee -+ this.documentConnectionsEstablished = new Set(); -+ // hooks payload by Document -+ this.hookPayloads = {}; -+ this.callbacks = { -+ onClose: [(document, payload) => { }], -+ }; -+ // Every new connection gets a unique identifier. -+ this.socketId = uuid.v4(); -+ // Once all hooks are run, we’ll fully establish the connection: -+ this.setUpNewConnection = async (documentName) => { -+ // Not an idle connection anymore, no need to close it then. -+ clearTimeout(this.closeIdleConnectionTimeout); -+ const hookPayload = this.hookPayloads[documentName]; -+ // If no hook interrupts, create a document and connection -+ const document = await this.documentProvider.createDocument(documentName, hookPayload.request, hookPayload.socketId, hookPayload.connection, hookPayload.context); -+ const instance = this.createConnection(this.websocket, document); -+ instance.onClose((document, event) => { -+ delete this.hookPayloads[documentName]; -+ delete this.documentConnections[documentName]; -+ delete this.incomingMessageQueue[documentName]; -+ this.documentConnectionsEstablished.delete(documentName); -+ if (Object.keys(this.documentConnections).length === 0) { -+ instance.webSocket.close(event === null || event === void 0 ? void 0 : event.code, event === null || event === void 0 ? void 0 : event.reason); // TODO: Move this to Hocuspocus connection handler -+ } -+ }); -+ this.documentConnections[documentName] = true; -+ // There’s no need to queue messages anymore. -+ // Let’s work through queued messages. -+ this.incomingMessageQueue[documentName].forEach(input => { -+ this.websocket.emit('message', input); -+ }); -+ this.hooks('connected', { -+ ...hookPayload, -+ documentName, -+ context: hookPayload.context, -+ connectionInstance: instance, -+ }); -+ }; -+ // This listener handles authentication messages and queues everything else. -+ this.handleQueueingMessage = async (data) => { -+ var _a; -+ try { -+ const tmpMsg = new IncomingMessage(data); -+ const documentName = readVarString(tmpMsg.decoder); -+ const type = readVarUint(tmpMsg.decoder); -+ if (!(type === exports.MessageType.Auth && !this.documentConnectionsEstablished.has(documentName))) { -+ this.incomingMessageQueue[documentName].push(data); -+ return; -+ } -+ // Okay, we’ve got the authentication message we’re waiting for: -+ this.documentConnectionsEstablished.add(documentName); -+ // The 2nd integer contains the submessage type -+ // which will always be authentication when sent from client -> server -+ readVarUint(tmpMsg.decoder); -+ const token = readVarString(tmpMsg.decoder); -+ this.debuggerTool.log({ -+ direction: 'in', -+ type, -+ category: 'Token', -+ }); -+ try { -+ const hookPayload = this.hookPayloads[documentName]; -+ await this.hooks('onAuthenticate', { -+ token, -+ ...hookPayload, -+ documentName, -+ }, (contextAdditions) => { -+ // Hooks are allowed to give us even more context and we’ll merge everything together. -+ // We’ll pass the context to other hooks then. -+ hookPayload.context = { ...hookPayload.context, ...contextAdditions }; -+ }); -+ // All `onAuthenticate` hooks passed. -+ hookPayload.connection.isAuthenticated = true; -+ // Let the client know that authentication was successful. -+ const message = new OutgoingMessage(documentName).writeAuthenticated(hookPayload.connection.readOnly); -+ this.debuggerTool.log({ -+ direction: 'out', -+ type: message.type, -+ category: message.category, -+ }); -+ this.websocket.send(message.toUint8Array()); -+ // Time to actually establish the connection. -+ await this.setUpNewConnection(documentName); -+ } -+ catch (err) { -+ const error = err || common.Forbidden; -+ const message = new OutgoingMessage(documentName).writePermissionDenied((_a = error.reason) !== null && _a !== void 0 ? _a : 'permission-denied'); -+ this.debuggerTool.log({ -+ direction: 'out', -+ type: message.type, -+ category: message.category, -+ }); -+ // Ensure that the permission denied message is sent before the -+ // connection is closed -+ this.websocket.send(message.toUint8Array(), () => { -+ var _a, _b; -+ if (Object.keys(this.documentConnections).length === 0) { -+ try { -+ this.websocket.close((_a = error.code) !== null && _a !== void 0 ? _a : common.Forbidden.code, (_b = error.reason) !== null && _b !== void 0 ? _b : common.Forbidden.reason); -+ } -+ catch (closeError) { -+ // catch is needed in case invalid error code is returned by hook (that would fail sending the close message) -+ console.error(closeError); -+ this.websocket.close(common.Forbidden.code, common.Forbidden.reason); -+ } -+ } -+ }); -+ } -+ // Catch errors due to failed decoding of data -+ } -+ catch (error) { -+ console.error(error); -+ this.websocket.close(common.Unauthorized.code, common.Unauthorized.reason); -+ } -+ }; -+ this.messageHandler = async (data) => { -+ var _a, _b; -+ try { -+ const tmpMsg = new IncomingMessage(data); -+ const documentName = readVarString(tmpMsg.decoder); -+ if (this.documentConnections[documentName] === true) { -+ // we already have a `Connection` set up for this document -+ return; -+ } -+ const isFirst = this.incomingMessageQueue[documentName] === undefined; -+ if (isFirst) { -+ this.incomingMessageQueue[documentName] = []; -+ if (this.hookPayloads[documentName]) { -+ throw new Error('first message, but hookPayloads exists'); -+ } -+ const hookPayload = { -+ instance: this.documentProvider, -+ request: this.request, -+ connection: { -+ readOnly: false, -+ requiresAuthentication: this.opts.requiresAuthentication, -+ isAuthenticated: false, -+ }, -+ requestHeaders: this.request.headers, -+ requestParameters: getParameters(this.request), -+ socketId: this.socketId, -+ context: {}, -+ }; -+ this.hookPayloads[documentName] = hookPayload; -+ } -+ this.handleQueueingMessage(data); -+ if (isFirst) { -+ const hookPayload = this.hookPayloads[documentName]; -+ // if this is the first message, trigger onConnect & check if we can start the connection (only if no auth is required) -+ try { -+ await this.hooks('onConnect', { ...hookPayload, documentName }, (contextAdditions) => { -+ // merge context from all hooks -+ hookPayload.context = { ...hookPayload.context, ...contextAdditions }; -+ }); -+ if (hookPayload.connection.requiresAuthentication || this.documentConnectionsEstablished.has(documentName)) { -+ // Authentication is required, we’ll need to wait for the Authentication message. -+ return; -+ } -+ this.documentConnectionsEstablished.add(documentName); -+ await this.setUpNewConnection(documentName); -+ } -+ catch (err) { -+ // if a hook interrupts, close the websocket connection -+ const error = err || common.Forbidden; -+ try { -+ this.websocket.close((_a = error.code) !== null && _a !== void 0 ? _a : common.Forbidden.code, (_b = error.reason) !== null && _b !== void 0 ? _b : common.Forbidden.reason); -+ } -+ catch (closeError) { -+ // catch is needed in case invalid error code is returned by hook (that would fail sending the close message) -+ console.error(closeError); -+ this.websocket.close(common.Unauthorized.code, common.Unauthorized.reason); -+ } -+ } -+ } -+ } -+ catch (closeError) { -+ // catch is needed in case an invalid payload crashes the parsing of the Uint8Array -+ console.error(closeError); -+ this.websocket.close(common.Unauthorized.code, common.Unauthorized.reason); -+ } -+ }; -+ // Make sure to close an idle connection after a while. -+ this.closeIdleConnectionTimeout = setTimeout(() => { -+ websocket.close(common.Unauthorized.code, common.Unauthorized.reason); -+ }, opts.timeout); -+ websocket.on('message', this.messageHandler); -+ } -+ /** -+ * Set a callback that will be triggered when the connection is closed -+ */ -+ onClose(callback) { -+ this.callbacks.onClose.push(callback); -+ return this; -+ } -+ /** -+ * Create a new connection by the given request and document -+ */ -+ createConnection(connection, document) { -+ const hookPayload = this.hookPayloads[document.name]; -+ const instance = new Connection(connection, hookPayload.request, document, this.opts.timeout, hookPayload.socketId, hookPayload.context, hookPayload.connection.readOnly, this.debuggerTool); -+ instance.onClose(async (document, event) => { -+ const disconnectHookPayload = { -+ instance: this.documentProvider, -+ clientsCount: document.getConnectionsCount(), -+ context: hookPayload.context, -+ document, -+ socketId: hookPayload.socketId, -+ documentName: document.name, -+ requestHeaders: hookPayload.request.headers, -+ requestParameters: getParameters(hookPayload.request), -+ }; -+ await this.hooks('onDisconnect', hookPayload); -+ this.callbacks.onClose.forEach((callback => callback(document, disconnectHookPayload))); -+ }); -+ instance.onStatelessCallback(async (payload) => { -+ try { -+ return await this.hooks('onStateless', payload); -+ } -+ catch (error) { -+ // TODO: weird pattern, what's the use of this? -+ if (error === null || error === void 0 ? void 0 : error.message) { -+ throw error; -+ } -+ } -+ }); -+ instance.beforeHandleMessage((connection, update) => { -+ const beforeHandleMessagePayload = { -+ instance: this.documentProvider, -+ clientsCount: document.getConnectionsCount(), -+ context: hookPayload.context, -+ document, -+ socketId: hookPayload.socketId, -+ connection, -+ documentName: document.name, -+ requestHeaders: hookPayload.request.headers, -+ requestParameters: getParameters(hookPayload.request), -+ update, -+ }; -+ return this.hooks('beforeHandleMessage', beforeHandleMessagePayload); -+ }); -+ // If the WebSocket has already disconnected (wow, that was fast) – then -+ // immediately call close to cleanup the connection and document in memory. -+ if (connection.readyState === common.WsReadyStates.Closing -+ || connection.readyState === common.WsReadyStates.Closed) { -+ instance.close(); -+ } -+ return instance; -+ } -+} -+ - class DirectConnection { - /** - * Constructor. -@@ -2310,14 +2633,14 @@ class Hocuspocus { - }); - this.handleConnection(incoming, request); - }); -- const server = http.createServer((request, response) => { -- this.hooks('onRequest', { request, response, instance: this }) -- .then(() => { -+ const server = http.createServer(async (request, response) => { -+ try { -+ await this.hooks('onRequest', { request, response, instance: this }); - // default response if all prior hooks don't interfere - response.writeHead(200, { 'Content-Type': 'text/plain' }); - response.end('OK'); -- }) -- .catch(error => { -+ } -+ catch (error) { - // if a hook rejects and the error is empty, do nothing - // this is only meant to prevent later hooks and the - // default handler to do something. if a error is present -@@ -2325,31 +2648,32 @@ class Hocuspocus { - if (error) { - throw error; - } -- }); -+ } - }); -- server.on('upgrade', (request, socket, head) => { -- this.hooks('onUpgrade', { -- request, -- socket, -- head, -- instance: this, -- }) -- .then(() => { -+ server.on('upgrade', async (request, socket, head) => { -+ try { -+ await this.hooks('onUpgrade', { -+ request, -+ socket, -+ head, -+ instance: this, -+ }); - // let the default websocket server handle the connection if - // prior hooks don't interfere - webSocketServer.handleUpgrade(request, socket, head, ws => { - webSocketServer.emit('connection', ws, request); - }); -- }) -- .catch(error => { -+ } -+ catch (error) { - // if a hook rejects and the error is empty, do nothing - // this is only meant to prevent later hooks and the - // default handler to do something. if a error is present - // just rethrow it -+ // TODO: why? - if (error) { - throw error; - } -- }); -+ } - }); - this.httpServer = server; - this.webSocketServer = webSocketServer; -@@ -2357,7 +2681,7 @@ class Hocuspocus { - server.listen({ - port: this.configuration.port, - host: this.configuration.address, -- }, () => { -+ }, async () => { - if (!this.configuration.quiet && process.env.NODE_ENV !== 'testing') { - this.showStartScreen(); - } -@@ -2366,9 +2690,13 @@ class Hocuspocus { - configuration: this.configuration, - port: this.address.port, - }; -- this.hooks('onListen', onListenPayload) -- .then(() => resolve(this)) -- .catch(error => reject(error)); -+ try { -+ await this.hooks('onListen', onListenPayload); -+ resolve(this); -+ } -+ catch (e) { -+ reject(e); -+ } - }); - }); - } -@@ -2475,188 +2803,35 @@ class Hocuspocus { - * … and if nothings fails it’ll fully establish the connection and - * load the Document then. - */ -- handleConnection(incoming, request, context = null) { -- // Make sure to close an idle connection after a while. -- const closeIdleConnection = setTimeout(() => { -- incoming.close(common.Unauthorized.code, common.Unauthorized.reason); -- }, this.configuration.timeout); -- // Every new connection gets a unique identifier. -- const socketId = uuid.v4(); -- // To override settings for specific connections, we’ll -- // keep track of a few things in the `ConnectionConfiguration`. -- const connection = { -- readOnly: false, -+ handleConnection(incoming, request) { -+ const clientConnection = new ClientConnection(incoming, request, this, this.hooks.bind(this), this.debugger, { - requiresAuthentication: this.requiresAuthentication, -- isAuthenticated: false, -- }; -- // The `onConnect` and `onAuthenticate` hooks need some context -- // to decide who’s connecting, so let’s put it together: -- const hookPayload = { -- instance: this, -- request, -- requestHeaders: request.headers, -- requestParameters: Hocuspocus.getParameters(request), -- socketId, -- connection, -- }; -- // this map indicates whether a `Connection` instance has already taken over for incoming message for the key (i.e. documentName) -- const documentConnections = {}; -- // While the connection will be establishing messages will -- // be queued and handled later. -- const incomingMessageQueue = {}; -- // While the connection is establishing -- const connectionEstablishing = {}; -- // Once all hooks are run, we’ll fully establish the connection: -- const setUpNewConnection = async (documentName) => { -- // Not an idle connection anymore, no need to close it then. -- clearTimeout(closeIdleConnection); -- // If no hook interrupts, create a document and connection -- const document = await this.createDocument(documentName, request, socketId, connection, context); -- const instance = this.createConnection(incoming, request, document, socketId, connection.readOnly, context); -- instance.onClose((document, event) => { -- delete documentConnections[documentName]; -- delete incomingMessageQueue[documentName]; -- delete connectionEstablishing[documentName]; -- if (Object.keys(documentConnections).length === 0) { -- instance.webSocket.close(event === null || event === void 0 ? void 0 : event.code, event === null || event === void 0 ? void 0 : event.reason); // TODO: Move this to Hocuspocus connection handler -- } -- }); -- documentConnections[documentName] = true; -- // There’s no need to queue messages anymore. -- // Let’s work through queued messages. -- incomingMessageQueue[documentName].forEach(input => { -- incoming.emit('message', input); -- }); -- this.hooks('connected', { -- ...hookPayload, -- documentName, -- context, -- connectionInstance: instance, -- }); -- }; -- // This listener handles authentication messages and queues everything else. -- const handleQueueingMessage = (data) => { -- try { -- const tmpMsg = new IncomingMessage(data); -- const documentName = readVarString(tmpMsg.decoder); -- const type = readVarUint(tmpMsg.decoder); -- // Okay, we’ve got the authentication message we’re waiting for: -- if (type === exports.MessageType.Auth && !connectionEstablishing[documentName]) { -- connectionEstablishing[documentName] = true; -- // The 2nd integer contains the submessage type -- // which will always be authentication when sent from client -> server -- readVarUint(tmpMsg.decoder); -- const token = readVarString(tmpMsg.decoder); -- this.debugger.log({ -- direction: 'in', -- type, -- category: 'Token', -- }); -- this.hooks('onAuthenticate', { -- token, -- ...hookPayload, -- documentName, -- }, (contextAdditions) => { -- // Hooks are allowed to give us even more context and we’ll merge everything together. -- // We’ll pass the context to other hooks then. -- context = { ...context, ...contextAdditions }; -- }) -- .then(() => { -- // All `onAuthenticate` hooks passed. -- connection.isAuthenticated = true; -- // Let the client know that authentication was successful. -- const message = new OutgoingMessage(documentName).writeAuthenticated(connection.readOnly); -- this.debugger.log({ -- direction: 'out', -- type: message.type, -- category: message.category, -- }); -- incoming.send(message.toUint8Array()); -- }) -- .then(() => { -- // Time to actually establish the connection. -- return setUpNewConnection(documentName); -- }) -- .catch((error = common.Forbidden) => { -- var _a; -- const message = new OutgoingMessage(documentName).writePermissionDenied((_a = error.reason) !== null && _a !== void 0 ? _a : 'permission-denied'); -- this.debugger.log({ -- direction: 'out', -- type: message.type, -- category: message.category, -- }); -- // Ensure that the permission denied message is sent before the -- // connection is closed -- incoming.send(message.toUint8Array(), () => { -- var _a, _b; -- if (Object.keys(documentConnections).length === 0) { -- try { -- incoming.close((_a = error.code) !== null && _a !== void 0 ? _a : common.Forbidden.code, (_b = error.reason) !== null && _b !== void 0 ? _b : common.Forbidden.reason); -- } -- catch (closeError) { -- // catch is needed in case invalid error code is returned by hook (that would fail sending the close message) -- console.error(closeError); -- incoming.close(common.Forbidden.code, common.Forbidden.reason); -- } -- } -- }); -- }); -- } -- else { -- incomingMessageQueue[documentName].push(data); -- } -- // Catch errors due to failed decoding of data -- } -- catch (error) { -- console.error(error); -- incoming.close(common.Unauthorized.code, common.Unauthorized.reason); -+ timeout: this.configuration.timeout, -+ }); -+ clientConnection.onClose((document, hookPayload) => { -+ // Check if there are still no connections to the document, as these hooks -+ // may take some time to resolve (e.g. database queries). If a -+ // new connection were to come in during that time it would rely on the -+ // document in the map that we remove now. -+ if (document.getConnectionsCount() > 0) { -+ return; - } -- }; -- const messageHandler = (data) => { -- try { -- const tmpMsg = new IncomingMessage(data); -- const documentName = readVarString(tmpMsg.decoder); -- if (documentConnections[documentName] === true) { -- // we already have a `Connection` set up for this document -- return; -- } -- // if this is the first message, trigger onConnect & check if we can start the connection (only if no auth is required) -- if (incomingMessageQueue[documentName] === undefined) { -- incomingMessageQueue[documentName] = []; -- this.hooks('onConnect', { ...hookPayload, documentName }, (contextAdditions) => { -- // merge context from all hooks -- context = { ...context, ...contextAdditions }; -- }) -- .then(() => { -- // Authentication is required, we’ll need to wait for the Authentication message. -- if (connection.requiresAuthentication || connectionEstablishing[documentName]) { -- return; -- } -- connectionEstablishing[documentName] = true; -- return setUpNewConnection(documentName); -- }) -- .catch((error = common.Forbidden) => { -- var _a, _b; -- // if a hook interrupts, close the websocket connection -- try { -- incoming.close((_a = error.code) !== null && _a !== void 0 ? _a : common.Forbidden.code, (_b = error.reason) !== null && _b !== void 0 ? _b : common.Forbidden.reason); -- } -- catch (closeError) { -- // catch is needed in case invalid error code is returned by hook (that would fail sending the close message) -- console.error(closeError); -- incoming.close(common.Unauthorized.code, common.Unauthorized.reason); -- } -- }); -- } -- handleQueueingMessage(data); -+ // If it’s the last connection, we need to make sure to store the -+ // document. Use the debounce helper, to clear running timers, -+ // but make it run immediately (`true`). -+ // Only run this if the document has finished loading earlier (i.e. not to persist the empty -+ // ydoc if the onLoadDocument hook returned an error) -+ if (!document.isLoading) { -+ this.debounce(`onStoreDocument-${document.name}`, () => { -+ this.storeDocumentHooks(document, hookPayload); -+ }, true); - } -- catch (closeError) { -- // catch is needed in case an invalid payload crashes the parsing of the Uint8Array -- console.error(closeError); -- incoming.close(common.Unauthorized.code, common.Unauthorized.reason); -+ else { -+ // Remove document from memory immediately -+ this.documents.delete(document.name); -+ document.destroy(); - } -- }; -- incoming.on('message', messageHandler); -+ }); - } - /** - * Handle update of the given document -@@ -2670,11 +2845,12 @@ class Hocuspocus { - document, - documentName: document.name, - requestHeaders: (_a = request === null || request === void 0 ? void 0 : request.headers) !== null && _a !== void 0 ? _a : {}, -- requestParameters: Hocuspocus.getParameters(request), -+ requestParameters: getParameters(request), - socketId: (_b = connection === null || connection === void 0 ? void 0 : connection.socketId) !== null && _b !== void 0 ? _b : '', - update, - }; - this.hooks('onChange', hookPayload).catch(error => { -+ // TODO: what's the intention of this catch -> throw? - throw error; - }); - // If the update was received through other ways than the -@@ -2731,7 +2907,7 @@ class Hocuspocus { - documentName, - socketId, - requestHeaders: request.headers, -- requestParameters: Hocuspocus.getParameters(request), -+ requestParameters: getParameters(request), - }; - try { - await this.hooks('onLoadDocument', hookPayload, (loadedDocument) => { -@@ -2772,78 +2948,6 @@ class Hocuspocus { - }); - return document; - } -- /** -- * Create a new connection by the given request and document -- */ -- createConnection(connection, request, document, socketId, readOnly = false, context) { -- const instance = new Connection(connection, request, document, this.configuration.timeout, socketId, context, readOnly, this.debugger); -- instance.onClose(document => { -- const hookPayload = { -- instance: this, -- clientsCount: document.getConnectionsCount(), -- context, -- document, -- socketId, -- documentName: document.name, -- requestHeaders: request.headers, -- requestParameters: Hocuspocus.getParameters(request), -- }; -- this.hooks('onDisconnect', hookPayload).then(() => { -- // Check if there are still no connections to the document, as these hooks -- // may take some time to resolve (e.g. database queries). If a -- // new connection were to come in during that time it would rely on the -- // document in the map that we remove now. -- if (document.getConnectionsCount() > 0) { -- return; -- } -- // If it’s the last connection, we need to make sure to store the -- // document. Use the debounce helper, to clear running timers, -- // but make it run immediately (`true`). -- // Only run this if the document has finished loading earlier (i.e. not to persist the empty -- // ydoc if the onLoadDocument hook returned an error) -- if (!document.isLoading) { -- this.debounce(`onStoreDocument-${document.name}`, () => { -- this.storeDocumentHooks(document, hookPayload); -- }, true); -- } -- else { -- // Remove document from memory immediately -- this.documents.delete(document.name); -- document.destroy(); -- } -- }); -- }); -- instance.onStatelessCallback(payload => { -- return this.hooks('onStateless', payload) -- .catch(error => { -- if (error === null || error === void 0 ? void 0 : error.message) { -- throw error; -- } -- }); -- }); -- instance.beforeHandleMessage((connection, update) => { -- const hookPayload = { -- instance: this, -- clientsCount: document.getConnectionsCount(), -- context, -- document, -- socketId, -- connection, -- documentName: document.name, -- requestHeaders: request.headers, -- requestParameters: Hocuspocus.getParameters(request), -- update, -- }; -- return this.hooks('beforeHandleMessage', hookPayload); -- }); -- // If the WebSocket has already disconnected (wow, that was fast) – then -- // immediately call close to cleanup the connection and document in memory. -- if (connection.readyState === common.WsReadyStates.Closing -- || connection.readyState === common.WsReadyStates.Closed) { -- instance.close(); -- } -- return instance; -- } - storeDocumentHooks(document, hookPayload) { - this.hooks('onStoreDocument', hookPayload) - .catch(error => { -@@ -2891,14 +2995,6 @@ class Hocuspocus { - }); - return chain; - } -- /** -- * Get parameters by the given request -- */ -- static getParameters(request) { -- var _a; -- const query = ((_a = request === null || request === void 0 ? void 0 : request.url) === null || _a === void 0 ? void 0 : _a.split('?')) || []; -- return new url.URLSearchParams(query[1] ? query[1] : ''); -- } - enableDebugging() { - this.debugger.enable(); - } -diff --git a/node_modules/@hocuspocus/server/dist/hocuspocus-server.cjs.map b/node_modules/@hocuspocus/server/dist/hocuspocus-server.cjs.map -index 0cd8611..239cbc0 100644 ---- a/node_modules/@hocuspocus/server/dist/hocuspocus-server.cjs.map -+++ b/node_modules/@hocuspocus/server/dist/hocuspocus-server.cjs.map -@@ -1 +1 @@ --{"version":3,"file":"hocuspocus-server.cjs","sources":["../../../node_modules/lib0/string.js","../../../node_modules/lib0/map.js","../../../node_modules/lib0/conditions.js","../../../node_modules/lib0/storage.js","../../../node_modules/lib0/set.js","../../../node_modules/lib0/array.js","../../../node_modules/lib0/object.js","../../../node_modules/lib0/function.js","../../../node_modules/lib0/environment.js","../../../node_modules/lib0/math.js","../../../node_modules/lib0/binary.js","../../../node_modules/lib0/number.js","../../../node_modules/lib0/encoding.js","../../../node_modules/lib0/buffer.js","../../../node_modules/lib0/error.js","../../../node_modules/lib0/decoding.js","../src/IncomingMessage.ts","../../../node_modules/y-protocols/sync.js","../../../node_modules/lib0/time.js","../../../node_modules/lib0/observable.js","../../../node_modules/y-protocols/awareness.js","../src/types.ts","../src/OutgoingMessage.ts","../src/MessageReceiver.ts","../src/Connection.ts","../src/Debugger.ts","../../../node_modules/lib0/mutex.js","../src/Document.ts","../src/DirectConnection.ts","../src/Hocuspocus.ts"],"sourcesContent":["/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* c8 ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* c8 ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* c8 ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* c8 ignore start */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* c8 ignore next */\n utf8TextDecoder = null\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* c8 ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n","/**\n * Utility module to work with key-value stores.\n *\n * @module map\n */\n\n/**\n * Creates a new Map instance.\n *\n * @function\n * @return {Map}\n *\n * @function\n */\nexport const create = () => new Map()\n\n/**\n * Copy a Map object into a fresh Map object.\n *\n * @function\n * @template X,Y\n * @param {Map} m\n * @return {Map}\n */\nexport const copy = m => {\n const r = create()\n m.forEach((v, k) => { r.set(k, v) })\n return r\n}\n\n/**\n * Get map property. Create T if property is undefined and set T on map.\n *\n * ```js\n * const listeners = map.setIfUndefined(events, 'eventName', set.create)\n * listeners.add(listener)\n * ```\n *\n * @function\n * @template V,K\n * @template {Map} MAP\n * @param {MAP} map\n * @param {K} key\n * @param {function():V} createT\n * @return {V}\n */\nexport const setIfUndefined = (map, key, createT) => {\n let set = map.get(key)\n if (set === undefined) {\n map.set(key, set = createT())\n }\n return set\n}\n\n/**\n * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function.\n *\n * @function\n * @template K\n * @template V\n * @template R\n * @param {Map} m\n * @param {function(V,K):R} f\n * @return {Array}\n */\nexport const map = (m, f) => {\n const res = []\n for (const [key, value] of m) {\n res.push(f(value, key))\n }\n return res\n}\n\n/**\n * Tests whether any key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @todo should rename to some - similarly to Array.some\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const any = (m, f) => {\n for (const [key, value] of m) {\n if (f(value, key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * Tests whether all key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const all = (m, f) => {\n for (const [key, value] of m) {\n if (!f(value, key)) {\n return false\n }\n }\n return true\n}\n","/**\n * Often used conditions.\n *\n * @module conditions\n */\n\n/**\n * @template T\n * @param {T|null|undefined} v\n * @return {T|null}\n */\n/* c8 ignore next */\nexport const undefinedToNull = v => v === undefined ? null : v\n","/* eslint-env browser */\n\n/**\n * Isomorphic variable storage.\n *\n * Uses LocalStorage in the browser and falls back to in-memory storage.\n *\n * @module storage\n */\n\n/* c8 ignore start */\nclass VarStoragePolyfill {\n constructor () {\n this.map = new Map()\n }\n\n /**\n * @param {string} key\n * @param {any} newValue\n */\n setItem (key, newValue) {\n this.map.set(key, newValue)\n }\n\n /**\n * @param {string} key\n */\n getItem (key) {\n return this.map.get(key)\n }\n}\n/* c8 ignore stop */\n\n/**\n * @type {any}\n */\nlet _localStorage = new VarStoragePolyfill()\nlet usePolyfill = true\n\n/* c8 ignore start */\ntry {\n // if the same-origin rule is violated, accessing localStorage might thrown an error\n if (typeof localStorage !== 'undefined') {\n _localStorage = localStorage\n usePolyfill = false\n }\n} catch (e) { }\n/* c8 ignore stop */\n\n/**\n * This is basically localStorage in browser, or a polyfill in nodejs\n */\n/* c8 ignore next */\nexport const varStorage = _localStorage\n\n/**\n * A polyfill for `addEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler))\n\n/**\n * A polyfill for `removeEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler))\n","/**\n * Utility module to work with sets.\n *\n * @module set\n */\n\nexport const create = () => new Set()\n\n/**\n * @template T\n * @param {Set} set\n * @return {Array}\n */\nexport const toArray = set => Array.from(set)\n\n/**\n * @template T\n * @param {Set} set\n * @return {T}\n */\nexport const first = set =>\n set.values().next().value || undefined\n\n/**\n * @template T\n * @param {Iterable} entries\n * @return {Set}\n */\nexport const from = entries => new Set(entries)\n","/**\n * Utility module to work with Arrays.\n *\n * @module array\n */\n\nimport * as set from './set.js'\n\n/**\n * Return the last element of an array. The element must exist\n *\n * @template L\n * @param {ArrayLike} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array}\n */\nexport const create = () => /** @type {Array} */ ([])\n\n/**\n * @template D\n * @param {Array} a\n * @return {Array}\n */\nexport const copy = a => /** @type {Array} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array} dest\n * @param {Array} src\n */\nexport const appendTo = (dest, src) => {\n for (let i = 0; i < src.length; i++) {\n dest.push(src[i])\n }\n}\n\n/**\n * Transforms something array-like to an actual Array.\n *\n * @function\n * @template T\n * @param {ArrayLike|Iterable} arraylike\n * @return {T}\n */\nexport const from = Array.from\n\n/**\n * True iff condition holds on every element in the Array.\n *\n * @function\n * @template ITEM\n * @template {ArrayLike} ARR\n *\n * @param {ARR} arr\n * @param {function(ITEM, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const every = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (!f(arr[i], i, arr)) {\n return false\n }\n }\n return true\n}\n\n/**\n * True iff condition holds on some element in the Array.\n *\n * @function\n * @template S\n * @template {ArrayLike} ARR\n * @param {ARR} arr\n * @param {function(S, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const some = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (f(arr[i], i, arr)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @template ELEM\n *\n * @param {ArrayLike} a\n * @param {ArrayLike} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a.length === b.length && every(a, (item, index) => item === b[index])\n\n/**\n * @template ELEM\n * @param {Array>} arr\n * @return {Array}\n */\nexport const flatten = arr => arr.reduce((acc, val) => acc.concat(val), [])\n\nexport const isArray = Array.isArray\n\n/**\n * @template T\n * @param {Array} arr\n * @return {Array}\n */\nexport const unique = arr => from(set.from(arr))\n\n/**\n * @template T\n * @template M\n * @param {ArrayLike} arr\n * @param {function(T):M} mapper\n * @return {Array}\n */\nexport const uniqueBy = (arr, mapper) => {\n /**\n * @type {Set}\n */\n const happened = set.create()\n /**\n * @type {Array}\n */\n const result = []\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i]\n const mapped = mapper(el)\n if (!happened.has(mapped)) {\n happened.add(mapped)\n result.push(el)\n }\n }\n return result\n}\n","/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object} obj\n */\nexport const keys = Object.keys\n\n/**\n * @template V\n * @param {{[k:string]:V}} obj\n * @param {function(V,string):any} f\n */\nexport const forEach = (obj, f) => {\n for (const key in obj) {\n f(obj[key], key)\n }\n}\n\n/**\n * @todo implement mapToArray & map\n *\n * @template R\n * @param {Object} obj\n * @param {function(any,string):R} f\n * @return {Array}\n */\nexport const map = (obj, f) => {\n const results = []\n for (const key in obj) {\n results.push(f(obj[key], key))\n }\n return results\n}\n\n/**\n * @param {Object} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n for (const key in obj) {\n if (f(obj[key], key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {Object|undefined} obj\n */\nexport const isEmpty = obj => {\n for (const _k in obj) {\n return false\n }\n return true\n}\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n for (const key in obj) {\n if (!f(obj[key], key)) {\n return false\n }\n }\n return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object} a\n * @param {Object} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val))\n","/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array} fs\n * @param {Array} args\n */\nexport const callAll = (fs, args, i = 0) => {\n try {\n for (; i < fs.length; i++) {\n fs[i](...args)\n }\n } finally {\n if (i < fs.length) {\n callAll(fs, args, i + 1)\n }\n }\n}\n\nexport const nop = () => {}\n\n/**\n * @template T\n * @param {function():T} f\n * @return {T}\n */\nexport const apply = f => f()\n\n/**\n * @template A\n *\n * @param {A} a\n * @return {A}\n */\nexport const id = a => a\n\n/**\n * @template T\n *\n * @param {T} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equalityStrict = (a, b) => a === b\n\n/**\n * @template T\n *\n * @param {Array|object} a\n * @param {Array|object} b\n * @return {boolean}\n */\nexport const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((a instanceof Array && array.equalFlat(a, /** @type {Array} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/* c8 ignore start */\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a == null || b == null) {\n return equalityStrict(a, b)\n }\n if (a.constructor !== b.constructor) {\n return false\n }\n if (a === b) {\n return true\n }\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n break\n }\n case Map: {\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n return false\n }\n }\n break\n }\n case Object:\n if (object.length(a) !== object.length(b)) {\n return false\n }\n for (const key in a) {\n if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n return false\n }\n }\n break\n case Array:\n if (a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!equalityDeep(a[i], b[i])) {\n return false\n }\n }\n break\n default:\n return false\n }\n return true\n}\n\n/**\n * @template V\n * @template {V} OPTS\n *\n * @param {V} value\n * @param {Array} options\n */\n// @ts-ignore\nexport const isOneOf = (value, options) => options.includes(value)\n/* c8 ignore stop */\n","/**\n * Isomorphic module to work access the environment (query params, env variables).\n *\n * @module map\n */\n\nimport * as map from './map.js'\nimport * as string from './string.js'\nimport * as conditions from './conditions.js'\nimport * as storage from './storage.js'\nimport * as f from './function.js'\n\n/* c8 ignore next */\n// @ts-ignore\nexport const isNode = typeof process !== 'undefined' && process.release &&\n /node|io\\.js/.test(process.release.name)\n/* c8 ignore next */\nexport const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && !isNode\n/* c8 ignore next 3 */\nexport const isMac = typeof navigator !== 'undefined'\n ? /Mac/.test(navigator.platform)\n : false\n\n/**\n * @type {Map}\n */\nlet params\nconst args = []\n\n/* c8 ignore start */\nconst computeParams = () => {\n if (params === undefined) {\n if (isNode) {\n params = map.create()\n const pargs = process.argv\n let currParamName = null\n for (let i = 0; i < pargs.length; i++) {\n const parg = pargs[i]\n if (parg[0] === '-') {\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n currParamName = parg\n } else {\n if (currParamName !== null) {\n params.set(currParamName, parg)\n currParamName = null\n } else {\n args.push(parg)\n }\n }\n }\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n // in ReactNative for example this would not be true (unless connected to the Remote Debugger)\n } else if (typeof location === 'object') {\n params = map.create(); // eslint-disable-next-line no-undef\n (location.search || '?').slice(1).split('&').forEach((kv) => {\n if (kv.length !== 0) {\n const [key, value] = kv.split('=')\n params.set(`--${string.fromCamelCase(key, '-')}`, value)\n params.set(`-${string.fromCamelCase(key, '-')}`, value)\n }\n })\n } else {\n params = map.create()\n }\n }\n return params\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next */\nexport const hasParam = (name) => computeParams().has(name)\n\n/**\n * @param {string} name\n * @param {string} defaultVal\n * @return {string}\n */\n/* c8 ignore next 2 */\nexport const getParam = (name, defaultVal) =>\n computeParams().get(name) || defaultVal\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 4 */\nexport const getVariable = (name) =>\n isNode\n ? conditions.undefinedToNull(process.env[name.toUpperCase()])\n : conditions.undefinedToNull(storage.varStorage.getItem(name))\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 2 */\nexport const getConf = (name) =>\n computeParams().get('--' + name) || getVariable(name)\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next 2 */\nexport const hasConf = (name) =>\n hasParam('--' + name) || getVariable(name) !== null\n\n/* c8 ignore next */\nexport const production = hasConf('production')\n\n/* c8 ignore next 2 */\nconst forceColor = isNode &&\n f.isOneOf(process.env.FORCE_COLOR, ['true', '1', '2'])\n\n/* c8 ignore start */\nexport const supportsColor = !hasParam('no-colors') &&\n (!isNode || process.stdout.isTTY || forceColor) && (\n !isNode || hasParam('color') || forceColor ||\n getVariable('COLORTERM') !== null ||\n (getVariable('TERM') || '').includes('color')\n)\n/* c8 ignore stop */\n","/**\n * Common Math expressions.\n *\n * @module math\n */\n\nexport const floor = Math.floor\nexport const ceil = Math.ceil\nexport const abs = Math.abs\nexport const imul = Math.imul\nexport const round = Math.round\nexport const log10 = Math.log10\nexport const log2 = Math.log2\nexport const log = Math.log\nexport const sqrt = Math.sqrt\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The sum of a and b\n */\nexport const add = (a, b) => a + b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The smaller element of a and b\n */\nexport const min = (a, b) => a < b ? a : b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The bigger element of a and b\n */\nexport const max = (a, b) => a > b ? a : b\n\nexport const isNaN = Number.isNaN\n\nexport const pow = Math.pow\n/**\n * Base 10 exponential function. Returns the value of 10 raised to the power of pow.\n *\n * @param {number} exp\n * @return {number}\n */\nexport const exp10 = exp => Math.pow(10, exp)\n\nexport const sign = Math.sign\n\n/**\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\n/**\n * @type {number}\n */\nexport const HIGHEST_INT32 = binary.BITS31\n\n/**\n * @module number\n */\n\n/* c8 ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n","/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\nimport * as string from './string.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nexport const verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer. Max encodable integer is 2^53.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num = math.floor(num / 64) // shift >>> 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n}\n\n/**\n * A cache to store strings temporarily\n */\nconst _strBuffer = new Uint8Array(30000)\nconst _maxStrBSize = _strBuffer.length / 3\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringNative = (encoder, str) => {\n if (str.length < _maxStrBSize) {\n // We can encode the string into the existing buffer\n /* c8 ignore next */\n const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0\n writeVarUint(encoder, written)\n for (let i = 0; i < written; i++) {\n write(encoder, _strBuffer[i])\n }\n } else {\n writeVarUint8Array(encoder, string.encodeUtf8(str))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringPolyfill = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\n/* c8 ignore next */\nexport const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && math.abs(data) <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (data instanceof Array) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n","/**\n * Utility functions to work with buffers (Uint8Array).\n *\n * @module buffer\n */\n\nimport * as string from './string.js'\nimport * as env from './environment.js'\nimport * as encoding from './encoding.js'\nimport * as decoding from './decoding.js'\n\n/**\n * @param {number} len\n */\nexport const createUint8ArrayFromLen = len => new Uint8Array(len)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n * @param {number} byteOffset\n * @param {number} length\n */\nexport const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n */\nexport const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer)\n\n/* c8 ignore start */\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Browser = bytes => {\n let s = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n s += string.fromCharCode(bytes[i])\n }\n // eslint-disable-next-line no-undef\n return btoa(s)\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')\n\n/* c8 ignore start */\n/**\n * @param {string} s\n * @return {Uint8Array}\n */\nconst fromBase64Browser = s => {\n // eslint-disable-next-line no-undef\n const a = atob(s)\n const bytes = createUint8ArrayFromLen(a.length)\n for (let i = 0; i < a.length; i++) {\n bytes[i] = a.charCodeAt(i)\n }\n return bytes\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} s\n */\nconst fromBase64Node = s => {\n const buf = Buffer.from(s, 'base64')\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n}\n\n/* c8 ignore next */\nexport const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node\n\n/* c8 ignore next */\nexport const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node\n\n/**\n * Copy the content of an Uint8Array view to a new ArrayBuffer.\n *\n * @param {Uint8Array} uint8Array\n * @return {Uint8Array}\n */\nexport const copyUint8Array = uint8Array => {\n const newBuf = createUint8ArrayFromLen(uint8Array.byteLength)\n newBuf.set(uint8Array)\n return newBuf\n}\n\n/**\n * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type.\n * See encoding.writeAny for more information.\n *\n * @param {any} data\n * @return {Uint8Array}\n */\nexport const encodeAny = data => {\n const encoder = encoding.createEncoder()\n encoding.writeAny(encoder, data)\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Decode an any-encoded value.\n *\n * @param {Uint8Array} buf\n * @return {any}\n */\nexport const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf))\n","/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* c8 ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n","/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as binary from './binary.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as string from './string.js'\nimport * as error from './error.js'\n\nconst errorUnexpectedEndOfArray = error.create('Unexpected end of array')\nconst errorIntegerOutOfRange = error.create('Integer out of Range')\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n */\nexport class Decoder {\n /**\n * @param {Uint8Array} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @param {Uint8Array} uint8Array\n * @return {Decoder}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = buffer.createUint8ArrayViewFromArrayBuffer(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let mult = 1\n const len = decoder.arr.length\n while (decoder.pos < len) {\n const r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num\n mult *= 128 // next iteration, shift 7 \"more\" to the left\n if (r < binary.BIT8) {\n return num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let mult = 64\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n const len = decoder.arr.length\n while (decoder.pos < len) {\n r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult\n mult *= 128\n if (r < binary.BIT8) {\n return sign * num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * We don't test this function anymore as we use native decoding/encoding by default now.\n * Better not modify this anymore..\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\n/* c8 ignore start */\nexport const _readVarStringPolyfill = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n/* c8 ignore stop */\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n */\nexport const _readVarStringNative = decoder =>\n /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder))\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n *\n */\n/* c8 ignore next */\nexport const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object\n const len = readVarUint(decoder)\n /**\n * @type {Object}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = math.floor(diff / 2) // shift >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n","import {\n createDecoder,\n Decoder,\n readVarUint,\n readVarUint8Array,\n readVarString,\n} from 'lib0/decoding'\nimport {\n createEncoder,\n Encoder,\n toUint8Array,\n writeVarUint,\n writeVarString,\n length,\n} from 'lib0/encoding'\nimport { MessageType } from './types.js'\n\nexport class IncomingMessage {\n /**\n * Access to the received message.\n */\n decoder: Decoder\n\n /**\n * Access to the reply.\n */\n encoder: Encoder\n\n constructor(input: any) {\n if (!(input instanceof Uint8Array)) {\n input = new Uint8Array(input)\n }\n\n this.encoder = createEncoder()\n this.decoder = createDecoder(input)\n }\n\n readVarUint8Array() {\n return readVarUint8Array(this.decoder)\n }\n\n readVarUint() {\n return readVarUint(this.decoder)\n }\n\n readVarString() {\n return readVarString(this.decoder)\n }\n\n toUint8Array() {\n return toUint8Array(this.encoder)\n }\n\n writeVarUint(type: MessageType) {\n writeVarUint(this.encoder, type)\n }\n\n writeVarString(string: string) {\n writeVarString(this.encoder, string)\n }\n\n get length(): number {\n return length(this.encoder)\n }\n}\n","/**\n * @module sync-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as Y from 'yjs'\n\n/**\n * @typedef {Map} StateMap\n */\n\n/**\n * Core Yjs defines two message types:\n * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.\n * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it\n * received all information from the remote client.\n *\n * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection\n * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both\n * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.\n *\n * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.\n * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies\n * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the\n * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can\n * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them.\n * Therefore it is necesarry that the client initiates the sync.\n *\n * Construction of a message:\n * [messageType : varUint, message definition..]\n *\n * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!\n *\n * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)\n */\n\nexport const messageYjsSyncStep1 = 0\nexport const messageYjsSyncStep2 = 1\nexport const messageYjsUpdate = 2\n\n/**\n * Create a sync step 1 message based on the state of the current shared document.\n *\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n */\nexport const writeSyncStep1 = (encoder, doc) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep1)\n const sv = Y.encodeStateVector(doc)\n encoding.writeVarUint8Array(encoder, sv)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n * @param {Uint8Array} [encodedStateVector]\n */\nexport const writeSyncStep2 = (encoder, doc, encodedStateVector) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep2)\n encoding.writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector))\n}\n\n/**\n * Read SyncStep1 message and reply with SyncStep2.\n *\n * @param {decoding.Decoder} decoder The reply to the received message\n * @param {encoding.Encoder} encoder The received message\n * @param {Y.Doc} doc\n */\nexport const readSyncStep1 = (decoder, encoder, doc) =>\n writeSyncStep2(encoder, doc, decoding.readVarUint8Array(decoder))\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin) => {\n try {\n Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n } catch (error) {\n // This catches errors that are thrown by event handlers\n console.error('Caught error while handling a Yjs update', error)\n }\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Uint8Array} update\n */\nexport const writeUpdate = (encoder, update) => {\n encoding.writeVarUint(encoder, messageYjsUpdate)\n encoding.writeVarUint8Array(encoder, update)\n}\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readUpdate = readSyncStep2\n\n/**\n * @param {decoding.Decoder} decoder A message received from another client\n * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => {\n const messageType = decoding.readVarUint(decoder)\n switch (messageType) {\n case messageYjsSyncStep1:\n readSyncStep1(decoder, encoder, doc)\n break\n case messageYjsSyncStep2:\n readSyncStep2(decoder, doc, transactionOrigin)\n break\n case messageYjsUpdate:\n readUpdate(decoder, doc, transactionOrigin)\n break\n default:\n throw new Error('Unknown message type')\n }\n return messageType\n}\n","/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* c8 ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n","/**\n * Observable class prototype.\n *\n * @module observable\n */\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as array from './array.js'\n\n/**\n * Handles named events.\n *\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map}\n */\n this._observers = map.create()\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, name, set.create).add(f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, _f)\n f(...args)\n }\n this.on(name, _f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @param {N} name The event name.\n * @param {Array} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // 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.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n","/**\n * @module awareness-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as time from 'lib0/time'\nimport * as math from 'lib0/math'\nimport { Observable } from 'lib0/observable'\nimport * as f from 'lib0/function'\nimport * as Y from 'yjs' // eslint-disable-line\n\nexport const outdatedTimeout = 30000\n\n/**\n * @typedef {Object} MetaClientState\n * @property {number} MetaClientState.clock\n * @property {number} MetaClientState.lastUpdated unix timestamp\n */\n\n/**\n * The Awareness class implements a simple shared state protocol that can be used for non-persistent data like awareness information\n * (cursor, username, status, ..). Each client can update its own local state and listen to state changes of\n * remote clients. Every client may set a state of a remote peer to `null` to mark the client as offline.\n *\n * Each client is identified by a unique client id (something we borrow from `doc.clientID`). A client can override\n * its own state by propagating a message with an increasing timestamp (`clock`). If such a message is received, it is\n * applied if the known state of that client is older than the new state (`clock < newClock`). If a client thinks that\n * a remote client is offline, it may propagate a message with\n * `{ clock: currentClientClock, state: null, client: remoteClient }`. If such a\n * message is received, and the known clock of that client equals the received clock, it will override the state with `null`.\n *\n * Before a client disconnects, it should propagate a `null` state with an updated clock.\n *\n * Awareness states must be updated every 30 seconds. Otherwise the Awareness instance will delete the client state.\n *\n * @extends {Observable}\n */\nexport class Awareness extends Observable {\n /**\n * @param {Y.Doc} doc\n */\n constructor (doc) {\n super()\n this.doc = doc\n /**\n * @type {number}\n */\n this.clientID = doc.clientID\n /**\n * Maps from client id to client state\n * @type {Map>}\n */\n this.states = new Map()\n /**\n * @type {Map}\n */\n this.meta = new Map()\n this._checkInterval = /** @type {any} */ (setInterval(() => {\n const now = time.getUnixTime()\n if (this.getLocalState() !== null && (outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ (this.meta.get(this.clientID)).lastUpdated)) {\n // renew local clock\n this.setLocalState(this.getLocalState())\n }\n /**\n * @type {Array}\n */\n const remove = []\n this.meta.forEach((meta, clientid) => {\n if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) {\n remove.push(clientid)\n }\n })\n if (remove.length > 0) {\n removeAwarenessStates(this, remove, 'timeout')\n }\n }, math.floor(outdatedTimeout / 10)))\n doc.on('destroy', () => {\n this.destroy()\n })\n this.setLocalState({})\n }\n\n destroy () {\n this.emit('destroy', [this])\n this.setLocalState(null)\n super.destroy()\n clearInterval(this._checkInterval)\n }\n\n /**\n * @return {Object|null}\n */\n getLocalState () {\n return this.states.get(this.clientID) || null\n }\n\n /**\n * @param {Object|null} state\n */\n setLocalState (state) {\n const clientID = this.clientID\n const currLocalMeta = this.meta.get(clientID)\n const clock = currLocalMeta === undefined ? 0 : currLocalMeta.clock + 1\n const prevState = this.states.get(clientID)\n if (state === null) {\n this.states.delete(clientID)\n } else {\n this.states.set(clientID, state)\n }\n this.meta.set(clientID, {\n clock,\n lastUpdated: time.getUnixTime()\n })\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n if (state === null) {\n removed.push(clientID)\n } else if (prevState == null) {\n if (state != null) {\n added.push(clientID)\n }\n } else {\n updated.push(clientID)\n if (!f.equalityDeep(prevState, state)) {\n filteredUpdated.push(clientID)\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n this.emit('change', [{ added, updated: filteredUpdated, removed }, 'local'])\n }\n this.emit('update', [{ added, updated, removed }, 'local'])\n }\n\n /**\n * @param {string} field\n * @param {any} value\n */\n setLocalStateField (field, value) {\n const state = this.getLocalState()\n if (state !== null) {\n this.setLocalState({\n ...state,\n [field]: value\n })\n }\n }\n\n /**\n * @return {Map>}\n */\n getStates () {\n return this.states\n }\n}\n\n/**\n * Mark (remote) clients as inactive and remove them from the list of active peers.\n * This change will be propagated to remote clients.\n *\n * @param {Awareness} awareness\n * @param {Array} clients\n * @param {any} origin\n */\nexport const removeAwarenessStates = (awareness, clients, origin) => {\n const removed = []\n for (let i = 0; i < clients.length; i++) {\n const clientID = clients[i]\n if (awareness.states.has(clientID)) {\n awareness.states.delete(clientID)\n if (clientID === awareness.clientID) {\n const curMeta = /** @type {MetaClientState} */ (awareness.meta.get(clientID))\n awareness.meta.set(clientID, {\n clock: curMeta.clock + 1,\n lastUpdated: time.getUnixTime()\n })\n }\n removed.push(clientID)\n }\n }\n if (removed.length > 0) {\n awareness.emit('change', [{ added: [], updated: [], removed }, origin])\n awareness.emit('update', [{ added: [], updated: [], removed }, origin])\n }\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Array} clients\n * @return {Uint8Array}\n */\nexport const encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {\n const len = clients.length\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = clients[i]\n const state = states.get(clientID) || null\n const clock = /** @type {MetaClientState} */ (awareness.meta.get(clientID)).clock\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(state))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Modify the content of an awareness update before re-encoding it to an awareness update.\n *\n * This might be useful when you have a central server that wants to ensure that clients\n * cant hijack somebody elses identity.\n *\n * @param {Uint8Array} update\n * @param {function(any):any} modify\n * @return {Uint8Array}\n */\nexport const modifyAwarenessUpdate = (update, modify) => {\n const decoder = decoding.createDecoder(update)\n const encoder = encoding.createEncoder()\n const len = decoding.readVarUint(decoder)\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n const clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const modifiedState = modify(state)\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(modifiedState))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Uint8Array} update\n * @param {any} origin This will be added to the emitted change event\n */\nexport const applyAwarenessUpdate = (awareness, update, origin) => {\n const decoder = decoding.createDecoder(update)\n const timestamp = time.getUnixTime()\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n const len = decoding.readVarUint(decoder)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n let clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const clientMeta = awareness.meta.get(clientID)\n const prevState = awareness.states.get(clientID)\n const currClock = clientMeta === undefined ? 0 : clientMeta.clock\n if (currClock < clock || (currClock === clock && state === null && awareness.states.has(clientID))) {\n if (state === null) {\n // never let a remote client remove this local state\n if (clientID === awareness.clientID && awareness.getLocalState() != null) {\n // remote client removed the local state. Do not remote state. Broadcast a message indicating\n // that this client still exists by increasing the clock\n clock++\n } else {\n awareness.states.delete(clientID)\n }\n } else {\n awareness.states.set(clientID, state)\n }\n awareness.meta.set(clientID, {\n clock,\n lastUpdated: timestamp\n })\n if (clientMeta === undefined && state !== null) {\n added.push(clientID)\n } else if (clientMeta !== undefined && state === null) {\n removed.push(clientID)\n } else if (state !== null) {\n if (!f.equalityDeep(state, prevState)) {\n filteredUpdated.push(clientID)\n }\n updated.push(clientID)\n }\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n awareness.emit('change', [{\n added, updated: filteredUpdated, removed\n }, origin])\n }\n if (added.length > 0 || updated.length > 0 || removed.length > 0) {\n awareness.emit('update', [{\n added, updated, removed\n }, origin])\n }\n}\n","import {\n IncomingHttpHeaders, IncomingMessage, ServerResponse,\n} from 'http'\nimport { URLSearchParams } from 'url'\nimport { Awareness } from 'y-protocols/awareness'\nimport Document from './Document.js'\nimport { Hocuspocus } from './Hocuspocus.js'\nimport Connection from './Connection.js'\n\nexport enum MessageType {\n Unknown = -1,\n Sync = 0,\n Awareness = 1,\n Auth = 2,\n QueryAwareness = 3,\n SyncReply = 4, // same as Sync, but won't trigger another 'SyncStep1'\n Stateless = 5,\n BroadcastStateless = 6,\n\n CLOSE = 7,\n}\n\nexport interface AwarenessUpdate {\n added: Array,\n updated: Array,\n removed: Array,\n}\n\nexport interface ConnectionConfiguration {\n readOnly: boolean\n requiresAuthentication: boolean\n isAuthenticated: boolean\n}\n\nexport interface Extension {\n priority?: number,\n onConfigure?(data: onConfigurePayload): Promise,\n onListen?(data: onListenPayload): Promise,\n onUpgrade?(data: onUpgradePayload): Promise,\n onConnect?(data: onConnectPayload): Promise,\n connected?(data: connectedPayload): Promise,\n onAuthenticate?(data: onAuthenticatePayload): Promise,\n onLoadDocument?(data: onLoadDocumentPayload): Promise,\n afterLoadDocument?(data: onLoadDocumentPayload): Promise,\n beforeHandleMessage?(data: beforeHandleMessagePayload): Promise,\n beforeBroadcastStateless?(data: beforeBroadcastStatelessPayload): Promise,\n onStateless?(payload: onStatelessPayload): Promise;\n onChange?(data: onChangePayload): Promise,\n onStoreDocument?(data: onStoreDocumentPayload): Promise,\n afterStoreDocument?(data: afterStoreDocumentPayload): Promise,\n onAwarenessUpdate?(data: onAwarenessUpdatePayload): Promise,\n onRequest?(data: onRequestPayload): Promise,\n onDisconnect?(data: onDisconnectPayload): Promise\n onDestroy?(data: onDestroyPayload): Promise,\n}\n\nexport type HookName =\n 'onConfigure' |\n 'onListen' |\n 'onUpgrade' |\n 'onConnect' |\n 'connected' |\n 'onAuthenticate' |\n 'onLoadDocument' |\n 'afterLoadDocument' |\n 'beforeHandleMessage' |\n 'beforeBroadcastStateless' |\n 'onStateless' |\n 'onChange' |\n 'onStoreDocument' |\n 'afterStoreDocument' |\n 'onAwarenessUpdate' |\n 'onRequest' |\n 'onDisconnect' |\n 'onDestroy'\n\nexport type HookPayload =\n onConfigurePayload |\n onListenPayload |\n onUpgradePayload |\n onConnectPayload |\n connectedPayload |\n onAuthenticatePayload |\n onLoadDocumentPayload |\n onStatelessPayload |\n beforeHandleMessagePayload |\n beforeBroadcastStatelessPayload |\n onChangePayload |\n onStoreDocumentPayload |\n afterStoreDocumentPayload |\n onAwarenessUpdatePayload |\n onRequestPayload |\n onDisconnectPayload |\n onDestroyPayload\n\nexport interface Configuration extends Extension {\n /**\n * A name for the instance, used for logging.\n */\n name: string | null,\n /**\n * A list of hocuspocus extenions.\n */\n extensions: Array,\n /**\n * The port which the server listens on.\n */\n port?: number,\n /**\n * The address which the server listens on.\n */\n address?: string,\n /**\n * Defines in which interval the server sends a ping, and closes the connection when no pong is sent back.\n */\n timeout: number,\n /**\n * Debounces the call of the `onStoreDocument` hook for the given amount of time in ms.\n * Otherwise every single update would be persisted.\n */\n debounce: number,\n /**\n * Makes sure to call `onStoreDocument` at least in the given amount of time (ms).\n */\n maxDebounce: number\n /**\n * By default, the servers show a start screen. If passed false, the server will start quietly.\n */\n quiet: boolean,\n\n /**\n * options to pass to the ydoc document\n */\n yDocOptions: {\n gc: boolean, // enable or disable garbage collection (see https://github.com/yjs/yjs/blob/main/INTERNALS.md#deletions)\n gcFilter: () => boolean, // will be called before garbage collecting ; return false to keep it\n },\n /**\n * Function which returns the (customized) document name based on the request\n */\n getDocumentName?(data: getDocumentNamePayload): string | Promise,\n}\n\nexport interface getDocumentNamePayload {\n documentName: string,\n request: IncomingMessage,\n requestParameters: URLSearchParams,\n}\n\nexport interface onStatelessPayload {\n connection: Connection,\n documentName: string,\n document: Document,\n payload: string,\n}\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface onAuthenticatePayload {\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n token: string,\n connection: ConnectionConfiguration\n}\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface onConnectPayload {\n documentName: string,\n instance: Hocuspocus,\n request: IncomingMessage,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration\n}\n\n// @todo Change 'connection' to 'connectionConfig', and 'connectionInstance' to 'connection' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface connectedPayload {\n context: any,\n documentName: string,\n instance: Hocuspocus,\n request: IncomingMessage,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration,\n connectionInstance: Connection\n}\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface onLoadDocumentPayload {\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration\n}\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface afterLoadDocumentPayload {\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration\n}\n\nexport interface onChangePayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n update: Uint8Array,\n socketId: string,\n}\n\nexport interface beforeHandleMessagePayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n update: Uint8Array,\n socketId: string,\n connection: Connection\n}\n\nexport interface beforeBroadcastStatelessPayload {\n document: Document,\n documentName: string,\n payload: string,\n}\n\nexport interface onStoreDocumentPayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n}\n\nexport interface afterStoreDocumentPayload extends onStoreDocumentPayload {}\n\nexport interface onAwarenessUpdatePayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n update: Uint8Array,\n socketId: string,\n added: number[],\n updated: number[],\n removed: number[],\n awareness: Awareness,\n states: StatesArray,\n}\n\nexport type StatesArray = { clientId: number, [key: string | number]: any }[]\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface fetchPayload {\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration\n}\n\nexport interface storePayload extends onStoreDocumentPayload {\n state: Buffer,\n}\n\nexport interface onDisconnectPayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n}\n\nexport interface onRequestPayload {\n request: IncomingMessage,\n response: ServerResponse,\n instance: Hocuspocus,\n}\n\nexport interface onUpgradePayload {\n request: IncomingMessage,\n socket: any,\n head: any,\n instance: Hocuspocus,\n}\n\nexport interface onListenPayload {\n instance: Hocuspocus,\n configuration: Configuration,\n port: number,\n}\n\nexport interface onDestroyPayload {\n instance: Hocuspocus,\n}\n\nexport interface onConfigurePayload {\n instance: Hocuspocus,\n configuration: Configuration,\n version: string,\n}\n","import {\n createEncoder,\n Encoder,\n toUint8Array,\n writeVarString,\n writeVarUint,\n writeVarUint8Array,\n} from 'lib0/encoding'\nimport { writeSyncStep1, writeUpdate } from 'y-protocols/sync'\nimport { Awareness, encodeAwarenessUpdate } from 'y-protocols/awareness'\n\nimport { writeAuthenticated, writePermissionDenied } from '@hocuspocus/common'\nimport { MessageType } from './types.js'\nimport Document from './Document.js'\n\nexport class OutgoingMessage {\n\n encoder: Encoder\n\n type?: number\n\n category?: string\n\n constructor(documentName: string) {\n this.encoder = createEncoder()\n\n writeVarString(this.encoder, documentName)\n }\n\n createSyncMessage(): OutgoingMessage {\n this.type = MessageType.Sync\n\n writeVarUint(this.encoder, MessageType.Sync)\n\n return this\n }\n\n createSyncReplyMessage(): OutgoingMessage {\n this.type = MessageType.SyncReply\n\n writeVarUint(this.encoder, MessageType.SyncReply)\n\n return this\n }\n\n createAwarenessUpdateMessage(awareness: Awareness, changedClients?: Array): OutgoingMessage {\n this.type = MessageType.Awareness\n this.category = 'Update'\n\n const message = encodeAwarenessUpdate(\n awareness,\n changedClients || Array.from(awareness.getStates().keys()),\n )\n\n writeVarUint(this.encoder, MessageType.Awareness)\n writeVarUint8Array(this.encoder, message)\n\n return this\n }\n\n writeQueryAwareness(): OutgoingMessage {\n this.type = MessageType.QueryAwareness\n this.category = 'Update'\n\n writeVarUint(this.encoder, MessageType.QueryAwareness)\n\n return this\n }\n\n writeAuthenticated(readonly: boolean): OutgoingMessage {\n this.type = MessageType.Auth\n this.category = 'Authenticated'\n\n writeVarUint(this.encoder, MessageType.Auth)\n writeAuthenticated(this.encoder, readonly ? 'readonly' : 'read-write')\n\n return this\n }\n\n writePermissionDenied(reason: string): OutgoingMessage {\n this.type = MessageType.Auth\n this.category = 'PermissionDenied'\n\n writeVarUint(this.encoder, MessageType.Auth)\n writePermissionDenied(this.encoder, reason)\n\n return this\n }\n\n writeFirstSyncStepFor(document: Document): OutgoingMessage {\n this.category = 'SyncStep1'\n\n writeSyncStep1(this.encoder, document)\n\n return this\n }\n\n writeUpdate(update: Uint8Array): OutgoingMessage {\n this.category = 'Update'\n\n writeUpdate(this.encoder, update)\n\n return this\n }\n\n writeStateless(payload: string): OutgoingMessage {\n this.category = 'Stateless'\n\n writeVarUint(this.encoder, MessageType.Stateless)\n writeVarString(this.encoder, payload)\n\n return this\n }\n\n writeBroadcastStateless(payload: string): OutgoingMessage {\n this.category = 'Stateless'\n\n writeVarUint(this.encoder, MessageType.BroadcastStateless)\n writeVarString(this.encoder, payload)\n\n return this\n }\n\n toUint8Array(): Uint8Array {\n return toUint8Array(this.encoder)\n }\n\n}\n","import {\n messageYjsSyncStep1,\n messageYjsSyncStep2,\n messageYjsUpdate,\n readSyncStep1,\n readSyncStep2,\n readUpdate,\n} from 'y-protocols/sync'\nimport { applyAwarenessUpdate } from 'y-protocols/awareness'\nimport { readVarString } from 'lib0/decoding'\nimport { MessageType } from './types.js'\nimport Connection from './Connection.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { Debugger } from './Debugger.js'\nimport Document from './Document.js'\n\nexport class MessageReceiver {\n\n message: IncomingMessage\n\n logger: Debugger\n\n constructor(message: IncomingMessage, logger: Debugger) {\n this.message = message\n this.logger = logger\n }\n\n public apply(document: Document, connection?: Connection, reply?: (message: Uint8Array) => void) {\n const { message } = this\n const type = message.readVarUint()\n const emptyMessageLength = message.length\n\n switch (type) {\n case MessageType.Sync:\n case MessageType.SyncReply: {\n message.writeVarUint(MessageType.Sync)\n this.readSyncMessage(message, document, connection, reply, type !== MessageType.SyncReply)\n\n if (message.length > emptyMessageLength + 1) {\n if (reply) {\n reply(message.toUint8Array())\n } else if (connection) {\n // TODO: We should log this, shouldn’t we?\n // this.logger.log({\n // direction: 'out',\n // type: MessageType.Awareness,\n // category: 'Update',\n // })\n connection.send(message.toUint8Array())\n }\n }\n\n break\n }\n case MessageType.Awareness: {\n this.logger.log({\n direction: 'in',\n type: MessageType.Awareness,\n category: 'Update',\n })\n\n applyAwarenessUpdate(document.awareness, message.readVarUint8Array(), connection)\n\n break\n }\n case MessageType.QueryAwareness: {\n\n this.applyQueryAwarenessMessage(document, reply)\n\n break\n }\n case MessageType.Stateless: {\n connection?.callbacks.statelessCallback({\n connection,\n documentName: document.name,\n document,\n payload: readVarString(message.decoder),\n })\n\n break\n }\n case MessageType.BroadcastStateless: {\n const msg = message.readVarString()\n document.getConnections().forEach(connection => {\n connection.sendStateless(msg)\n })\n break\n }\n\n case MessageType.CLOSE: {\n connection?.close({\n code: 1000,\n reason: 'provider_initiated',\n })\n break\n }\n default:\n console.error(`Unable to handle message of type ${type}: no handler defined!`)\n // Do nothing\n }\n }\n\n readSyncMessage(message: IncomingMessage, document: Document, connection?: Connection, reply?: (message: Uint8Array) => void, requestFirstSync = true) {\n const type = message.readVarUint()\n\n switch (type) {\n case messageYjsSyncStep1: {\n this.logger.log({\n direction: 'in',\n type: MessageType.Sync,\n category: 'SyncStep1',\n })\n\n readSyncStep1(message.decoder, message.encoder, document)\n\n // When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1.\n this.logger.log({\n direction: 'out',\n type: MessageType.Sync,\n category: 'SyncStep2',\n })\n\n if (reply && requestFirstSync) {\n const syncMessage = (new OutgoingMessage(document.name)\n .createSyncReplyMessage()\n .writeFirstSyncStepFor(document))\n\n this.logger.log({\n direction: 'out',\n type: MessageType.Sync,\n category: 'SyncStep1',\n })\n\n reply(syncMessage.toUint8Array())\n } else if (connection) {\n const syncMessage = (new OutgoingMessage(document.name)\n .createSyncMessage()\n .writeFirstSyncStepFor(document))\n\n this.logger.log({\n direction: 'out',\n type: MessageType.Sync,\n category: 'SyncStep1',\n })\n\n connection.send(syncMessage.toUint8Array())\n }\n break\n }\n case messageYjsSyncStep2:\n this.logger.log({\n direction: 'in',\n type: MessageType.Sync,\n category: 'SyncStep2',\n })\n\n if (connection?.readOnly) {\n break\n }\n\n readSyncStep2(message.decoder, document, connection)\n break\n case messageYjsUpdate:\n this.logger.log({\n direction: 'in',\n type: MessageType.Sync,\n category: 'Update',\n })\n\n if (connection?.readOnly) {\n break\n }\n\n readUpdate(message.decoder, document, connection)\n break\n default:\n throw new Error(`Received a message with an unknown type: ${type}`)\n }\n\n return type\n }\n\n applyQueryAwarenessMessage(document: Document, reply?: (message: Uint8Array) => void) {\n const message = new OutgoingMessage(document.name)\n .createAwarenessUpdateMessage(document.awareness)\n\n if (reply) {\n reply(message.toUint8Array())\n }\n\n // TODO: We should add support for WebSocket connections, too, right?\n // this.logger.log({\n // direction: 'out',\n // type: MessageType.Sync,\n // category: 'SyncStep1',\n // })\n\n // connection.send(syncMessage.toUint8Array())\n }\n}\n","import { IncomingMessage as HTTPIncomingMessage } from 'http'\nimport AsyncLock from 'async-lock'\nimport WebSocket from 'ws'\nimport {\n CloseEvent, ConnectionTimeout, Forbidden, WsReadyStates,\n} from '@hocuspocus/common'\nimport Document from './Document.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { MessageReceiver } from './MessageReceiver.js'\nimport { Debugger } from './Debugger.js'\nimport { onStatelessPayload } from './types.js'\n\nexport class Connection {\n\n webSocket: WebSocket\n\n context: any\n\n document: Document\n\n pingInterval: NodeJS.Timeout\n\n pongReceived = true\n\n request: HTTPIncomingMessage\n\n timeout: number\n\n callbacks: any = {\n onClose: [(document: Document, event?: CloseEvent) => null],\n beforeHandleMessage: (connection: Connection, update: Uint8Array) => Promise,\n statelessCallback: () => Promise,\n }\n\n socketId: string\n\n lock: AsyncLock\n\n readOnly: Boolean\n\n logger: Debugger\n\n /**\n * Constructor.\n */\n constructor(\n connection: WebSocket,\n request: HTTPIncomingMessage,\n document: Document,\n timeout: number,\n socketId: string,\n context: any,\n readOnly = false,\n logger: Debugger,\n ) {\n this.webSocket = connection\n this.context = context\n this.document = document\n this.request = request\n this.timeout = timeout\n this.socketId = socketId\n this.readOnly = readOnly\n this.logger = logger\n\n this.lock = new AsyncLock()\n\n this.webSocket.binaryType = 'arraybuffer'\n this.document.addConnection(this)\n\n this.pingInterval = setInterval(this.check.bind(this), this.timeout)\n\n this.webSocket.on('close', this.boundClose)\n this.webSocket.on('message', this.boundHandleMessage)\n this.webSocket.on('pong', this.boundHandlePong)\n\n this.sendCurrentAwareness()\n }\n\n boundClose = this.close.bind(this)\n\n boundHandleMessage = this.handleMessage.bind(this)\n\n boundHandlePong = this.handlePong.bind(this)\n\n handlePong() {\n this.pongReceived = true\n }\n\n /**\n * Set a callback that will be triggered when the connection is closed\n */\n onClose(callback: (document: Document, event?: CloseEvent) => void): Connection {\n this.callbacks.onClose.push(callback)\n\n return this\n }\n\n /**\n * Set a callback that will be triggered when an stateless message is received\n */\n onStatelessCallback(callback: (payload: onStatelessPayload) => Promise): Connection {\n this.callbacks.statelessCallback = callback\n\n return this\n }\n\n /**\n * Set a callback that will be triggered before an message is handled\n */\n beforeHandleMessage(callback: (connection: Connection, update: Uint8Array) => Promise): Connection {\n this.callbacks.beforeHandleMessage = callback\n\n return this\n }\n\n /**\n * Send the given message\n */\n send(message: any): void {\n if (\n this.webSocket.readyState === WsReadyStates.Closing\n || this.webSocket.readyState === WsReadyStates.Closed\n ) {\n this.close()\n }\n\n try {\n this.webSocket.send(message, (error: any) => {\n if (error != null) this.close()\n })\n } catch (exception) {\n this.close()\n }\n }\n\n /**\n * Send a stateless message with payload\n */\n public sendStateless(payload: string): void {\n const message = new OutgoingMessage(this.document.name)\n .writeStateless(payload)\n\n this.logger.log({\n direction: 'out',\n type: message.type,\n category: message.category,\n })\n\n this.send(\n message.toUint8Array(),\n )\n }\n\n /**\n * Graceful wrapper around the WebSocket close method.\n */\n close(event?: CloseEvent): void {\n this.lock.acquire('close', (done: Function) => {\n if (this.pingInterval) {\n clearInterval(this.pingInterval)\n }\n\n if (this.document.hasConnection(this)) {\n this.document.removeConnection(this)\n clearInterval(this.pingInterval)\n\n this.webSocket.removeListener('close', this.boundClose)\n this.webSocket.removeListener('message', this.boundHandleMessage)\n this.webSocket.removeListener('pong', this.boundHandlePong)\n\n this.callbacks.onClose.forEach((callback: (arg0: Document, arg1?: CloseEvent) => any) => callback(this.document, event))\n }\n\n done()\n })\n }\n\n /**\n * Check if pong was received and close the connection otherwise\n * @private\n */\n private check(): void {\n if (!this.pongReceived) {\n return this.close(ConnectionTimeout)\n }\n\n if (this.document.hasConnection(this)) {\n this.pongReceived = false\n\n try {\n this.webSocket.ping()\n } catch (error) {\n this.close(ConnectionTimeout)\n }\n }\n }\n\n /**\n * Send the current document awareness to the client, if any\n * @private\n */\n private sendCurrentAwareness(): void {\n if (!this.document.hasAwarenessStates()) {\n return\n }\n\n const awarenessMessage = new OutgoingMessage(this.document.name)\n .createAwarenessUpdateMessage(this.document.awareness)\n\n this.logger.log({\n direction: 'out',\n type: awarenessMessage.type,\n category: awarenessMessage.category,\n })\n\n this.send(awarenessMessage.toUint8Array())\n }\n\n /**\n * Handle an incoming message\n * @private\n */\n private handleMessage(data: Uint8Array): void {\n const message = new IncomingMessage(data)\n const documentName = message.readVarString()\n\n if (documentName !== this.document.name) return\n\n message.writeVarString(documentName)\n\n this.callbacks.beforeHandleMessage(this, data)\n .then(() => {\n new MessageReceiver(\n message,\n this.logger,\n ).apply(this.document, this)\n })\n .catch((e: any) => {\n console.log('closing connection because of exception', e)\n this.close({\n code: 'code' in e ? e.code : Forbidden.code,\n reason: 'reason' in e ? e.reason : Forbidden.reason,\n })\n })\n }\n\n}\n\nexport default Connection\n","// import * as time from 'lib0/time'\nimport { MessageType } from './types.js'\n\nexport class Debugger {\n logs: any[] = []\n\n listen = false\n\n output = false\n\n enable() {\n this.flush()\n\n this.listen = true\n }\n\n disable() {\n this.listen = false\n }\n\n verbose() {\n this.output = true\n }\n\n quiet() {\n this.output = false\n }\n\n log(message: any) {\n if (!this.listen) {\n return this\n }\n\n const item = {\n ...message,\n type: MessageType[message.type],\n // time: time.getUnixTime(),\n }\n\n this.logs.push(item)\n\n if (this.output) {\n console.log('[DEBUGGER]', item.direction === 'in' ? 'IN –>' : 'OUT <–', `${item.type}/${item.category}`)\n }\n\n return this\n }\n\n flush() {\n this.logs = []\n\n return this\n }\n\n get() {\n return {\n logs: this.logs,\n }\n }\n}\n","/**\n * Mutual exclude for JavaScript.\n *\n * @module mutex\n */\n\n/**\n * @callback mutex\n * @param {function():void} cb Only executed when this mutex is not in the current stack\n * @param {function():void} [elseCb] Executed when this mutex is in the current stack\n */\n\n/**\n * Creates a mutual exclude function with the following property:\n *\n * ```js\n * const mutex = createMutex()\n * mutex(() => {\n * // This function is immediately executed\n * mutex(() => {\n * // This function is not executed, as the mutex is already active.\n * })\n * })\n * ```\n *\n * @return {mutex} A mutual exclude function\n * @public\n */\nexport const createMutex = () => {\n let token = true\n return (f, g) => {\n if (token) {\n token = false\n try {\n f()\n } finally {\n token = true\n }\n } else if (g !== undefined) {\n g()\n }\n }\n}\n","import WebSocket from 'ws'\nimport { Awareness, removeAwarenessStates, applyAwarenessUpdate } from 'y-protocols/awareness'\nimport { applyUpdate, Doc, encodeStateAsUpdate } from 'yjs'\nimport { mutex, createMutex } from 'lib0/mutex.js'\nimport { AwarenessUpdate } from './types.js'\nimport Connection from './Connection.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { Debugger } from './Debugger.js'\n\nexport class Document extends Doc {\n\n awareness: Awareness\n\n callbacks = {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n onUpdate: (document: Document, connection: Connection, update: Uint8Array) => {},\n beforeBroadcastStateless: (document: Document, stateless: string) => {},\n }\n\n connections: Map,\n connection: Connection\n }> = new Map()\n\n // The number of direct (non-websocket) connections to this document\n directConnectionsCount = 0\n\n name: string\n\n mux: mutex\n\n logger: Debugger\n\n isLoading: boolean\n\n /**\n * Constructor.\n */\n constructor(name: string, logger: Debugger, yDocOptions: {}) {\n super(yDocOptions)\n\n this.name = name\n this.mux = createMutex()\n\n this.awareness = new Awareness(this)\n this.awareness.setLocalState(null)\n\n this.awareness.on('update', this.handleAwarenessUpdate.bind(this))\n this.on('update', this.handleUpdate.bind(this))\n\n this.logger = logger\n this.isLoading = true\n }\n\n /**\n * Check if the Document is empty\n */\n isEmpty(fieldName: string): boolean {\n // eslint-disable-next-line no-underscore-dangle\n return !this.get(fieldName)._start\n }\n\n /**\n * Merge the given document(s) into this one\n */\n merge(documents: Doc|Array): Document {\n (Array.isArray(documents) ? documents : [documents]).forEach(document => {\n applyUpdate(this, encodeStateAsUpdate(document))\n })\n\n return this\n }\n\n /**\n * Set a callback that will be triggered when the document is updated\n */\n onUpdate(callback: (document: Document, connection: Connection, update: Uint8Array) => void): Document {\n this.callbacks.onUpdate = callback\n\n return this\n }\n\n /**\n * Set a callback that will be triggered before a stateless message is broadcasted\n */\n beforeBroadcastStateless(callback: (document: Document, stateless: string) => void): Document {\n this.callbacks.beforeBroadcastStateless = callback\n\n return this\n }\n\n /**\n * Register a connection and a set of clients on this document keyed by the\n * underlying websocket connection\n */\n addConnection(connection: Connection): Document {\n this.connections.set(connection.webSocket, {\n clients: new Set(),\n connection,\n })\n\n return this\n }\n\n /**\n * Is the given connection registered on this document\n */\n hasConnection(connection: Connection): boolean {\n return this.connections.has(connection.webSocket)\n }\n\n /**\n * Remove the given connection from this document\n */\n removeConnection(connection: Connection): Document {\n removeAwarenessStates(\n this.awareness,\n Array.from(this.getClients(connection.webSocket)),\n null,\n )\n\n this.connections.delete(connection.webSocket)\n\n return this\n }\n\n addDirectConnection(): Document {\n this.directConnectionsCount += 1\n\n return this\n }\n\n removeDirectConnection(): Document {\n if (this.directConnectionsCount > 0) {\n this.directConnectionsCount -= 1\n }\n\n return this\n }\n\n /**\n * Get the number of active connections for this document\n */\n getConnectionsCount(): number {\n return this.connections.size + this.directConnectionsCount\n }\n\n /**\n * Get an array of registered connections\n */\n getConnections(): Array {\n return Array.from(this.connections.values()).map(data => data.connection)\n }\n\n /**\n * Get the client ids for the given connection instance\n */\n getClients(connectionInstance: WebSocket): Set {\n const connection = this.connections.get(connectionInstance)\n\n return connection?.clients === undefined ? new Set() : connection.clients\n }\n\n /**\n * Has the document awareness states\n */\n hasAwarenessStates(): boolean {\n return this.awareness.getStates().size > 0\n }\n\n /**\n * Apply the given awareness update\n */\n applyAwarenessUpdate(connection: Connection, update: Uint8Array): Document {\n applyAwarenessUpdate(\n this.awareness,\n update,\n connection.webSocket,\n )\n\n return this\n }\n\n /**\n * Handle an awareness update and sync changes to clients\n * @private\n */\n private handleAwarenessUpdate(\n { added, updated, removed }: AwarenessUpdate,\n connectionInstance: WebSocket,\n ): Document {\n const changedClients = added.concat(updated, removed)\n\n if (connectionInstance !== null) {\n const connection = this.connections.get(connectionInstance)\n\n if (connection) {\n added.forEach((clientId: any) => connection.clients.add(clientId))\n removed.forEach((clientId: any) => connection.clients.delete(clientId))\n }\n }\n\n this.getConnections().forEach(connection => {\n const awarenessMessage = new OutgoingMessage(this.name)\n .createAwarenessUpdateMessage(this.awareness, changedClients)\n\n this.logger.log({\n direction: 'out',\n type: awarenessMessage.type,\n category: awarenessMessage.category,\n })\n\n connection.send(\n awarenessMessage.toUint8Array(),\n )\n })\n\n return this\n }\n\n /**\n * Handle an updated document and sync changes to clients\n */\n private handleUpdate(update: Uint8Array, connection: Connection): Document {\n this.callbacks.onUpdate(this, connection, update)\n\n const message = new OutgoingMessage(this.name)\n .createSyncMessage()\n .writeUpdate(update)\n\n this.getConnections().forEach(connection => {\n this.logger.log({\n direction: 'out',\n type: message.type,\n category: message.category,\n })\n\n connection.send(\n message.toUint8Array(),\n )\n })\n\n return this\n }\n\n /**\n * Broadcast stateless message to all connections\n */\n public broadcastStateless(payload: string): void {\n this.callbacks.beforeBroadcastStateless(this, payload)\n\n this.getConnections().forEach(connection => {\n connection.sendStateless(payload)\n })\n }\n}\n\nexport default Document\n","import { URLSearchParams } from 'url'\nimport Document from './Document.js'\nimport type { Hocuspocus } from './Hocuspocus.js'\n\nexport class DirectConnection {\n document: Document | null = null\n\n instance!: Hocuspocus\n\n context: any\n\n /**\n * Constructor.\n */\n constructor(\n document: Document,\n instance: Hocuspocus,\n context?: any,\n ) {\n this.document = document\n this.instance = instance\n this.context = context\n\n this.document.addDirectConnection()\n }\n\n async transact(transaction: (document: Document) => void) {\n if (!this.document) {\n throw new Error('direct connection closed')\n }\n\n transaction(this.document)\n\n this.instance.storeDocumentHooks(this.document, {\n clientsCount: this.document.getConnectionsCount(),\n context: this.context,\n document: this.document,\n documentName: this.document.name,\n instance: this.instance,\n requestHeaders: {},\n requestParameters: new URLSearchParams(),\n socketId: 'server',\n })\n }\n\n disconnect() {\n this.document?.removeDirectConnection()\n this.document = null\n }\n}\n","import { createServer, IncomingMessage, Server as HTTPServer } from 'http'\nimport { URLSearchParams } from 'url'\nimport { ListenOptions } from 'net'\nimport * as decoding from 'lib0/decoding'\nimport WebSocket, { AddressInfo, WebSocketServer } from 'ws'\nimport { Doc, encodeStateAsUpdate, applyUpdate } from 'yjs'\nimport { v4 as uuid } from 'uuid'\nimport kleur from 'kleur'\nimport {\n ResetConnection,\n Unauthorized,\n Forbidden,\n awarenessStatesToArray,\n WsReadyStates,\n} from '@hocuspocus/common'\nimport meta from '../package.json' assert {type: 'json'}\nimport { IncomingMessage as SocketIncomingMessage } from './IncomingMessage.js'\nimport {\n MessageType,\n Configuration,\n ConnectionConfiguration,\n HookName,\n AwarenessUpdate,\n HookPayload,\n beforeHandleMessagePayload,\n beforeBroadcastStatelessPayload,\n onListenPayload,\n onStoreDocumentPayload,\n} from './types.js'\nimport Document from './Document.js'\nimport Connection from './Connection.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { Debugger } from './Debugger.js'\nimport { DirectConnection } from './DirectConnection.js'\n\nexport const defaultConfiguration = {\n name: null,\n port: 80,\n address: '0.0.0.0',\n timeout: 30000,\n debounce: 2000,\n maxDebounce: 10000,\n quiet: false,\n yDocOptions: {\n gc: true,\n gcFilter: () => true,\n },\n}\n\n/**\n * Hocuspocus Server\n */\nexport class Hocuspocus {\n configuration: Configuration = {\n ...defaultConfiguration,\n extensions: [],\n onConfigure: () => new Promise(r => r(null)),\n onListen: () => new Promise(r => r(null)),\n onUpgrade: () => new Promise(r => r(null)),\n onConnect: () => new Promise(r => r(null)),\n connected: () => new Promise(r => r(null)),\n beforeHandleMessage: () => new Promise(r => r(null)),\n beforeBroadcastStateless: () => new Promise(r => r(null)),\n onStateless: () => new Promise(r => r(null)),\n onChange: () => new Promise(r => r(null)),\n onLoadDocument: () => new Promise(r => r(null)),\n onStoreDocument: () => new Promise(r => r(null)),\n afterStoreDocument: () => new Promise(r => r(null)),\n onAwarenessUpdate: () => new Promise(r => r(null)),\n onRequest: () => new Promise(r => r(null)),\n onDisconnect: () => new Promise(r => r(null)),\n onDestroy: () => new Promise(r => r(null)),\n }\n\n documents: Map = new Map()\n\n httpServer?: HTTPServer\n\n webSocketServer?: WebSocketServer\n\n debugger = new Debugger()\n\n constructor(configuration?: Partial) {\n if (configuration) {\n this.configure(configuration)\n }\n }\n\n /**\n * Configure the server\n */\n configure(configuration: Partial): Hocuspocus {\n this.configuration = {\n ...this.configuration,\n ...configuration,\n }\n\n this.configuration.extensions.sort((a, b) => {\n const one = typeof a.priority === 'undefined' ? 100 : a.priority\n const two = typeof b.priority === 'undefined' ? 100 : b.priority\n\n if (one > two) {\n return -1\n }\n\n if (one < two) {\n return 1\n }\n\n return 0\n })\n\n this.configuration.extensions.push({\n onConfigure: this.configuration.onConfigure,\n onListen: this.configuration.onListen,\n onUpgrade: this.configuration.onUpgrade,\n onConnect: this.configuration.onConnect,\n connected: this.configuration.connected,\n onAuthenticate: this.configuration.onAuthenticate,\n onLoadDocument: this.configuration.onLoadDocument,\n beforeHandleMessage: this.configuration.beforeHandleMessage,\n beforeBroadcastStateless: this.configuration.beforeBroadcastStateless,\n onStateless: this.configuration.onStateless,\n onChange: this.configuration.onChange,\n onStoreDocument: this.configuration.onStoreDocument,\n afterStoreDocument: this.configuration.afterStoreDocument,\n onAwarenessUpdate: this.configuration.onAwarenessUpdate,\n onRequest: this.configuration.onRequest,\n onDisconnect: this.configuration.onDisconnect,\n onDestroy: this.configuration.onDestroy,\n })\n\n this.hooks('onConfigure', {\n configuration: this.configuration,\n version: meta.version,\n instance: this,\n })\n\n return this\n }\n\n get requiresAuthentication(): boolean {\n return !!this.configuration.extensions.find(extension => {\n return extension.onAuthenticate !== undefined\n })\n }\n\n /**\n * Start the server\n */\n async listen(\n portOrCallback: number | ((data: onListenPayload) => Promise) | null = null,\n callback: any = null,\n ): Promise {\n if (typeof portOrCallback === 'number') {\n this.configuration.port = portOrCallback\n }\n\n if (typeof portOrCallback === 'function') {\n this.configuration.extensions.push({\n onListen: portOrCallback,\n })\n }\n\n if (typeof callback === 'function') {\n this.configuration.extensions.push({\n onListen: callback,\n })\n }\n\n const webSocketServer = new WebSocketServer({ noServer: true })\n\n webSocketServer.on('connection', async (incoming: WebSocket, request: IncomingMessage) => {\n\n incoming.on('error', error => {\n /**\n * Handle a ws instance error, which is required to prevent\n * the server from crashing when one happens\n * See https://github.com/websockets/ws/issues/1777#issuecomment-660803472\n * @private\n */\n this.debugger.log('Error emitted from webSocket instance:')\n this.debugger.log(error)\n })\n\n this.handleConnection(incoming, request)\n })\n\n const server = createServer((request, response) => {\n this.hooks('onRequest', { request, response, instance: this })\n .then(() => {\n // default response if all prior hooks don't interfere\n response.writeHead(200, { 'Content-Type': 'text/plain' })\n response.end('OK')\n })\n .catch(error => {\n // if a hook rejects and the error is empty, do nothing\n // this is only meant to prevent later hooks and the\n // default handler to do something. if a error is present\n // just rethrow it\n if (error) {\n throw error\n }\n })\n })\n\n server.on('upgrade', (request, socket, head) => {\n this.hooks('onUpgrade', {\n request,\n socket,\n head,\n instance: this,\n })\n .then(() => {\n // let the default websocket server handle the connection if\n // prior hooks don't interfere\n webSocketServer.handleUpgrade(request, socket, head, ws => {\n webSocketServer.emit('connection', ws, request)\n })\n })\n .catch(error => {\n // if a hook rejects and the error is empty, do nothing\n // this is only meant to prevent later hooks and the\n // default handler to do something. if a error is present\n // just rethrow it\n if (error) {\n throw error\n }\n })\n })\n\n this.httpServer = server\n this.webSocketServer = webSocketServer\n\n return new Promise((resolve: Function, reject: Function) => {\n server.listen({\n port: this.configuration.port,\n host: this.configuration.address,\n } as ListenOptions, () => {\n if (!this.configuration.quiet && process.env.NODE_ENV !== 'testing') {\n this.showStartScreen()\n }\n\n const onListenPayload = {\n instance: this,\n configuration: this.configuration,\n port: this.address.port,\n }\n\n this.hooks('onListen', onListenPayload)\n .then(() => resolve(this))\n .catch(error => reject(error))\n })\n })\n }\n\n get address(): AddressInfo {\n return (this.httpServer?.address() || {\n port: this.configuration.port,\n address: this.configuration.address,\n family: 'IPv4',\n }) as AddressInfo\n }\n\n get URL(): string {\n return `${this.configuration.address}:${this.address.port}`\n }\n\n get webSocketURL(): string {\n return `ws://${this.URL}`\n }\n\n get httpURL(): string {\n return `http://${this.URL}`\n }\n\n private showStartScreen() {\n const name = this.configuration.name ? ` (${this.configuration.name})` : ''\n\n console.log()\n console.log(` ${kleur.cyan(`Hocuspocus v${meta.version}${name}`)}${kleur.green(' running at:')}`)\n console.log()\n console.log(` > HTTP: ${kleur.cyan(`${this.httpURL}`)}`)\n console.log(` > WebSocket: ${this.webSocketURL}`)\n\n const extensions = this.configuration?.extensions.map(extension => {\n return extension.constructor?.name\n })\n .filter(name => name)\n .filter(name => name !== 'Object')\n\n if (!extensions.length) {\n return\n }\n\n console.log()\n console.log(' Extensions:')\n\n extensions\n .forEach(name => {\n console.log(` - ${name}`)\n })\n\n console.log()\n console.log(` ${kleur.green('Ready.')}`)\n console.log()\n }\n\n /**\n * Get the total number of active documents\n */\n getDocumentsCount(): number {\n return this.documents.size\n }\n\n /**\n * Get the total number of active connections\n */\n getConnectionsCount(): number {\n return Array.from(this.documents.values()).reduce((acc, document) => {\n acc += document.getConnectionsCount()\n return acc\n }, 0)\n }\n\n /**\n * Force close one or more connections\n */\n closeConnections(documentName?: string) {\n // Iterate through all connections for all documents\n // and invoke their close method, which is a graceful\n // disconnect wrapper around the underlying websocket.close\n this.documents.forEach((document: Document) => {\n // If a documentName was specified, bail if it doesnt match\n if (documentName && document.name !== documentName) {\n return\n }\n\n document.connections.forEach(({ connection }) => {\n connection.close(ResetConnection)\n })\n })\n }\n\n /**\n * Destroy the server\n */\n async destroy(): Promise {\n this.httpServer?.close()\n\n try {\n this.webSocketServer?.close()\n this.webSocketServer?.clients.forEach(client => {\n client.terminate()\n })\n } catch (error) {\n console.error(error)\n //\n }\n\n this.debugger.flush()\n\n await this.hooks('onDestroy', { instance: this })\n }\n\n /**\n * The `handleConnection` method receives incoming WebSocket connections,\n * runs all hooks:\n *\n * - onConnect for all connections\n * - onAuthenticate only if required\n *\n * … and if nothings fails it’ll fully establish the connection and\n * load the Document then.\n */\n handleConnection(incoming: WebSocket, request: IncomingMessage, context: any = null): void {\n // Make sure to close an idle connection after a while.\n const closeIdleConnection = setTimeout(() => {\n incoming.close(Unauthorized.code, Unauthorized.reason)\n }, this.configuration.timeout)\n\n // Every new connection gets a unique identifier.\n const socketId = uuid()\n\n // To override settings for specific connections, we’ll\n // keep track of a few things in the `ConnectionConfiguration`.\n const connection: ConnectionConfiguration = {\n readOnly: false,\n requiresAuthentication: this.requiresAuthentication,\n isAuthenticated: false,\n }\n\n // The `onConnect` and `onAuthenticate` hooks need some context\n // to decide who’s connecting, so let’s put it together:\n const hookPayload = {\n instance: this,\n request,\n requestHeaders: request.headers,\n requestParameters: Hocuspocus.getParameters(request),\n socketId,\n connection,\n }\n\n // this map indicates whether a `Connection` instance has already taken over for incoming message for the key (i.e. documentName)\n const documentConnections: Record = {}\n\n // While the connection will be establishing messages will\n // be queued and handled later.\n const incomingMessageQueue: Record = {}\n\n // While the connection is establishing\n const connectionEstablishing: Record = {}\n\n // Once all hooks are run, we’ll fully establish the connection:\n const setUpNewConnection = async (documentName: string) => {\n // Not an idle connection anymore, no need to close it then.\n clearTimeout(closeIdleConnection)\n\n // If no hook interrupts, create a document and connection\n const document = await this.createDocument(documentName, request, socketId, connection, context)\n const instance = this.createConnection(incoming, request, document, socketId, connection.readOnly, context)\n\n instance.onClose((document, event) => {\n delete documentConnections[documentName]\n delete incomingMessageQueue[documentName]\n delete connectionEstablishing[documentName]\n\n if (Object.keys(documentConnections).length === 0) {\n instance.webSocket.close(event?.code, event?.reason) // TODO: Move this to Hocuspocus connection handler\n }\n })\n\n documentConnections[documentName] = true\n\n // There’s no need to queue messages anymore.\n // Let’s work through queued messages.\n incomingMessageQueue[documentName].forEach(input => {\n incoming.emit('message', input)\n })\n\n this.hooks('connected', {\n ...hookPayload,\n documentName,\n context,\n connectionInstance: instance,\n })\n }\n\n // This listener handles authentication messages and queues everything else.\n const handleQueueingMessage = (data: Uint8Array) => {\n try {\n const tmpMsg = new SocketIncomingMessage(data)\n\n const documentName = decoding.readVarString(tmpMsg.decoder)\n const type = decoding.readVarUint(tmpMsg.decoder)\n\n // Okay, we’ve got the authentication message we’re waiting for:\n if (type === MessageType.Auth && !connectionEstablishing[documentName]) {\n connectionEstablishing[documentName] = true\n\n // The 2nd integer contains the submessage type\n // which will always be authentication when sent from client -> server\n decoding.readVarUint(tmpMsg.decoder)\n const token = decoding.readVarString(tmpMsg.decoder)\n\n this.debugger.log({\n direction: 'in',\n type,\n category: 'Token',\n })\n\n this.hooks('onAuthenticate', {\n token,\n ...hookPayload,\n documentName,\n }, (contextAdditions: any) => {\n // Hooks are allowed to give us even more context and we’ll merge everything together.\n // We’ll pass the context to other hooks then.\n context = { ...context, ...contextAdditions }\n })\n .then(() => {\n // All `onAuthenticate` hooks passed.\n connection.isAuthenticated = true\n\n // Let the client know that authentication was successful.\n const message = new OutgoingMessage(documentName).writeAuthenticated(connection.readOnly)\n\n this.debugger.log({\n direction: 'out',\n type: message.type,\n category: message.category,\n })\n\n incoming.send(message.toUint8Array())\n })\n .then(() => {\n // Time to actually establish the connection.\n return setUpNewConnection(documentName)\n })\n .catch((error = Forbidden) => {\n const message = new OutgoingMessage(documentName).writePermissionDenied(error.reason ?? 'permission-denied')\n\n this.debugger.log({\n direction: 'out',\n type: message.type,\n category: message.category,\n })\n\n // Ensure that the permission denied message is sent before the\n // connection is closed\n incoming.send(message.toUint8Array(), () => {\n if (Object.keys(documentConnections).length === 0) {\n try {\n incoming.close(error.code ?? Forbidden.code, error.reason ?? Forbidden.reason)\n } catch (closeError) {\n // catch is needed in case invalid error code is returned by hook (that would fail sending the close message)\n console.error(closeError)\n incoming.close(Forbidden.code, Forbidden.reason)\n }\n }\n })\n })\n } else {\n incomingMessageQueue[documentName].push(data)\n }\n\n // Catch errors due to failed decoding of data\n } catch (error) {\n console.error(error)\n incoming.close(Unauthorized.code, Unauthorized.reason)\n }\n }\n\n const messageHandler = (data: Uint8Array) => {\n try {\n const tmpMsg = new SocketIncomingMessage(data)\n\n const documentName = decoding.readVarString(tmpMsg.decoder)\n\n if (documentConnections[documentName] === true) {\n // we already have a `Connection` set up for this document\n return\n }\n\n // if this is the first message, trigger onConnect & check if we can start the connection (only if no auth is required)\n if (incomingMessageQueue[documentName] === undefined) {\n incomingMessageQueue[documentName] = []\n\n this.hooks('onConnect', { ...hookPayload, documentName }, (contextAdditions: any) => {\n // merge context from all hooks\n context = { ...context, ...contextAdditions }\n })\n .then(() => {\n // Authentication is required, we’ll need to wait for the Authentication message.\n if (connection.requiresAuthentication || connectionEstablishing[documentName]) {\n return\n }\n connectionEstablishing[documentName] = true\n\n return setUpNewConnection(documentName)\n })\n .catch((error = Forbidden) => {\n // if a hook interrupts, close the websocket connection\n try {\n incoming.close(error.code ?? Forbidden.code, error.reason ?? Forbidden.reason)\n } catch (closeError) {\n // catch is needed in case invalid error code is returned by hook (that would fail sending the close message)\n console.error(closeError)\n incoming.close(Unauthorized.code, Unauthorized.reason)\n }\n })\n }\n\n handleQueueingMessage(data)\n } catch (closeError) {\n // catch is needed in case an invalid payload crashes the parsing of the Uint8Array\n console.error(closeError)\n incoming.close(Unauthorized.code, Unauthorized.reason)\n }\n\n }\n\n incoming.on('message', messageHandler)\n }\n\n /**\n * Handle update of the given document\n */\n private handleDocumentUpdate(document: Document, connection: Connection | undefined, update: Uint8Array, request?: IncomingMessage): void {\n const hookPayload = {\n instance: this,\n clientsCount: document.getConnectionsCount(),\n context: connection?.context || {},\n document,\n documentName: document.name,\n requestHeaders: request?.headers ?? {},\n requestParameters: Hocuspocus.getParameters(request),\n socketId: connection?.socketId ?? '',\n update,\n }\n\n this.hooks('onChange', hookPayload).catch(error => {\n throw error\n })\n\n // If the update was received through other ways than the\n // WebSocket connection, we don’t need to feel responsible for\n // storing the content.\n if (!connection) {\n return\n }\n\n this.debounce(`onStoreDocument-${document.name}`, () => {\n this.storeDocumentHooks(document, hookPayload)\n })\n }\n\n timers: Map = new Map()\n\n /**\n * debounce the given function, using the given identifier\n */\n debounce(id: string, func: Function, immediately = false) {\n const old = this.timers.get(id)\n const start = old?.start || Date.now()\n\n const run = () => {\n this.timers.delete(id)\n func()\n }\n\n if (old?.timeout) {\n clearTimeout(old.timeout)\n }\n\n if (immediately) {\n return run()\n }\n\n if (Date.now() - start >= this.configuration.maxDebounce) {\n return run()\n }\n\n this.timers.set(id, {\n start,\n timeout: setTimeout(run, this.configuration.debounce),\n })\n }\n\n /**\n * Create a new document by the given request\n */\n private async createDocument(documentName: string, request: Partial>, socketId: string, connection: ConnectionConfiguration, context?: any): Promise {\n if (this.documents.has(documentName)) {\n const document = this.documents.get(documentName)\n\n if (document) {\n return document\n }\n }\n\n const document = new Document(documentName, this.debugger, this.configuration.yDocOptions)\n this.documents.set(documentName, document)\n\n const hookPayload = {\n instance: this,\n context,\n connection,\n document,\n documentName,\n socketId,\n requestHeaders: request.headers,\n requestParameters: Hocuspocus.getParameters(request),\n }\n\n try {\n await this.hooks('onLoadDocument', hookPayload, (loadedDocument: Doc | undefined) => {\n // if a hook returns a Y-Doc, encode the document state as update\n // and apply it to the newly created document\n // Note: instanceof doesn't work, because Doc !== Doc for some reason I don't understand\n if (\n loadedDocument?.constructor.name === 'Document'\n || loadedDocument?.constructor.name === 'Doc'\n ) {\n applyUpdate(document, encodeStateAsUpdate(loadedDocument))\n }\n })\n } catch (e) {\n this.closeConnections(documentName)\n this.documents.delete(documentName)\n throw e\n }\n\n document.isLoading = false\n await this.hooks('afterLoadDocument', hookPayload)\n\n document.onUpdate((document: Document, connection: Connection, update: Uint8Array) => {\n this.handleDocumentUpdate(document, connection, update, connection?.request)\n })\n\n document.beforeBroadcastStateless((document: Document, stateless: string) => {\n const hookPayload: beforeBroadcastStatelessPayload = {\n document,\n documentName: document.name,\n payload: stateless,\n }\n\n this.hooks('beforeBroadcastStateless', hookPayload)\n })\n\n document.awareness.on('update', (update: AwarenessUpdate) => {\n this.hooks('onAwarenessUpdate', {\n ...hookPayload,\n ...update,\n awareness: document.awareness,\n states: awarenessStatesToArray(document.awareness.getStates()),\n })\n })\n\n return document\n }\n\n /**\n * Create a new connection by the given request and document\n */\n private createConnection(connection: WebSocket, request: IncomingMessage, document: Document, socketId: string, readOnly = false, context?: any): Connection {\n const instance = new Connection(\n connection,\n request,\n document,\n this.configuration.timeout,\n socketId,\n context,\n readOnly,\n this.debugger,\n )\n\n instance.onClose(document => {\n const hookPayload = {\n instance: this,\n clientsCount: document.getConnectionsCount(),\n context,\n document,\n socketId,\n documentName: document.name,\n requestHeaders: request.headers,\n requestParameters: Hocuspocus.getParameters(request),\n }\n\n this.hooks('onDisconnect', hookPayload).then(() => {\n // Check if there are still no connections to the document, as these hooks\n // may take some time to resolve (e.g. database queries). If a\n // new connection were to come in during that time it would rely on the\n // document in the map that we remove now.\n if (document.getConnectionsCount() > 0) {\n return\n }\n\n // If it’s the last connection, we need to make sure to store the\n // document. Use the debounce helper, to clear running timers,\n // but make it run immediately (`true`).\n // Only run this if the document has finished loading earlier (i.e. not to persist the empty\n // ydoc if the onLoadDocument hook returned an error)\n if (!document.isLoading) {\n this.debounce(`onStoreDocument-${document.name}`, () => {\n this.storeDocumentHooks(document, hookPayload)\n }, true)\n\n } else {\n // Remove document from memory immediately\n this.documents.delete(document.name)\n document.destroy()\n }\n })\n\n })\n\n instance.onStatelessCallback(payload => {\n return this.hooks('onStateless', payload)\n .catch(error => {\n if (error?.message) {\n throw error\n }\n })\n })\n\n instance.beforeHandleMessage((connection, update) => {\n const hookPayload: beforeHandleMessagePayload = {\n instance: this,\n clientsCount: document.getConnectionsCount(),\n context,\n document,\n socketId,\n connection,\n documentName: document.name,\n requestHeaders: request.headers,\n requestParameters: Hocuspocus.getParameters(request),\n update,\n }\n\n return this.hooks('beforeHandleMessage', hookPayload)\n })\n\n // If the WebSocket has already disconnected (wow, that was fast) – then\n // immediately call close to cleanup the connection and document in memory.\n if (\n connection.readyState === WsReadyStates.Closing\n || connection.readyState === WsReadyStates.Closed\n ) {\n instance.close()\n }\n\n return instance\n }\n\n storeDocumentHooks(document: Document, hookPayload: onStoreDocumentPayload) {\n this.hooks('onStoreDocument', hookPayload)\n .catch(error => {\n if (error?.message) {\n throw error\n }\n })\n .then(() => {\n this.hooks('afterStoreDocument', hookPayload).then(() => {\n // Remove document from memory.\n\n if (document.getConnectionsCount() > 0) {\n return\n }\n\n this.documents.delete(document.name)\n document.destroy()\n })\n })\n }\n\n /**\n * Run the given hook on all configured extensions.\n * Runs the given callback after each hook.\n */\n hooks(name: HookName, payload: HookPayload, callback: Function | null = null): Promise {\n const { extensions } = this.configuration\n\n // create a new `thenable` chain\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve\n let chain = Promise.resolve()\n\n extensions\n // get me all extensions which have the given hook\n .filter(extension => typeof extension[name] === 'function')\n // run through all the configured hooks\n .forEach(extension => {\n chain = chain\n .then(() => (extension[name] as any)?.(payload))\n .catch(error => {\n // make sure to log error messages\n if (error?.message) {\n console.error(`[${name}]`, error.message)\n }\n\n throw error\n })\n\n if (callback) {\n chain = chain.then((...args: any[]) => callback(...args))\n }\n })\n\n return chain\n }\n\n /**\n * Get parameters by the given request\n */\n private static getParameters(request?: Pick): URLSearchParams {\n const query = request?.url?.split('?') || []\n return new URLSearchParams(query[1] ? query[1] : '')\n }\n\n enableDebugging() {\n this.debugger.enable()\n }\n\n enableMessageLogging() {\n this.debugger.enable()\n this.debugger.verbose()\n }\n\n disableLogging() {\n this.debugger.quiet()\n }\n\n disableDebugging() {\n this.debugger.disable()\n }\n\n flushMessageLogs() {\n this.debugger.flush()\n\n return this\n }\n\n getMessageLogs() {\n return this.debugger.get()?.logs\n }\n\n async openDirectConnection(documentName: string, context?: any): Promise {\n const connectionConfig: ConnectionConfiguration = {\n isAuthenticated: true,\n readOnly: false,\n requiresAuthentication: true,\n }\n\n const document: Document = await this.createDocument(\n documentName,\n {}, // direct connection has no request params\n uuid(),\n connectionConfig,\n context,\n )\n\n return new DirectConnection(document, this, context)\n }\n}\n\nexport const Server = new Hocuspocus()\n"],"names":["create","length","object.length","object.hasProperty","map.create","string.fromCamelCase","conditions.undefinedToNull","storage.varStorage","f.isOneOf","buffer.createUint8ArrayViewFromArrayBuffer","binary.BITS7","binary.BIT8","math.floor","string.utf8TextEncoder","string.encodeUtf8","math.min","math.max","error.create","number.MAX_SAFE_INTEGER","string.utf8TextDecoder","encoding.writeVarUint","Y","encoding.writeVarUint8Array","decoding.readVarUint8Array","map.setIfUndefined","set.create","array.from","time.getUnixTime","f.equalityDeep","encoding.createEncoder","encoding.writeVarString","encoding.toUint8Array","decoding.createDecoder","decoding.readVarUint","decoding.readVarString","MessageType","writeAuthenticated","writePermissionDenied","AsyncLock","WsReadyStates","ConnectionTimeout","Forbidden","Doc","applyUpdate","encodeStateAsUpdate","URLSearchParams","WebSocketServer","createServer","kleur","ResetConnection","Unauthorized","uuid","SocketIncomingMessage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IAED,oBAAoB,GAAA;AAClB,QAAA,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAA;AACtB,QAAA,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAA;KACxB;IAED,cAAc,GAAA;AACZ,QAAA,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAA;KACtB;IAED,gBAAgB,GAAA;AACd,QAAA,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAA;KACxB;IAED,gBAAgB,GAAA;AACd,QAAA,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAA;AAErB,QAAA,OAAO,IAAI,CAAA;KACZ;IAED,cAAc,GAAA;;QACZ,OAAO,CAAA,EAAA,GAAA,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,MAAE,IAAA,IAAA,EAAA,KAAA,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,IAAI,CAAA;KACjC;AAED,IAAA,MAAM,oBAAoB,CAAC,YAAoB,EAAE,OAAa,EAAA;AAC5D,QAAA,MAAM,gBAAgB,GAA4B;AAChD,YAAA,eAAe,EAAE,IAAI;AACrB,YAAA,QAAQ,EAAE,KAAK;AACf,YAAA,sBAAsB,EAAE,IAAI;SAC7B,CAAA;QAED,MAAM,QAAQ,GAAa,MAAM,IAAI,CAAC,cAAc,CAClD,YAAY,EACZ,EAAE;AACF,QAAAM,OAAI,EAAE,EACN,gBAAgB,EAChB,OAAO,CACR,CAAA;QAED,OAAO,IAAI,gBAAgB,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAA;KACrD;AACF,CAAA;AAEY,MAAA,MAAM,GAAG,IAAI,UAAU;;;;;;;;;;;;"} -\ No newline at end of file -+{"version":3,"file":"hocuspocus-server.cjs","sources":["../../../node_modules/lib0/set.js","../../../node_modules/lib0/array.js","../../../node_modules/lib0/string.js","../../../node_modules/lib0/map.js","../../../node_modules/lib0/conditions.js","../../../node_modules/lib0/storage.js","../../../node_modules/lib0/object.js","../../../node_modules/lib0/function.js","../../../node_modules/lib0/environment.js","../../../node_modules/lib0/math.js","../../../node_modules/lib0/binary.js","../../../node_modules/lib0/number.js","../../../node_modules/lib0/encoding.js","../../../node_modules/lib0/buffer.js","../../../node_modules/lib0/error.js","../../../node_modules/lib0/decoding.js","../src/IncomingMessage.ts","../../../node_modules/lib0/time.js","../../../node_modules/lib0/observable.js","../../../node_modules/y-protocols/awareness.js","../../../node_modules/y-protocols/sync.js","../src/types.ts","../src/OutgoingMessage.ts","../src/MessageReceiver.ts","../src/Connection.ts","../src/Debugger.ts","../../../node_modules/lib0/mutex.js","../src/Document.ts","../src/util/getParameters.ts","../src/ClientConnection.ts","../src/DirectConnection.ts","../src/Hocuspocus.ts"],"sourcesContent":["/**\n * Utility module to work with sets.\n *\n * @module set\n */\n\nexport const create = () => new Set()\n\n/**\n * @template T\n * @param {Set} set\n * @return {Array}\n */\nexport const toArray = set => Array.from(set)\n\n/**\n * @template T\n * @param {Set} set\n * @return {T}\n */\nexport const first = set =>\n set.values().next().value || undefined\n\n/**\n * @template T\n * @param {Iterable} entries\n * @return {Set}\n */\nexport const from = entries => new Set(entries)\n","/**\n * Utility module to work with Arrays.\n *\n * @module array\n */\n\nimport * as set from './set.js'\n\n/**\n * Return the last element of an array. The element must exist\n *\n * @template L\n * @param {ArrayLike} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array}\n */\nexport const create = () => /** @type {Array} */ ([])\n\n/**\n * @template D\n * @param {Array} a\n * @return {Array}\n */\nexport const copy = a => /** @type {Array} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array} dest\n * @param {Array} src\n */\nexport const appendTo = (dest, src) => {\n for (let i = 0; i < src.length; i++) {\n dest.push(src[i])\n }\n}\n\n/**\n * Transforms something array-like to an actual Array.\n *\n * @function\n * @template T\n * @param {ArrayLike|Iterable} arraylike\n * @return {T}\n */\nexport const from = Array.from\n\n/**\n * True iff condition holds on every element in the Array.\n *\n * @function\n * @template ITEM\n * @template {ArrayLike} ARR\n *\n * @param {ARR} arr\n * @param {function(ITEM, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const every = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (!f(arr[i], i, arr)) {\n return false\n }\n }\n return true\n}\n\n/**\n * True iff condition holds on some element in the Array.\n *\n * @function\n * @template S\n * @template {ArrayLike} ARR\n * @param {ARR} arr\n * @param {function(S, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const some = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (f(arr[i], i, arr)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @template ELEM\n *\n * @param {ArrayLike} a\n * @param {ArrayLike} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a.length === b.length && every(a, (item, index) => item === b[index])\n\n/**\n * @template ELEM\n * @param {Array>} arr\n * @return {Array}\n */\nexport const flatten = arr => fold(arr, /** @type {Array} */ ([]), (acc, val) => acc.concat(val))\n\n/**\n * @template T\n * @param {number} len\n * @param {function(number, Array):T} f\n * @return {Array}\n */\nexport const unfold = (len, f) => {\n const array = new Array(len)\n for (let i = 0; i < len; i++) {\n array[i] = f(i, array)\n }\n return array\n}\n\n/**\n * @template T\n * @template RESULT\n * @param {Array} arr\n * @param {RESULT} seed\n * @param {function(RESULT, T, number):RESULT} folder\n */\nexport const fold = (arr, seed, folder) => arr.reduce(folder, seed)\n\nexport const isArray = Array.isArray\n\n/**\n * @template T\n * @param {Array} arr\n * @return {Array}\n */\nexport const unique = arr => from(set.from(arr))\n\n/**\n * @template T\n * @template M\n * @param {ArrayLike} arr\n * @param {function(T):M} mapper\n * @return {Array}\n */\nexport const uniqueBy = (arr, mapper) => {\n /**\n * @type {Set}\n */\n const happened = set.create()\n /**\n * @type {Array}\n */\n const result = []\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i]\n const mapped = mapper(el)\n if (!happened.has(mapped)) {\n happened.add(mapped)\n result.push(el)\n }\n }\n return result\n}\n","import * as array from './array.js'\n\n/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * The largest utf16 character.\n * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8)\n */\nexport const MAX_UTF16_CHARACTER = fromCharCode(65535)\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* c8 ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* c8 ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* c8 ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* c8 ignore start */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* c8 ignore next */\n utf8TextDecoder = null\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* c8 ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n\n/**\n * @param {string} source\n * @param {number} n\n */\nexport const repeat = (source, n) => array.unfold(n, () => source).join('')\n","/**\n * Utility module to work with key-value stores.\n *\n * @module map\n */\n\n/**\n * Creates a new Map instance.\n *\n * @function\n * @return {Map}\n *\n * @function\n */\nexport const create = () => new Map()\n\n/**\n * Copy a Map object into a fresh Map object.\n *\n * @function\n * @template X,Y\n * @param {Map} m\n * @return {Map}\n */\nexport const copy = m => {\n const r = create()\n m.forEach((v, k) => { r.set(k, v) })\n return r\n}\n\n/**\n * Get map property. Create T if property is undefined and set T on map.\n *\n * ```js\n * const listeners = map.setIfUndefined(events, 'eventName', set.create)\n * listeners.add(listener)\n * ```\n *\n * @function\n * @template V,K\n * @template {Map} MAP\n * @param {MAP} map\n * @param {K} key\n * @param {function():V} createT\n * @return {V}\n */\nexport const setIfUndefined = (map, key, createT) => {\n let set = map.get(key)\n if (set === undefined) {\n map.set(key, set = createT())\n }\n return set\n}\n\n/**\n * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function.\n *\n * @function\n * @template K\n * @template V\n * @template R\n * @param {Map} m\n * @param {function(V,K):R} f\n * @return {Array}\n */\nexport const map = (m, f) => {\n const res = []\n for (const [key, value] of m) {\n res.push(f(value, key))\n }\n return res\n}\n\n/**\n * Tests whether any key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @todo should rename to some - similarly to Array.some\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const any = (m, f) => {\n for (const [key, value] of m) {\n if (f(value, key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * Tests whether all key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const all = (m, f) => {\n for (const [key, value] of m) {\n if (!f(value, key)) {\n return false\n }\n }\n return true\n}\n","/**\n * Often used conditions.\n *\n * @module conditions\n */\n\n/**\n * @template T\n * @param {T|null|undefined} v\n * @return {T|null}\n */\n/* c8 ignore next */\nexport const undefinedToNull = v => v === undefined ? null : v\n","/* eslint-env browser */\n\n/**\n * Isomorphic variable storage.\n *\n * Uses LocalStorage in the browser and falls back to in-memory storage.\n *\n * @module storage\n */\n\n/* c8 ignore start */\nclass VarStoragePolyfill {\n constructor () {\n this.map = new Map()\n }\n\n /**\n * @param {string} key\n * @param {any} newValue\n */\n setItem (key, newValue) {\n this.map.set(key, newValue)\n }\n\n /**\n * @param {string} key\n */\n getItem (key) {\n return this.map.get(key)\n }\n}\n/* c8 ignore stop */\n\n/**\n * @type {any}\n */\nlet _localStorage = new VarStoragePolyfill()\nlet usePolyfill = true\n\n/* c8 ignore start */\ntry {\n // if the same-origin rule is violated, accessing localStorage might thrown an error\n if (typeof localStorage !== 'undefined') {\n _localStorage = localStorage\n usePolyfill = false\n }\n} catch (e) { }\n/* c8 ignore stop */\n\n/**\n * This is basically localStorage in browser, or a polyfill in nodejs\n */\n/* c8 ignore next */\nexport const varStorage = _localStorage\n\n/**\n * A polyfill for `addEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler))\n\n/**\n * A polyfill for `removeEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler))\n","/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object} obj\n */\nexport const keys = Object.keys\n\n/**\n * @template V\n * @param {{[k:string]:V}} obj\n * @param {function(V,string):any} f\n */\nexport const forEach = (obj, f) => {\n for (const key in obj) {\n f(obj[key], key)\n }\n}\n\n/**\n * @todo implement mapToArray & map\n *\n * @template R\n * @param {Object} obj\n * @param {function(any,string):R} f\n * @return {Array}\n */\nexport const map = (obj, f) => {\n const results = []\n for (const key in obj) {\n results.push(f(obj[key], key))\n }\n return results\n}\n\n/**\n * @param {Object} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n for (const key in obj) {\n if (f(obj[key], key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {Object|undefined} obj\n */\nexport const isEmpty = obj => {\n for (const _k in obj) {\n return false\n }\n return true\n}\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n for (const key in obj) {\n if (!f(obj[key], key)) {\n return false\n }\n }\n return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object} a\n * @param {Object} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val))\n","/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array} fs\n * @param {Array} args\n */\nexport const callAll = (fs, args, i = 0) => {\n try {\n for (; i < fs.length; i++) {\n fs[i](...args)\n }\n } finally {\n if (i < fs.length) {\n callAll(fs, args, i + 1)\n }\n }\n}\n\nexport const nop = () => {}\n\n/**\n * @template T\n * @param {function():T} f\n * @return {T}\n */\nexport const apply = f => f()\n\n/**\n * @template A\n *\n * @param {A} a\n * @return {A}\n */\nexport const id = a => a\n\n/**\n * @template T\n *\n * @param {T} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equalityStrict = (a, b) => a === b\n\n/**\n * @template T\n *\n * @param {Array|object} a\n * @param {Array|object} b\n * @return {boolean}\n */\nexport const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((array.isArray(a) && array.equalFlat(a, /** @type {Array} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/* c8 ignore start */\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a == null || b == null) {\n return equalityStrict(a, b)\n }\n if (a.constructor !== b.constructor) {\n return false\n }\n if (a === b) {\n return true\n }\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n break\n }\n case Map: {\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n return false\n }\n }\n break\n }\n case Object:\n if (object.length(a) !== object.length(b)) {\n return false\n }\n for (const key in a) {\n if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n return false\n }\n }\n break\n case Array:\n if (a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!equalityDeep(a[i], b[i])) {\n return false\n }\n }\n break\n default:\n return false\n }\n return true\n}\n\n/**\n * @template V\n * @template {V} OPTS\n *\n * @param {V} value\n * @param {Array} options\n */\n// @ts-ignore\nexport const isOneOf = (value, options) => options.includes(value)\n/* c8 ignore stop */\n\nexport const isArray = array.isArray\n\n/**\n * @param {any} s\n * @return {s is String}\n */\nexport const isString = (s) => s && s.constructor === String\n\n/**\n * @param {any} n\n * @return {n is Number}\n */\nexport const isNumber = n => n != null && n.constructor === Number\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {any} n\n * @param {TYPE} T\n * @return {n is InstanceType}\n */\nexport const is = (n, T) => n && n.constructor === T\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {TYPE} T\n */\nexport const isTemplate = (T) =>\n /**\n * @param {any} n\n * @return {n is InstanceType}\n **/\n n => n && n.constructor === T\n","/**\n * Isomorphic module to work access the environment (query params, env variables).\n *\n * @module map\n */\n\nimport * as map from './map.js'\nimport * as string from './string.js'\nimport * as conditions from './conditions.js'\nimport * as storage from './storage.js'\nimport * as f from './function.js'\n\n/* c8 ignore next */\n// @ts-ignore\nexport const isNode = typeof process !== 'undefined' && process.release &&\n /node|io\\.js/.test(process.release.name)\n/* c8 ignore next */\nexport const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && !isNode\n/* c8 ignore next 3 */\nexport const isMac = typeof navigator !== 'undefined'\n ? /Mac/.test(navigator.platform)\n : false\n\n/**\n * @type {Map}\n */\nlet params\nconst args = []\n\n/* c8 ignore start */\nconst computeParams = () => {\n if (params === undefined) {\n if (isNode) {\n params = map.create()\n const pargs = process.argv\n let currParamName = null\n for (let i = 0; i < pargs.length; i++) {\n const parg = pargs[i]\n if (parg[0] === '-') {\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n currParamName = parg\n } else {\n if (currParamName !== null) {\n params.set(currParamName, parg)\n currParamName = null\n } else {\n args.push(parg)\n }\n }\n }\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n // in ReactNative for example this would not be true (unless connected to the Remote Debugger)\n } else if (typeof location === 'object') {\n params = map.create(); // eslint-disable-next-line no-undef\n (location.search || '?').slice(1).split('&').forEach((kv) => {\n if (kv.length !== 0) {\n const [key, value] = kv.split('=')\n params.set(`--${string.fromCamelCase(key, '-')}`, value)\n params.set(`-${string.fromCamelCase(key, '-')}`, value)\n }\n })\n } else {\n params = map.create()\n }\n }\n return params\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next */\nexport const hasParam = (name) => computeParams().has(name)\n\n/**\n * @param {string} name\n * @param {string} defaultVal\n * @return {string}\n */\n/* c8 ignore next 2 */\nexport const getParam = (name, defaultVal) =>\n computeParams().get(name) || defaultVal\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 4 */\nexport const getVariable = (name) =>\n isNode\n ? conditions.undefinedToNull(process.env[name.toUpperCase()])\n : conditions.undefinedToNull(storage.varStorage.getItem(name))\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 2 */\nexport const getConf = (name) =>\n computeParams().get('--' + name) || getVariable(name)\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next 2 */\nexport const hasConf = (name) =>\n hasParam('--' + name) || getVariable(name) !== null\n\n/* c8 ignore next */\nexport const production = hasConf('production')\n\n/* c8 ignore next 2 */\nconst forceColor = isNode &&\n f.isOneOf(process.env.FORCE_COLOR, ['true', '1', '2'])\n\n/* c8 ignore start */\nexport const supportsColor = !hasParam('no-colors') &&\n (!isNode || process.stdout.isTTY || forceColor) && (\n !isNode || hasParam('color') || forceColor ||\n getVariable('COLORTERM') !== null ||\n (getVariable('TERM') || '').includes('color')\n)\n/* c8 ignore stop */\n","/**\n * Common Math expressions.\n *\n * @module math\n */\n\nexport const floor = Math.floor\nexport const ceil = Math.ceil\nexport const abs = Math.abs\nexport const imul = Math.imul\nexport const round = Math.round\nexport const log10 = Math.log10\nexport const log2 = Math.log2\nexport const log = Math.log\nexport const sqrt = Math.sqrt\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The sum of a and b\n */\nexport const add = (a, b) => a + b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The smaller element of a and b\n */\nexport const min = (a, b) => a < b ? a : b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The bigger element of a and b\n */\nexport const max = (a, b) => a > b ? a : b\n\nexport const isNaN = Number.isNaN\n\nexport const pow = Math.pow\n/**\n * Base 10 exponential function. Returns the value of 10 raised to the power of pow.\n *\n * @param {number} exp\n * @return {number}\n */\nexport const exp10 = exp => Math.pow(10, exp)\n\nexport const sign = Math.sign\n\n/**\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\nexport const HIGHEST_INT32 = binary.BITS31\nexport const HIGHEST_UINT32 = binary.BITS32\n\n/* c8 ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n","/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\nimport * as string from './string.js'\nimport * as array from './array.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * @param {function(Encoder):void} f\n */\nexport const encode = (f) => {\n const encoder = createEncoder()\n f(encoder)\n return toUint8Array(encoder)\n}\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Check whether encoder is empty.\n *\n * @function\n * @param {Encoder} encoder\n * @return {boolean}\n */\nexport const hasContent = encoder => encoder.cpos > 0 || encoder.bufs.length > 0\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nexport const verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer. Max encodable integer is 2^53.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num = math.floor(num / 64) // shift >>> 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n}\n\n/**\n * A cache to store strings temporarily\n */\nconst _strBuffer = new Uint8Array(30000)\nconst _maxStrBSize = _strBuffer.length / 3\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringNative = (encoder, str) => {\n if (str.length < _maxStrBSize) {\n // We can encode the string into the existing buffer\n /* c8 ignore next */\n const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0\n writeVarUint(encoder, written)\n for (let i = 0; i < written; i++) {\n write(encoder, _strBuffer[i])\n }\n } else {\n writeVarUint8Array(encoder, string.encodeUtf8(str))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringPolyfill = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\n/* c8 ignore next */\nexport const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill\n\n/**\n * Write a string terminated by a special byte sequence. This is not very performant and is\n * generally discouraged. However, the resulting byte arrays are lexiographically ordered which\n * makes this a nice feature for databases.\n *\n * The string will be encoded using utf8 and then terminated and escaped using writeTerminatingUint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const writeTerminatedString = (encoder, str) =>\n writeTerminatedUint8Array(encoder, string.encodeUtf8(str))\n\n/**\n * Write a terminating Uint8Array. Note that this is not performant and is generally\n * discouraged. There are few situations when this is needed.\n *\n * We use 0x0 as a terminating character. 0x1 serves as an escape character for 0x0 and 0x1.\n *\n * Example: [0,1,2] is encoded to [1,0,1,1,2,0]. 0x0, and 0x1 needed to be escaped using 0x1. Then\n * the result is terminated using the 0x0 character.\n *\n * This is basically how many systems implement null terminated strings. However, we use an escape\n * character 0x1 to avoid issues and potenial attacks on our database (if this is used as a key\n * encoder for NoSql databases).\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} buf The string that is to be encoded.\n */\nexport const writeTerminatedUint8Array = (encoder, buf) => {\n for (let i = 0; i < buf.length; i++) {\n const b = buf[i]\n if (b === 0 || b === 1) {\n write(encoder, 1)\n }\n write(encoder, buf[i])\n }\n write(encoder, 0)\n}\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && math.abs(data) <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (array.isArray(data)) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n","/**\n * Utility functions to work with buffers (Uint8Array).\n *\n * @module buffer\n */\n\nimport * as string from './string.js'\nimport * as env from './environment.js'\nimport * as encoding from './encoding.js'\nimport * as decoding from './decoding.js'\n\n/**\n * @param {number} len\n */\nexport const createUint8ArrayFromLen = len => new Uint8Array(len)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n * @param {number} byteOffset\n * @param {number} length\n */\nexport const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n */\nexport const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer)\n\n/* c8 ignore start */\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Browser = bytes => {\n let s = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n s += string.fromCharCode(bytes[i])\n }\n // eslint-disable-next-line no-undef\n return btoa(s)\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')\n\n/* c8 ignore start */\n/**\n * @param {string} s\n * @return {Uint8Array}\n */\nconst fromBase64Browser = s => {\n // eslint-disable-next-line no-undef\n const a = atob(s)\n const bytes = createUint8ArrayFromLen(a.length)\n for (let i = 0; i < a.length; i++) {\n bytes[i] = a.charCodeAt(i)\n }\n return bytes\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} s\n */\nconst fromBase64Node = s => {\n const buf = Buffer.from(s, 'base64')\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n}\n\n/* c8 ignore next */\nexport const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node\n\n/* c8 ignore next */\nexport const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node\n\n/**\n * Copy the content of an Uint8Array view to a new ArrayBuffer.\n *\n * @param {Uint8Array} uint8Array\n * @return {Uint8Array}\n */\nexport const copyUint8Array = uint8Array => {\n const newBuf = createUint8ArrayFromLen(uint8Array.byteLength)\n newBuf.set(uint8Array)\n return newBuf\n}\n\n/**\n * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type.\n * See encoding.writeAny for more information.\n *\n * @param {any} data\n * @return {Uint8Array}\n */\nexport const encodeAny = data => {\n const encoder = encoding.createEncoder()\n encoding.writeAny(encoder, data)\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Decode an any-encoded value.\n *\n * @param {Uint8Array} buf\n * @return {any}\n */\nexport const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf))\n","/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* c8 ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n","/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as binary from './binary.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as string from './string.js'\nimport * as error from './error.js'\nimport * as encoding from './encoding.js'\n\nconst errorUnexpectedEndOfArray = error.create('Unexpected end of array')\nconst errorIntegerOutOfRange = error.create('Integer out of Range')\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n */\nexport class Decoder {\n /**\n * @param {Uint8Array} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @param {Uint8Array} uint8Array\n * @return {Decoder}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = buffer.createUint8ArrayViewFromArrayBuffer(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let mult = 1\n const len = decoder.arr.length\n while (decoder.pos < len) {\n const r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num\n mult *= 128 // next iteration, shift 7 \"more\" to the left\n if (r < binary.BIT8) {\n return num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let mult = 64\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n const len = decoder.arr.length\n while (decoder.pos < len) {\n r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult\n mult *= 128\n if (r < binary.BIT8) {\n return sign * num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * We don't test this function anymore as we use native decoding/encoding by default now.\n * Better not modify this anymore..\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\n/* c8 ignore start */\nexport const _readVarStringPolyfill = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n/* c8 ignore stop */\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n */\nexport const _readVarStringNative = decoder =>\n /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder))\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n *\n */\n/* c8 ignore next */\nexport const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill\n\n/**\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTerminatedUint8Array = decoder => {\n const encoder = encoding.createEncoder()\n let b\n while (true) {\n b = readUint8(decoder)\n if (b === 0) {\n return encoding.toUint8Array(encoder)\n }\n if (b === 1) {\n b = readUint8(decoder)\n }\n encoding.write(encoder, b)\n }\n}\n\n/**\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const readTerminatedString = decoder => string.decodeUtf8(readTerminatedUint8Array(decoder))\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object\n const len = readVarUint(decoder)\n /**\n * @type {Object}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = math.floor(diff / 2) // shift >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n","import {\n createDecoder,\n Decoder,\n readVarUint,\n readVarUint8Array,\n readVarString,\n} from 'lib0/decoding'\nimport {\n createEncoder,\n Encoder,\n toUint8Array,\n writeVarUint,\n writeVarString,\n length,\n} from 'lib0/encoding'\nimport { MessageType } from './types.js'\n\nexport class IncomingMessage {\n /**\n * Access to the received message.\n */\n decoder: Decoder\n\n /**\n * Access to the reply.\n */\n encoder: Encoder\n\n constructor(input: any) {\n if (!(input instanceof Uint8Array)) {\n input = new Uint8Array(input)\n }\n\n this.encoder = createEncoder()\n this.decoder = createDecoder(input)\n }\n\n readVarUint8Array() {\n return readVarUint8Array(this.decoder)\n }\n\n readVarUint() {\n return readVarUint(this.decoder)\n }\n\n readVarString() {\n return readVarString(this.decoder)\n }\n\n toUint8Array() {\n return toUint8Array(this.encoder)\n }\n\n writeVarUint(type: MessageType) {\n writeVarUint(this.encoder, type)\n }\n\n writeVarString(string: string) {\n writeVarString(this.encoder, string)\n }\n\n get length(): number {\n return length(this.encoder)\n }\n}\n","/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* c8 ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n","/**\n * Observable class prototype.\n *\n * @module observable\n */\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as array from './array.js'\n\n/**\n * Handles named events.\n *\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map}\n */\n this._observers = map.create()\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, name, set.create).add(f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, _f)\n f(...args)\n }\n this.on(name, _f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @param {N} name The event name.\n * @param {Array} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // 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.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n","/**\n * @module awareness-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as time from 'lib0/time'\nimport * as math from 'lib0/math'\nimport { Observable } from 'lib0/observable'\nimport * as f from 'lib0/function'\nimport * as Y from 'yjs' // eslint-disable-line\n\nexport const outdatedTimeout = 30000\n\n/**\n * @typedef {Object} MetaClientState\n * @property {number} MetaClientState.clock\n * @property {number} MetaClientState.lastUpdated unix timestamp\n */\n\n/**\n * The Awareness class implements a simple shared state protocol that can be used for non-persistent data like awareness information\n * (cursor, username, status, ..). Each client can update its own local state and listen to state changes of\n * remote clients. Every client may set a state of a remote peer to `null` to mark the client as offline.\n *\n * Each client is identified by a unique client id (something we borrow from `doc.clientID`). A client can override\n * its own state by propagating a message with an increasing timestamp (`clock`). If such a message is received, it is\n * applied if the known state of that client is older than the new state (`clock < newClock`). If a client thinks that\n * a remote client is offline, it may propagate a message with\n * `{ clock: currentClientClock, state: null, client: remoteClient }`. If such a\n * message is received, and the known clock of that client equals the received clock, it will override the state with `null`.\n *\n * Before a client disconnects, it should propagate a `null` state with an updated clock.\n *\n * Awareness states must be updated every 30 seconds. Otherwise the Awareness instance will delete the client state.\n *\n * @extends {Observable}\n */\nexport class Awareness extends Observable {\n /**\n * @param {Y.Doc} doc\n */\n constructor (doc) {\n super()\n this.doc = doc\n /**\n * @type {number}\n */\n this.clientID = doc.clientID\n /**\n * Maps from client id to client state\n * @type {Map>}\n */\n this.states = new Map()\n /**\n * @type {Map}\n */\n this.meta = new Map()\n this._checkInterval = /** @type {any} */ (setInterval(() => {\n const now = time.getUnixTime()\n if (this.getLocalState() !== null && (outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ (this.meta.get(this.clientID)).lastUpdated)) {\n // renew local clock\n this.setLocalState(this.getLocalState())\n }\n /**\n * @type {Array}\n */\n const remove = []\n this.meta.forEach((meta, clientid) => {\n if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) {\n remove.push(clientid)\n }\n })\n if (remove.length > 0) {\n removeAwarenessStates(this, remove, 'timeout')\n }\n }, math.floor(outdatedTimeout / 10)))\n doc.on('destroy', () => {\n this.destroy()\n })\n this.setLocalState({})\n }\n\n destroy () {\n this.emit('destroy', [this])\n this.setLocalState(null)\n super.destroy()\n clearInterval(this._checkInterval)\n }\n\n /**\n * @return {Object|null}\n */\n getLocalState () {\n return this.states.get(this.clientID) || null\n }\n\n /**\n * @param {Object|null} state\n */\n setLocalState (state) {\n const clientID = this.clientID\n const currLocalMeta = this.meta.get(clientID)\n const clock = currLocalMeta === undefined ? 0 : currLocalMeta.clock + 1\n const prevState = this.states.get(clientID)\n if (state === null) {\n this.states.delete(clientID)\n } else {\n this.states.set(clientID, state)\n }\n this.meta.set(clientID, {\n clock,\n lastUpdated: time.getUnixTime()\n })\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n if (state === null) {\n removed.push(clientID)\n } else if (prevState == null) {\n if (state != null) {\n added.push(clientID)\n }\n } else {\n updated.push(clientID)\n if (!f.equalityDeep(prevState, state)) {\n filteredUpdated.push(clientID)\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n this.emit('change', [{ added, updated: filteredUpdated, removed }, 'local'])\n }\n this.emit('update', [{ added, updated, removed }, 'local'])\n }\n\n /**\n * @param {string} field\n * @param {any} value\n */\n setLocalStateField (field, value) {\n const state = this.getLocalState()\n if (state !== null) {\n this.setLocalState({\n ...state,\n [field]: value\n })\n }\n }\n\n /**\n * @return {Map>}\n */\n getStates () {\n return this.states\n }\n}\n\n/**\n * Mark (remote) clients as inactive and remove them from the list of active peers.\n * This change will be propagated to remote clients.\n *\n * @param {Awareness} awareness\n * @param {Array} clients\n * @param {any} origin\n */\nexport const removeAwarenessStates = (awareness, clients, origin) => {\n const removed = []\n for (let i = 0; i < clients.length; i++) {\n const clientID = clients[i]\n if (awareness.states.has(clientID)) {\n awareness.states.delete(clientID)\n if (clientID === awareness.clientID) {\n const curMeta = /** @type {MetaClientState} */ (awareness.meta.get(clientID))\n awareness.meta.set(clientID, {\n clock: curMeta.clock + 1,\n lastUpdated: time.getUnixTime()\n })\n }\n removed.push(clientID)\n }\n }\n if (removed.length > 0) {\n awareness.emit('change', [{ added: [], updated: [], removed }, origin])\n awareness.emit('update', [{ added: [], updated: [], removed }, origin])\n }\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Array} clients\n * @return {Uint8Array}\n */\nexport const encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {\n const len = clients.length\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = clients[i]\n const state = states.get(clientID) || null\n const clock = /** @type {MetaClientState} */ (awareness.meta.get(clientID)).clock\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(state))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Modify the content of an awareness update before re-encoding it to an awareness update.\n *\n * This might be useful when you have a central server that wants to ensure that clients\n * cant hijack somebody elses identity.\n *\n * @param {Uint8Array} update\n * @param {function(any):any} modify\n * @return {Uint8Array}\n */\nexport const modifyAwarenessUpdate = (update, modify) => {\n const decoder = decoding.createDecoder(update)\n const encoder = encoding.createEncoder()\n const len = decoding.readVarUint(decoder)\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n const clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const modifiedState = modify(state)\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(modifiedState))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Uint8Array} update\n * @param {any} origin This will be added to the emitted change event\n */\nexport const applyAwarenessUpdate = (awareness, update, origin) => {\n const decoder = decoding.createDecoder(update)\n const timestamp = time.getUnixTime()\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n const len = decoding.readVarUint(decoder)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n let clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const clientMeta = awareness.meta.get(clientID)\n const prevState = awareness.states.get(clientID)\n const currClock = clientMeta === undefined ? 0 : clientMeta.clock\n if (currClock < clock || (currClock === clock && state === null && awareness.states.has(clientID))) {\n if (state === null) {\n // never let a remote client remove this local state\n if (clientID === awareness.clientID && awareness.getLocalState() != null) {\n // remote client removed the local state. Do not remote state. Broadcast a message indicating\n // that this client still exists by increasing the clock\n clock++\n } else {\n awareness.states.delete(clientID)\n }\n } else {\n awareness.states.set(clientID, state)\n }\n awareness.meta.set(clientID, {\n clock,\n lastUpdated: timestamp\n })\n if (clientMeta === undefined && state !== null) {\n added.push(clientID)\n } else if (clientMeta !== undefined && state === null) {\n removed.push(clientID)\n } else if (state !== null) {\n if (!f.equalityDeep(state, prevState)) {\n filteredUpdated.push(clientID)\n }\n updated.push(clientID)\n }\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n awareness.emit('change', [{\n added, updated: filteredUpdated, removed\n }, origin])\n }\n if (added.length > 0 || updated.length > 0 || removed.length > 0) {\n awareness.emit('update', [{\n added, updated, removed\n }, origin])\n }\n}\n","/**\n * @module sync-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as Y from 'yjs'\n\n/**\n * @typedef {Map} StateMap\n */\n\n/**\n * Core Yjs defines two message types:\n * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.\n * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it\n * received all information from the remote client.\n *\n * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection\n * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both\n * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.\n *\n * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.\n * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies\n * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the\n * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can\n * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them.\n * Therefore it is necesarry that the client initiates the sync.\n *\n * Construction of a message:\n * [messageType : varUint, message definition..]\n *\n * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!\n *\n * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)\n */\n\nexport const messageYjsSyncStep1 = 0\nexport const messageYjsSyncStep2 = 1\nexport const messageYjsUpdate = 2\n\n/**\n * Create a sync step 1 message based on the state of the current shared document.\n *\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n */\nexport const writeSyncStep1 = (encoder, doc) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep1)\n const sv = Y.encodeStateVector(doc)\n encoding.writeVarUint8Array(encoder, sv)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n * @param {Uint8Array} [encodedStateVector]\n */\nexport const writeSyncStep2 = (encoder, doc, encodedStateVector) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep2)\n encoding.writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector))\n}\n\n/**\n * Read SyncStep1 message and reply with SyncStep2.\n *\n * @param {decoding.Decoder} decoder The reply to the received message\n * @param {encoding.Encoder} encoder The received message\n * @param {Y.Doc} doc\n */\nexport const readSyncStep1 = (decoder, encoder, doc) =>\n writeSyncStep2(encoder, doc, decoding.readVarUint8Array(decoder))\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin) => {\n try {\n Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n } catch (error) {\n // This catches errors that are thrown by event handlers\n console.error('Caught error while handling a Yjs update', error)\n }\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Uint8Array} update\n */\nexport const writeUpdate = (encoder, update) => {\n encoding.writeVarUint(encoder, messageYjsUpdate)\n encoding.writeVarUint8Array(encoder, update)\n}\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readUpdate = readSyncStep2\n\n/**\n * @param {decoding.Decoder} decoder A message received from another client\n * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => {\n const messageType = decoding.readVarUint(decoder)\n switch (messageType) {\n case messageYjsSyncStep1:\n readSyncStep1(decoder, encoder, doc)\n break\n case messageYjsSyncStep2:\n readSyncStep2(decoder, doc, transactionOrigin)\n break\n case messageYjsUpdate:\n readUpdate(decoder, doc, transactionOrigin)\n break\n default:\n throw new Error('Unknown message type')\n }\n return messageType\n}\n","import {\n IncomingHttpHeaders, IncomingMessage, ServerResponse,\n} from 'http'\nimport { URLSearchParams } from 'url'\nimport { Awareness } from 'y-protocols/awareness'\nimport Connection from './Connection.js'\nimport Document from './Document.js'\nimport { Hocuspocus } from './Hocuspocus.js'\n\nexport enum MessageType {\n Unknown = -1,\n Sync = 0,\n Awareness = 1,\n Auth = 2,\n QueryAwareness = 3,\n SyncReply = 4, // same as Sync, but won't trigger another 'SyncStep1'\n Stateless = 5,\n BroadcastStateless = 6,\n CLOSE = 7,\n SyncStatus = 8, // TODO: should this be 8?\n}\n\nexport interface AwarenessUpdate {\n added: Array,\n updated: Array,\n removed: Array,\n}\n\nexport interface ConnectionConfiguration {\n readOnly: boolean\n requiresAuthentication: boolean\n isAuthenticated: boolean\n}\n\nexport interface Extension {\n priority?: number,\n onConfigure?(data: onConfigurePayload): Promise,\n onListen?(data: onListenPayload): Promise,\n onUpgrade?(data: onUpgradePayload): Promise,\n onConnect?(data: onConnectPayload): Promise,\n connected?(data: connectedPayload): Promise,\n onAuthenticate?(data: onAuthenticatePayload): Promise,\n onLoadDocument?(data: onLoadDocumentPayload): Promise,\n afterLoadDocument?(data: onLoadDocumentPayload): Promise,\n beforeHandleMessage?(data: beforeHandleMessagePayload): Promise,\n beforeBroadcastStateless?(data: beforeBroadcastStatelessPayload): Promise,\n onStateless?(payload: onStatelessPayload): Promise;\n onChange?(data: onChangePayload): Promise,\n onStoreDocument?(data: onStoreDocumentPayload): Promise,\n afterStoreDocument?(data: afterStoreDocumentPayload): Promise,\n onAwarenessUpdate?(data: onAwarenessUpdatePayload): Promise,\n onRequest?(data: onRequestPayload): Promise,\n onDisconnect?(data: onDisconnectPayload): Promise\n onDestroy?(data: onDestroyPayload): Promise,\n}\n\nexport type HookName =\n 'onConfigure' |\n 'onListen' |\n 'onUpgrade' |\n 'onConnect' |\n 'connected' |\n 'onAuthenticate' |\n 'onLoadDocument' |\n 'afterLoadDocument' |\n 'beforeHandleMessage' |\n 'beforeBroadcastStateless' |\n 'onStateless' |\n 'onChange' |\n 'onStoreDocument' |\n 'afterStoreDocument' |\n 'onAwarenessUpdate' |\n 'onRequest' |\n 'onDisconnect' |\n 'onDestroy'\n\nexport type HookPayload =\n onConfigurePayload |\n onListenPayload |\n onUpgradePayload |\n onConnectPayload |\n connectedPayload |\n onAuthenticatePayload |\n onLoadDocumentPayload |\n onStatelessPayload |\n beforeHandleMessagePayload |\n beforeBroadcastStatelessPayload |\n onChangePayload |\n onStoreDocumentPayload |\n afterStoreDocumentPayload |\n onAwarenessUpdatePayload |\n onRequestPayload |\n onDisconnectPayload |\n onDestroyPayload\n\nexport interface Configuration extends Extension {\n /**\n * A name for the instance, used for logging.\n */\n name: string | null,\n /**\n * A list of hocuspocus extenions.\n */\n extensions: Array,\n /**\n * The port which the server listens on.\n */\n port?: number,\n /**\n * The address which the server listens on.\n */\n address?: string,\n /**\n * Defines in which interval the server sends a ping, and closes the connection when no pong is sent back.\n */\n timeout: number,\n /**\n * Debounces the call of the `onStoreDocument` hook for the given amount of time in ms.\n * Otherwise every single update would be persisted.\n */\n debounce: number,\n /**\n * Makes sure to call `onStoreDocument` at least in the given amount of time (ms).\n */\n maxDebounce: number\n /**\n * By default, the servers show a start screen. If passed false, the server will start quietly.\n */\n quiet: boolean,\n\n /**\n * options to pass to the ydoc document\n */\n yDocOptions: {\n gc: boolean, // enable or disable garbage collection (see https://github.com/yjs/yjs/blob/main/INTERNALS.md#deletions)\n gcFilter: () => boolean, // will be called before garbage collecting ; return false to keep it\n },\n /**\n * Function which returns the (customized) document name based on the request\n */\n getDocumentName?(data: getDocumentNamePayload): string | Promise,\n}\n\nexport interface getDocumentNamePayload {\n documentName: string,\n request: IncomingMessage,\n requestParameters: URLSearchParams,\n}\n\nexport interface onStatelessPayload {\n connection: Connection,\n documentName: string,\n document: Document,\n payload: string,\n}\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface onAuthenticatePayload {\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n token: string,\n connection: ConnectionConfiguration\n}\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface onConnectPayload {\n documentName: string,\n instance: Hocuspocus,\n request: IncomingMessage,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration\n}\n\n// @todo Change 'connection' to 'connectionConfig', and 'connectionInstance' to 'connection' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface connectedPayload {\n context: any,\n documentName: string,\n instance: Hocuspocus,\n request: IncomingMessage,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration,\n connectionInstance: Connection\n}\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface onLoadDocumentPayload {\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration\n}\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface afterLoadDocumentPayload {\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration\n}\n\nexport interface onChangePayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n update: Uint8Array,\n socketId: string,\n}\n\nexport interface beforeHandleMessagePayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n update: Uint8Array,\n socketId: string,\n connection: Connection\n}\n\nexport interface beforeBroadcastStatelessPayload {\n document: Document,\n documentName: string,\n payload: string,\n}\n\nexport interface onStoreDocumentPayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n}\n\nexport interface afterStoreDocumentPayload extends onStoreDocumentPayload {}\n\nexport interface onAwarenessUpdatePayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n update: Uint8Array,\n socketId: string,\n added: number[],\n updated: number[],\n removed: number[],\n awareness: Awareness,\n states: StatesArray,\n}\n\nexport type StatesArray = { clientId: number, [key: string | number]: any }[]\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface fetchPayload {\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration\n}\n\nexport interface storePayload extends onStoreDocumentPayload {\n state: Buffer,\n}\n\nexport interface onDisconnectPayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n}\n\nexport interface onRequestPayload {\n request: IncomingMessage,\n response: ServerResponse,\n instance: Hocuspocus,\n}\n\nexport interface onUpgradePayload {\n request: IncomingMessage,\n socket: any,\n head: any,\n instance: Hocuspocus,\n}\n\nexport interface onListenPayload {\n instance: Hocuspocus,\n configuration: Configuration,\n port: number,\n}\n\nexport interface onDestroyPayload {\n instance: Hocuspocus,\n}\n\nexport interface onConfigurePayload {\n instance: Hocuspocus,\n configuration: Configuration,\n version: string,\n}\n","import {\n createEncoder,\n Encoder,\n toUint8Array,\n writeVarString,\n writeVarUint,\n writeVarUint8Array,\n} from 'lib0/encoding'\nimport { Awareness, encodeAwarenessUpdate } from 'y-protocols/awareness'\nimport { writeSyncStep1, writeUpdate } from 'y-protocols/sync'\n\nimport { writeAuthenticated, writePermissionDenied } from '@hocuspocus/common'\nimport Document from './Document.js'\nimport { MessageType } from './types.js'\n\nexport class OutgoingMessage {\n\n encoder: Encoder\n\n type?: number\n\n category?: string\n\n constructor(documentName: string) {\n this.encoder = createEncoder()\n\n writeVarString(this.encoder, documentName)\n }\n\n createSyncMessage(): OutgoingMessage {\n this.type = MessageType.Sync\n\n writeVarUint(this.encoder, MessageType.Sync)\n\n return this\n }\n\n createSyncReplyMessage(): OutgoingMessage {\n this.type = MessageType.SyncReply\n\n writeVarUint(this.encoder, MessageType.SyncReply)\n\n return this\n }\n\n createAwarenessUpdateMessage(awareness: Awareness, changedClients?: Array): OutgoingMessage {\n this.type = MessageType.Awareness\n this.category = 'Update'\n\n const message = encodeAwarenessUpdate(\n awareness,\n changedClients || Array.from(awareness.getStates().keys()),\n )\n\n writeVarUint(this.encoder, MessageType.Awareness)\n writeVarUint8Array(this.encoder, message)\n\n return this\n }\n\n writeQueryAwareness(): OutgoingMessage {\n this.type = MessageType.QueryAwareness\n this.category = 'Update'\n\n writeVarUint(this.encoder, MessageType.QueryAwareness)\n\n return this\n }\n\n writeAuthenticated(readonly: boolean): OutgoingMessage {\n this.type = MessageType.Auth\n this.category = 'Authenticated'\n\n writeVarUint(this.encoder, MessageType.Auth)\n writeAuthenticated(this.encoder, readonly ? 'readonly' : 'read-write')\n\n return this\n }\n\n writePermissionDenied(reason: string): OutgoingMessage {\n this.type = MessageType.Auth\n this.category = 'PermissionDenied'\n\n writeVarUint(this.encoder, MessageType.Auth)\n writePermissionDenied(this.encoder, reason)\n\n return this\n }\n\n writeFirstSyncStepFor(document: Document): OutgoingMessage {\n this.category = 'SyncStep1'\n\n writeSyncStep1(this.encoder, document)\n\n return this\n }\n\n writeUpdate(update: Uint8Array): OutgoingMessage {\n this.category = 'Update'\n\n writeUpdate(this.encoder, update)\n\n return this\n }\n\n writeStateless(payload: string): OutgoingMessage {\n this.category = 'Stateless'\n\n writeVarUint(this.encoder, MessageType.Stateless)\n writeVarString(this.encoder, payload)\n\n return this\n }\n\n writeBroadcastStateless(payload: string): OutgoingMessage {\n this.category = 'Stateless'\n\n writeVarUint(this.encoder, MessageType.BroadcastStateless)\n writeVarString(this.encoder, payload)\n\n return this\n }\n\n // TODO: should this be write* or create* as method name?\n writeSyncStatus(updateSaved: boolean): OutgoingMessage {\n this.category = 'SyncStatus'\n\n writeVarUint(this.encoder, MessageType.SyncStatus)\n writeVarUint(this.encoder, updateSaved ? 1 : 0)\n\n return this\n }\n\n toUint8Array(): Uint8Array {\n return toUint8Array(this.encoder)\n }\n\n}\n","import * as decoding from 'lib0/decoding'\nimport { readVarString } from 'lib0/decoding'\nimport { applyAwarenessUpdate } from 'y-protocols/awareness'\nimport {\n messageYjsSyncStep1,\n messageYjsSyncStep2,\n messageYjsUpdate,\n readSyncStep1,\n readSyncStep2,\n readUpdate,\n} from 'y-protocols/sync'\nimport * as Y from 'yjs'\nimport Connection from './Connection.js'\nimport { Debugger } from './Debugger.js'\nimport Document from './Document.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { MessageType } from './types.js'\n\nexport class MessageReceiver {\n\n message: IncomingMessage\n\n logger: Debugger\n\n constructor(message: IncomingMessage, logger: Debugger) {\n this.message = message\n this.logger = logger\n }\n\n public apply(document: Document, connection?: Connection, reply?: (message: Uint8Array) => void) {\n const { message } = this\n const type = message.readVarUint()\n const emptyMessageLength = message.length\n\n switch (type) {\n case MessageType.Sync:\n case MessageType.SyncReply: {\n message.writeVarUint(MessageType.Sync)\n this.readSyncMessage(message, document, connection, reply, type !== MessageType.SyncReply)\n\n if (message.length > emptyMessageLength + 1) {\n if (reply) {\n reply(message.toUint8Array())\n } else if (connection) {\n // TODO: We should log this, shouldn’t we?\n // this.logger.log({\n // direction: 'out',\n // type: MessageType.Awareness,\n // category: 'Update',\n // })\n connection.send(message.toUint8Array())\n }\n }\n\n break\n }\n case MessageType.Awareness: {\n this.logger.log({\n direction: 'in',\n type: MessageType.Awareness,\n category: 'Update',\n })\n\n applyAwarenessUpdate(document.awareness, message.readVarUint8Array(), connection)\n\n break\n }\n case MessageType.QueryAwareness: {\n\n this.applyQueryAwarenessMessage(document, reply)\n\n break\n }\n case MessageType.Stateless: {\n connection?.callbacks.statelessCallback({\n connection,\n documentName: document.name,\n document,\n payload: readVarString(message.decoder),\n })\n\n break\n }\n case MessageType.BroadcastStateless: {\n const msg = message.readVarString()\n document.getConnections().forEach(connection => {\n connection.sendStateless(msg)\n })\n break\n }\n\n case MessageType.CLOSE: {\n connection?.close({\n code: 1000,\n reason: 'provider_initiated',\n })\n break\n }\n default:\n console.error(`Unable to handle message of type ${type}: no handler defined!`)\n // Do nothing\n }\n }\n\n readSyncMessage(message: IncomingMessage, document: Document, connection?: Connection, reply?: (message: Uint8Array) => void, requestFirstSync = true) {\n const type = message.readVarUint()\n\n switch (type) {\n case messageYjsSyncStep1: {\n this.logger.log({\n direction: 'in',\n type: MessageType.Sync,\n category: 'SyncStep1',\n })\n\n readSyncStep1(message.decoder, message.encoder, document)\n\n // When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1.\n this.logger.log({\n direction: 'out',\n type: MessageType.Sync,\n category: 'SyncStep2',\n })\n\n if (reply && requestFirstSync) {\n const syncMessage = (new OutgoingMessage(document.name)\n .createSyncReplyMessage()\n .writeFirstSyncStepFor(document))\n\n this.logger.log({\n direction: 'out',\n type: MessageType.Sync,\n category: 'SyncStep1',\n })\n\n reply(syncMessage.toUint8Array())\n } else if (connection) {\n const syncMessage = (new OutgoingMessage(document.name)\n .createSyncMessage()\n .writeFirstSyncStepFor(document))\n\n this.logger.log({\n direction: 'out',\n type: MessageType.Sync,\n category: 'SyncStep1',\n })\n\n connection.send(syncMessage.toUint8Array())\n }\n break\n }\n case messageYjsSyncStep2:\n this.logger.log({\n direction: 'in',\n type: MessageType.Sync,\n category: 'SyncStep2',\n })\n\n if (connection?.readOnly) {\n // We're in read-only mode, so we can't apply the update.\n // Let's use snapshotContainsUpdate to see if the update actually contains changes.\n // If not, we can still ack the update\n const snapshot = Y.snapshot(document)\n const update = decoding.readVarUint8Array(message.decoder)\n if (Y.snapshotContainsUpdate(snapshot, update)) {\n // no new changes in update\n const ackMessage = new OutgoingMessage(document.name)\n .writeSyncStatus(true)\n\n connection.send(ackMessage.toUint8Array())\n } else {\n // new changes in update that we can't apply, because readOnly\n const ackMessage = new OutgoingMessage(document.name)\n .writeSyncStatus(false)\n\n connection.send(ackMessage.toUint8Array())\n }\n break\n }\n\n readSyncStep2(message.decoder, document, connection)\n\n if (connection) {\n // TODO: how should this work if connection is not set? should we use reply?\n // reply is used by redis, but I'm unsure how that code path works\n connection.send(new OutgoingMessage(document.name)\n .writeSyncStatus(true).toUint8Array())\n }\n break\n case messageYjsUpdate:\n this.logger.log({\n direction: 'in',\n type: MessageType.Sync,\n category: 'Update',\n })\n\n if (connection?.readOnly) {\n connection.send(new OutgoingMessage(document.name)\n .writeSyncStatus(false).toUint8Array())\n break\n }\n\n readUpdate(message.decoder, document, connection)\n if (connection) {\n // TODO: how should this work if connection is not set? should we use reply?\n // reply is used by redis, but I'm unsure how that code path works\n connection.send(new OutgoingMessage(document.name)\n .writeSyncStatus(true).toUint8Array())\n }\n break\n default:\n throw new Error(`Received a message with an unknown type: ${type}`)\n }\n\n return type\n }\n\n applyQueryAwarenessMessage(document: Document, reply?: (message: Uint8Array) => void) {\n const message = new OutgoingMessage(document.name)\n .createAwarenessUpdateMessage(document.awareness)\n\n if (reply) {\n reply(message.toUint8Array())\n }\n\n // TODO: We should add support for WebSocket connections, too, right?\n // this.logger.log({\n // direction: 'out',\n // type: MessageType.Sync,\n // category: 'SyncStep1',\n // })\n\n // connection.send(syncMessage.toUint8Array())\n }\n}\n","import { IncomingMessage as HTTPIncomingMessage } from 'http'\nimport AsyncLock from 'async-lock'\nimport WebSocket from 'ws'\nimport {\n CloseEvent, ConnectionTimeout, Forbidden, WsReadyStates,\n} from '@hocuspocus/common'\nimport Document from './Document.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { MessageReceiver } from './MessageReceiver.js'\nimport { Debugger } from './Debugger.js'\nimport { onStatelessPayload } from './types.js'\n\nexport class Connection {\n\n webSocket: WebSocket\n\n context: any\n\n document: Document\n\n pingInterval: NodeJS.Timeout\n\n pongReceived = true\n\n request: HTTPIncomingMessage\n\n timeout: number\n\n callbacks: any = {\n onClose: [(document: Document, event?: CloseEvent) => null],\n beforeHandleMessage: (connection: Connection, update: Uint8Array) => Promise,\n statelessCallback: () => Promise,\n }\n\n socketId: string\n\n lock: AsyncLock\n\n readOnly: Boolean\n\n logger: Debugger\n\n /**\n * Constructor.\n */\n constructor(\n connection: WebSocket,\n request: HTTPIncomingMessage,\n document: Document,\n timeout: number,\n socketId: string,\n context: any,\n readOnly = false,\n logger: Debugger,\n ) {\n this.webSocket = connection\n this.context = context\n this.document = document\n this.request = request\n this.timeout = timeout\n this.socketId = socketId\n this.readOnly = readOnly\n this.logger = logger\n\n this.lock = new AsyncLock()\n\n this.webSocket.binaryType = 'arraybuffer'\n this.document.addConnection(this)\n\n this.pingInterval = setInterval(this.check.bind(this), this.timeout)\n\n this.webSocket.on('close', this.boundClose)\n this.webSocket.on('message', this.boundHandleMessage)\n this.webSocket.on('pong', this.boundHandlePong)\n\n this.sendCurrentAwareness()\n }\n\n boundClose = this.close.bind(this)\n\n boundHandleMessage = this.handleMessage.bind(this)\n\n boundHandlePong = this.handlePong.bind(this)\n\n handlePong() {\n this.pongReceived = true\n }\n\n /**\n * Set a callback that will be triggered when the connection is closed\n */\n onClose(callback: (document: Document, event?: CloseEvent) => void): Connection {\n this.callbacks.onClose.push(callback)\n\n return this\n }\n\n /**\n * Set a callback that will be triggered when an stateless message is received\n */\n onStatelessCallback(callback: (payload: onStatelessPayload) => Promise): Connection {\n this.callbacks.statelessCallback = callback\n\n return this\n }\n\n /**\n * Set a callback that will be triggered before an message is handled\n */\n beforeHandleMessage(callback: (connection: Connection, update: Uint8Array) => Promise): Connection {\n this.callbacks.beforeHandleMessage = callback\n\n return this\n }\n\n /**\n * Send the given message\n */\n send(message: any): void {\n if (\n this.webSocket.readyState === WsReadyStates.Closing\n || this.webSocket.readyState === WsReadyStates.Closed\n ) {\n this.close()\n }\n\n try {\n this.webSocket.send(message, (error: any) => {\n if (error != null) this.close()\n })\n } catch (exception) {\n this.close()\n }\n }\n\n /**\n * Send a stateless message with payload\n */\n public sendStateless(payload: string): void {\n const message = new OutgoingMessage(this.document.name)\n .writeStateless(payload)\n\n this.logger.log({\n direction: 'out',\n type: message.type,\n category: message.category,\n })\n\n this.send(\n message.toUint8Array(),\n )\n }\n\n /**\n * Graceful wrapper around the WebSocket close method.\n */\n close(event?: CloseEvent): void {\n this.lock.acquire('close', (done: Function) => {\n if (this.pingInterval) {\n clearInterval(this.pingInterval)\n }\n\n if (this.document.hasConnection(this)) {\n this.document.removeConnection(this)\n clearInterval(this.pingInterval)\n\n this.webSocket.removeListener('close', this.boundClose)\n this.webSocket.removeListener('message', this.boundHandleMessage)\n this.webSocket.removeListener('pong', this.boundHandlePong)\n\n this.callbacks.onClose.forEach((callback: (arg0: Document, arg1?: CloseEvent) => any) => callback(this.document, event))\n }\n\n done()\n })\n }\n\n /**\n * Check if pong was received and close the connection otherwise\n * @private\n */\n private check(): void {\n if (!this.pongReceived) {\n return this.close(ConnectionTimeout)\n }\n\n if (this.document.hasConnection(this)) {\n this.pongReceived = false\n\n try {\n this.webSocket.ping()\n } catch (error) {\n this.close(ConnectionTimeout)\n }\n }\n }\n\n /**\n * Send the current document awareness to the client, if any\n * @private\n */\n private sendCurrentAwareness(): void {\n if (!this.document.hasAwarenessStates()) {\n return\n }\n\n const awarenessMessage = new OutgoingMessage(this.document.name)\n .createAwarenessUpdateMessage(this.document.awareness)\n\n this.logger.log({\n direction: 'out',\n type: awarenessMessage.type,\n category: awarenessMessage.category,\n })\n\n this.send(awarenessMessage.toUint8Array())\n }\n\n /**\n * Handle an incoming message\n * @private\n */\n private handleMessage(data: Uint8Array): void {\n const message = new IncomingMessage(data)\n const documentName = message.readVarString()\n\n if (documentName !== this.document.name) return\n\n message.writeVarString(documentName)\n\n this.callbacks.beforeHandleMessage(this, data)\n .then(() => {\n new MessageReceiver(\n message,\n this.logger,\n ).apply(this.document, this)\n })\n .catch((e: any) => {\n console.log('closing connection because of exception', e)\n this.close({\n code: 'code' in e ? e.code : Forbidden.code,\n reason: 'reason' in e ? e.reason : Forbidden.reason,\n })\n })\n }\n\n}\n\nexport default Connection\n","// import * as time from 'lib0/time'\nimport { MessageType } from './types.js'\n\nexport class Debugger {\n logs: any[] = []\n\n listen = false\n\n output = false\n\n enable() {\n this.flush()\n\n this.listen = true\n }\n\n disable() {\n this.listen = false\n }\n\n verbose() {\n this.output = true\n }\n\n quiet() {\n this.output = false\n }\n\n log(message: any) {\n if (!this.listen) {\n return this\n }\n\n const item = {\n ...message,\n type: MessageType[message.type],\n // time: time.getUnixTime(),\n }\n\n this.logs.push(item)\n\n if (this.output) {\n console.log('[DEBUGGER]', item.direction === 'in' ? 'IN –>' : 'OUT <–', `${item.type}/${item.category}`)\n }\n\n return this\n }\n\n flush() {\n this.logs = []\n\n return this\n }\n\n get() {\n return {\n logs: this.logs,\n }\n }\n}\n","/**\n * Mutual exclude for JavaScript.\n *\n * @module mutex\n */\n\n/**\n * @callback mutex\n * @param {function():void} cb Only executed when this mutex is not in the current stack\n * @param {function():void} [elseCb] Executed when this mutex is in the current stack\n */\n\n/**\n * Creates a mutual exclude function with the following property:\n *\n * ```js\n * const mutex = createMutex()\n * mutex(() => {\n * // This function is immediately executed\n * mutex(() => {\n * // This function is not executed, as the mutex is already active.\n * })\n * })\n * ```\n *\n * @return {mutex} A mutual exclude function\n * @public\n */\nexport const createMutex = () => {\n let token = true\n return (f, g) => {\n if (token) {\n token = false\n try {\n f()\n } finally {\n token = true\n }\n } else if (g !== undefined) {\n g()\n }\n }\n}\n","import WebSocket from 'ws'\nimport { Awareness, removeAwarenessStates, applyAwarenessUpdate } from 'y-protocols/awareness'\nimport { applyUpdate, Doc, encodeStateAsUpdate } from 'yjs'\nimport { mutex, createMutex } from 'lib0/mutex.js'\nimport { AwarenessUpdate } from './types.js'\nimport Connection from './Connection.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { Debugger } from './Debugger.js'\n\nexport class Document extends Doc {\n\n awareness: Awareness\n\n callbacks = {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n onUpdate: (document: Document, connection: Connection, update: Uint8Array) => {},\n beforeBroadcastStateless: (document: Document, stateless: string) => {},\n }\n\n connections: Map,\n connection: Connection\n }> = new Map()\n\n // The number of direct (non-websocket) connections to this document\n directConnectionsCount = 0\n\n name: string\n\n mux: mutex\n\n logger: Debugger\n\n isLoading: boolean\n\n /**\n * Constructor.\n */\n constructor(name: string, logger: Debugger, yDocOptions: {}) {\n super(yDocOptions)\n\n this.name = name\n this.mux = createMutex()\n\n this.awareness = new Awareness(this)\n this.awareness.setLocalState(null)\n\n this.awareness.on('update', this.handleAwarenessUpdate.bind(this))\n this.on('update', this.handleUpdate.bind(this))\n\n this.logger = logger\n this.isLoading = true\n }\n\n /**\n * Check if the Document is empty\n */\n isEmpty(fieldName: string): boolean {\n // eslint-disable-next-line no-underscore-dangle\n return !this.get(fieldName)._start\n }\n\n /**\n * Merge the given document(s) into this one\n */\n merge(documents: Doc|Array): Document {\n (Array.isArray(documents) ? documents : [documents]).forEach(document => {\n applyUpdate(this, encodeStateAsUpdate(document))\n })\n\n return this\n }\n\n /**\n * Set a callback that will be triggered when the document is updated\n */\n onUpdate(callback: (document: Document, connection: Connection, update: Uint8Array) => void): Document {\n this.callbacks.onUpdate = callback\n\n return this\n }\n\n /**\n * Set a callback that will be triggered before a stateless message is broadcasted\n */\n beforeBroadcastStateless(callback: (document: Document, stateless: string) => void): Document {\n this.callbacks.beforeBroadcastStateless = callback\n\n return this\n }\n\n /**\n * Register a connection and a set of clients on this document keyed by the\n * underlying websocket connection\n */\n addConnection(connection: Connection): Document {\n this.connections.set(connection.webSocket, {\n clients: new Set(),\n connection,\n })\n\n return this\n }\n\n /**\n * Is the given connection registered on this document\n */\n hasConnection(connection: Connection): boolean {\n return this.connections.has(connection.webSocket)\n }\n\n /**\n * Remove the given connection from this document\n */\n removeConnection(connection: Connection): Document {\n removeAwarenessStates(\n this.awareness,\n Array.from(this.getClients(connection.webSocket)),\n null,\n )\n\n this.connections.delete(connection.webSocket)\n\n return this\n }\n\n addDirectConnection(): Document {\n this.directConnectionsCount += 1\n\n return this\n }\n\n removeDirectConnection(): Document {\n if (this.directConnectionsCount > 0) {\n this.directConnectionsCount -= 1\n }\n\n return this\n }\n\n /**\n * Get the number of active connections for this document\n */\n getConnectionsCount(): number {\n return this.connections.size + this.directConnectionsCount\n }\n\n /**\n * Get an array of registered connections\n */\n getConnections(): Array {\n return Array.from(this.connections.values()).map(data => data.connection)\n }\n\n /**\n * Get the client ids for the given connection instance\n */\n getClients(connectionInstance: WebSocket): Set {\n const connection = this.connections.get(connectionInstance)\n\n return connection?.clients === undefined ? new Set() : connection.clients\n }\n\n /**\n * Has the document awareness states\n */\n hasAwarenessStates(): boolean {\n return this.awareness.getStates().size > 0\n }\n\n /**\n * Apply the given awareness update\n */\n applyAwarenessUpdate(connection: Connection, update: Uint8Array): Document {\n applyAwarenessUpdate(\n this.awareness,\n update,\n connection.webSocket,\n )\n\n return this\n }\n\n /**\n * Handle an awareness update and sync changes to clients\n * @private\n */\n private handleAwarenessUpdate(\n { added, updated, removed }: AwarenessUpdate,\n connectionInstance: WebSocket,\n ): Document {\n const changedClients = added.concat(updated, removed)\n\n if (connectionInstance !== null) {\n const connection = this.connections.get(connectionInstance)\n\n if (connection) {\n added.forEach((clientId: any) => connection.clients.add(clientId))\n removed.forEach((clientId: any) => connection.clients.delete(clientId))\n }\n }\n\n this.getConnections().forEach(connection => {\n const awarenessMessage = new OutgoingMessage(this.name)\n .createAwarenessUpdateMessage(this.awareness, changedClients)\n\n this.logger.log({\n direction: 'out',\n type: awarenessMessage.type,\n category: awarenessMessage.category,\n })\n\n connection.send(\n awarenessMessage.toUint8Array(),\n )\n })\n\n return this\n }\n\n /**\n * Handle an updated document and sync changes to clients\n */\n private handleUpdate(update: Uint8Array, connection: Connection): Document {\n this.callbacks.onUpdate(this, connection, update)\n\n const message = new OutgoingMessage(this.name)\n .createSyncMessage()\n .writeUpdate(update)\n\n this.getConnections().forEach(connection => {\n this.logger.log({\n direction: 'out',\n type: message.type,\n category: message.category,\n })\n\n connection.send(\n message.toUint8Array(),\n )\n })\n\n return this\n }\n\n /**\n * Broadcast stateless message to all connections\n */\n public broadcastStateless(payload: string): void {\n this.callbacks.beforeBroadcastStateless(this, payload)\n\n this.getConnections().forEach(connection => {\n connection.sendStateless(payload)\n })\n }\n}\n\nexport default Document\n","import { IncomingMessage } from 'http'\nimport { URLSearchParams } from 'url'\n\n/**\n * Get parameters by the given request\n */\nexport function getParameters(request?: Pick): URLSearchParams {\n const query = request?.url?.split('?') || []\n return new URLSearchParams(query[1] ? query[1] : '')\n}\n","import { IncomingHttpHeaders, IncomingMessage } from 'http'\nimport {\n Forbidden, Unauthorized, WsReadyStates,\n} from '@hocuspocus/common'\nimport * as decoding from 'lib0/decoding'\nimport { v4 as uuid } from 'uuid'\nimport WebSocket from 'ws'\n\nimport Connection from './Connection.js'\nimport { Debugger } from './Debugger.js'\nimport Document from './Document.js'\nimport { Hocuspocus } from './Hocuspocus.js'\nimport { IncomingMessage as SocketIncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport {\n ConnectionConfiguration,\n MessageType,\n beforeHandleMessagePayload,\n onDisconnectPayload,\n} from './types.js'\nimport { getParameters } from './util/getParameters.js'\n\n/**\n * The `ClientConnection` class is responsible for handling an incoming WebSocket\n *\n * TODO-refactor:\n * - use event handlers instead of calling hooks directly, hooks should probably be called from Hocuspocus.ts\n */\nexport class ClientConnection {\n // this map indicates whether a `Connection` instance has already taken over for incoming message for the key (i.e. documentName)\n private readonly documentConnections: Record = {}\n\n // While the connection will be establishing messages will\n // be queued and handled later.\n private readonly incomingMessageQueue: Record = {}\n\n // While the connection is establishing, kee\n private readonly documentConnectionsEstablished = new Set()\n\n // hooks payload by Document\n private readonly hookPayloads: Record = {}\n\n private readonly callbacks = {\n onClose: [(document: Document, payload: onDisconnectPayload) => {}],\n }\n\n private readonly closeIdleConnectionTimeout: NodeJS.Timeout\n\n // Every new connection gets a unique identifier.\n private readonly socketId = uuid()\n\n /**\n * The `ClientConnection` class receives incoming WebSocket connections,\n * runs all hooks:\n *\n * - onConnect for all connections\n * - onAuthenticate only if required\n *\n * … and if nothings fails it’ll fully establish the connection and\n * load the Document then.\n */\n constructor(\n private readonly websocket: WebSocket,\n private readonly request: IncomingMessage,\n private readonly documentProvider: {\n createDocument: Hocuspocus['createDocument'],\n },\n // TODO: change to events\n private readonly hooks: Hocuspocus['hooks'],\n private readonly debuggerTool: Debugger,\n private readonly opts: {\n requiresAuthentication: boolean,\n timeout: number,\n },\n ) {\n // Make sure to close an idle connection after a while.\n this.closeIdleConnectionTimeout = setTimeout(() => {\n websocket.close(Unauthorized.code, Unauthorized.reason)\n }, opts.timeout)\n\n websocket.on('message', this.messageHandler)\n }\n\n /**\n * Set a callback that will be triggered when the connection is closed\n */\n public onClose(callback: (document: Document, payload: onDisconnectPayload) => void): ClientConnection {\n this.callbacks.onClose.push(callback)\n\n return this\n }\n\n /**\n * Create a new connection by the given request and document\n */\n private createConnection(connection: WebSocket, document: Document): Connection {\n const hookPayload = this.hookPayloads[document.name]\n const instance = new Connection(\n connection,\n hookPayload.request,\n document,\n this.opts.timeout,\n hookPayload.socketId,\n hookPayload.context,\n hookPayload.connection.readOnly,\n this.debuggerTool,\n )\n\n instance.onClose(async (document, event) => {\n const disconnectHookPayload: onDisconnectPayload = {\n instance: this.documentProvider as Hocuspocus, // TODO, this will be removed when we use events instead of hooks for this class\n clientsCount: document.getConnectionsCount(),\n context: hookPayload.context,\n document,\n socketId: hookPayload.socketId,\n documentName: document.name,\n requestHeaders: hookPayload.request.headers,\n requestParameters: getParameters(hookPayload.request),\n }\n\n await this.hooks('onDisconnect', hookPayload)\n this.callbacks.onClose.forEach((callback => callback(document, disconnectHookPayload)))\n })\n\n instance.onStatelessCallback(async payload => {\n try {\n return await this.hooks('onStateless', payload)\n } catch (error: any) {\n // TODO: weird pattern, what's the use of this?\n if (error?.message) {\n throw error\n }\n }\n })\n\n instance.beforeHandleMessage((connection, update) => {\n const beforeHandleMessagePayload: beforeHandleMessagePayload = {\n instance: this.documentProvider as Hocuspocus, // TODO, this will be removed when we use events instead of hooks for this class\n clientsCount: document.getConnectionsCount(),\n context: hookPayload.context,\n document,\n socketId: hookPayload.socketId,\n connection,\n documentName: document.name,\n requestHeaders: hookPayload.request.headers,\n requestParameters: getParameters(hookPayload.request),\n update,\n }\n\n return this.hooks('beforeHandleMessage', beforeHandleMessagePayload)\n })\n\n // If the WebSocket has already disconnected (wow, that was fast) – then\n // immediately call close to cleanup the connection and document in memory.\n if (\n connection.readyState === WsReadyStates.Closing\n || connection.readyState === WsReadyStates.Closed\n ) {\n instance.close()\n }\n\n return instance\n }\n\n // Once all hooks are run, we’ll fully establish the connection:\n private setUpNewConnection = async (documentName: string) => {\n // Not an idle connection anymore, no need to close it then.\n clearTimeout(this.closeIdleConnectionTimeout)\n\n const hookPayload = this.hookPayloads[documentName]\n // If no hook interrupts, create a document and connection\n const document = await this.documentProvider.createDocument(documentName, hookPayload.request, hookPayload.socketId, hookPayload.connection, hookPayload.context)\n const instance = this.createConnection(this.websocket, document)\n\n instance.onClose((document, event) => {\n delete this.hookPayloads[documentName]\n delete this.documentConnections[documentName]\n delete this.incomingMessageQueue[documentName]\n this.documentConnectionsEstablished.delete(documentName)\n\n if (Object.keys(this.documentConnections).length === 0) {\n instance.webSocket.close(event?.code, event?.reason) // TODO: Move this to Hocuspocus connection handler\n }\n })\n\n this.documentConnections[documentName] = true\n\n // There’s no need to queue messages anymore.\n // Let’s work through queued messages.\n this.incomingMessageQueue[documentName].forEach(input => {\n this.websocket.emit('message', input)\n })\n\n this.hooks('connected', {\n ...hookPayload,\n documentName,\n context: hookPayload.context,\n connectionInstance: instance,\n })\n }\n\n // This listener handles authentication messages and queues everything else.\n private handleQueueingMessage = async (data: Uint8Array) => {\n try {\n const tmpMsg = new SocketIncomingMessage(data)\n\n const documentName = decoding.readVarString(tmpMsg.decoder)\n const type = decoding.readVarUint(tmpMsg.decoder)\n\n if (!(type === MessageType.Auth && !this.documentConnectionsEstablished.has(documentName))) {\n this.incomingMessageQueue[documentName].push(data)\n return\n }\n\n // Okay, we’ve got the authentication message we’re waiting for:\n this.documentConnectionsEstablished.add(documentName)\n\n // The 2nd integer contains the submessage type\n // which will always be authentication when sent from client -> server\n decoding.readVarUint(tmpMsg.decoder)\n const token = decoding.readVarString(tmpMsg.decoder)\n\n this.debuggerTool.log({\n direction: 'in',\n type,\n category: 'Token',\n })\n\n try {\n const hookPayload = this.hookPayloads[documentName]\n await this.hooks('onAuthenticate', {\n token,\n ...hookPayload,\n documentName,\n }, (contextAdditions: any) => {\n // Hooks are allowed to give us even more context and we’ll merge everything together.\n // We’ll pass the context to other hooks then.\n hookPayload.context = { ...hookPayload.context, ...contextAdditions }\n })\n // All `onAuthenticate` hooks passed.\n hookPayload.connection.isAuthenticated = true\n\n // Let the client know that authentication was successful.\n const message = new OutgoingMessage(documentName).writeAuthenticated(hookPayload.connection.readOnly)\n\n this.debuggerTool.log({\n direction: 'out',\n type: message.type,\n category: message.category,\n })\n\n this.websocket.send(message.toUint8Array())\n\n // Time to actually establish the connection.\n await this.setUpNewConnection(documentName)\n } catch (err: any) {\n const error = err || Forbidden\n const message = new OutgoingMessage(documentName).writePermissionDenied(error.reason ?? 'permission-denied')\n\n this.debuggerTool.log({\n direction: 'out',\n type: message.type,\n category: message.category,\n })\n\n // Ensure that the permission denied message is sent before the\n // connection is closed\n this.websocket.send(message.toUint8Array(), () => {\n if (Object.keys(this.documentConnections).length === 0) {\n try {\n this.websocket.close(error.code ?? Forbidden.code, error.reason ?? Forbidden.reason)\n } catch (closeError) {\n // catch is needed in case invalid error code is returned by hook (that would fail sending the close message)\n console.error(closeError)\n this.websocket.close(Forbidden.code, Forbidden.reason)\n }\n }\n })\n }\n\n // Catch errors due to failed decoding of data\n } catch (error) {\n console.error(error)\n this.websocket.close(Unauthorized.code, Unauthorized.reason)\n }\n }\n\n private messageHandler = async (data: Uint8Array) => {\n try {\n const tmpMsg = new SocketIncomingMessage(data)\n\n const documentName = decoding.readVarString(tmpMsg.decoder)\n\n if (this.documentConnections[documentName] === true) {\n // we already have a `Connection` set up for this document\n return\n }\n\n const isFirst = this.incomingMessageQueue[documentName] === undefined\n if (isFirst) {\n this.incomingMessageQueue[documentName] = []\n if (this.hookPayloads[documentName]) {\n throw new Error('first message, but hookPayloads exists')\n }\n\n const hookPayload = {\n instance: this.documentProvider as Hocuspocus,\n request: this.request,\n connection: {\n readOnly: false,\n requiresAuthentication: this.opts.requiresAuthentication,\n isAuthenticated: false,\n },\n requestHeaders: this.request.headers,\n requestParameters: getParameters(this.request),\n socketId: this.socketId,\n context: {},\n }\n\n this.hookPayloads[documentName] = hookPayload\n }\n this.handleQueueingMessage(data)\n\n if (isFirst) {\n const hookPayload = this.hookPayloads[documentName]\n // if this is the first message, trigger onConnect & check if we can start the connection (only if no auth is required)\n try {\n await this.hooks('onConnect', { ...hookPayload, documentName }, (contextAdditions: any) => {\n // merge context from all hooks\n hookPayload.context = { ...hookPayload.context, ...contextAdditions }\n })\n\n if (hookPayload.connection.requiresAuthentication || this.documentConnectionsEstablished.has(documentName)) {\n // Authentication is required, we’ll need to wait for the Authentication message.\n return\n }\n this.documentConnectionsEstablished.add(documentName)\n\n await this.setUpNewConnection(documentName)\n } catch (err: any) {\n // if a hook interrupts, close the websocket connection\n const error = err || Forbidden\n try {\n this.websocket.close(error.code ?? Forbidden.code, error.reason ?? Forbidden.reason)\n } catch (closeError) {\n // catch is needed in case invalid error code is returned by hook (that would fail sending the close message)\n console.error(closeError)\n this.websocket.close(Unauthorized.code, Unauthorized.reason)\n }\n }\n }\n } catch (closeError) {\n // catch is needed in case an invalid payload crashes the parsing of the Uint8Array\n console.error(closeError)\n this.websocket.close(Unauthorized.code, Unauthorized.reason)\n }\n }\n}\n","import { URLSearchParams } from 'url'\nimport Document from './Document.js'\nimport type { Hocuspocus } from './Hocuspocus.js'\n\nexport class DirectConnection {\n document: Document | null = null\n\n instance!: Hocuspocus\n\n context: any\n\n /**\n * Constructor.\n */\n constructor(\n document: Document,\n instance: Hocuspocus,\n context?: any,\n ) {\n this.document = document\n this.instance = instance\n this.context = context\n\n this.document.addDirectConnection()\n }\n\n async transact(transaction: (document: Document) => void) {\n if (!this.document) {\n throw new Error('direct connection closed')\n }\n\n transaction(this.document)\n\n this.instance.storeDocumentHooks(this.document, {\n clientsCount: this.document.getConnectionsCount(),\n context: this.context,\n document: this.document,\n documentName: this.document.name,\n instance: this.instance,\n requestHeaders: {},\n requestParameters: new URLSearchParams(),\n socketId: 'server',\n })\n }\n\n disconnect() {\n this.document?.removeDirectConnection()\n this.document = null\n }\n}\n","import { Server as HTTPServer, IncomingMessage, createServer } from 'http'\nimport { ListenOptions } from 'net'\nimport {\n ResetConnection, awarenessStatesToArray,\n} from '@hocuspocus/common'\nimport kleur from 'kleur'\nimport { v4 as uuid } from 'uuid'\nimport WebSocket, { AddressInfo, WebSocketServer } from 'ws'\nimport { Doc, applyUpdate, encodeStateAsUpdate } from 'yjs'\nimport meta from '../package.json' assert { type: 'json' }\nimport { ClientConnection } from './ClientConnection'\n// TODO: would be nice to only have a dependency on ClientConnection, and not on Connection\nimport Connection from './Connection.js'\nimport { Debugger } from './Debugger.js'\nimport { DirectConnection } from './DirectConnection.js'\nimport Document from './Document.js'\nimport {\n AwarenessUpdate,\n Configuration,\n ConnectionConfiguration,\n HookName,\n HookPayload,\n beforeBroadcastStatelessPayload,\n onChangePayload,\n onDisconnectPayload,\n onListenPayload,\n onStoreDocumentPayload,\n} from './types.js'\nimport { getParameters } from './util/getParameters'\n\nexport const defaultConfiguration = {\n name: null,\n port: 80,\n address: '0.0.0.0',\n timeout: 30000,\n debounce: 2000,\n maxDebounce: 10000,\n quiet: false,\n yDocOptions: {\n gc: true,\n gcFilter: () => true,\n },\n}\n\n/**\n * Hocuspocus Server\n */\nexport class Hocuspocus {\n configuration: Configuration = {\n ...defaultConfiguration,\n extensions: [],\n onConfigure: () => new Promise(r => r(null)),\n onListen: () => new Promise(r => r(null)),\n onUpgrade: () => new Promise(r => r(null)),\n onConnect: () => new Promise(r => r(null)),\n connected: () => new Promise(r => r(null)),\n beforeHandleMessage: () => new Promise(r => r(null)),\n beforeBroadcastStateless: () => new Promise(r => r(null)),\n onStateless: () => new Promise(r => r(null)),\n onChange: () => new Promise(r => r(null)),\n onLoadDocument: () => new Promise(r => r(null)),\n onStoreDocument: () => new Promise(r => r(null)),\n afterStoreDocument: () => new Promise(r => r(null)),\n onAwarenessUpdate: () => new Promise(r => r(null)),\n onRequest: () => new Promise(r => r(null)),\n onDisconnect: () => new Promise(r => r(null)),\n onDestroy: () => new Promise(r => r(null)),\n }\n\n documents: Map = new Map()\n\n httpServer?: HTTPServer\n\n webSocketServer?: WebSocketServer\n\n debugger = new Debugger()\n\n constructor(configuration?: Partial) {\n if (configuration) {\n this.configure(configuration)\n }\n }\n\n /**\n * Configure the server\n */\n configure(configuration: Partial): Hocuspocus {\n this.configuration = {\n ...this.configuration,\n ...configuration,\n }\n\n this.configuration.extensions.sort((a, b) => {\n const one = typeof a.priority === 'undefined' ? 100 : a.priority\n const two = typeof b.priority === 'undefined' ? 100 : b.priority\n\n if (one > two) {\n return -1\n }\n\n if (one < two) {\n return 1\n }\n\n return 0\n })\n\n this.configuration.extensions.push({\n onConfigure: this.configuration.onConfigure,\n onListen: this.configuration.onListen,\n onUpgrade: this.configuration.onUpgrade,\n onConnect: this.configuration.onConnect,\n connected: this.configuration.connected,\n onAuthenticate: this.configuration.onAuthenticate,\n onLoadDocument: this.configuration.onLoadDocument,\n beforeHandleMessage: this.configuration.beforeHandleMessage,\n beforeBroadcastStateless: this.configuration.beforeBroadcastStateless,\n onStateless: this.configuration.onStateless,\n onChange: this.configuration.onChange,\n onStoreDocument: this.configuration.onStoreDocument,\n afterStoreDocument: this.configuration.afterStoreDocument,\n onAwarenessUpdate: this.configuration.onAwarenessUpdate,\n onRequest: this.configuration.onRequest,\n onDisconnect: this.configuration.onDisconnect,\n onDestroy: this.configuration.onDestroy,\n })\n\n this.hooks('onConfigure', {\n configuration: this.configuration,\n version: meta.version,\n instance: this,\n })\n\n return this\n }\n\n get requiresAuthentication(): boolean {\n return !!this.configuration.extensions.find(extension => {\n return extension.onAuthenticate !== undefined\n })\n }\n\n /**\n * Start the server\n */\n async listen(\n portOrCallback: number | ((data: onListenPayload) => Promise) | null = null,\n callback: any = null,\n ): Promise {\n if (typeof portOrCallback === 'number') {\n this.configuration.port = portOrCallback\n }\n\n if (typeof portOrCallback === 'function') {\n this.configuration.extensions.push({\n onListen: portOrCallback,\n })\n }\n\n if (typeof callback === 'function') {\n this.configuration.extensions.push({\n onListen: callback,\n })\n }\n\n const webSocketServer = new WebSocketServer({ noServer: true })\n\n webSocketServer.on('connection', async (incoming: WebSocket, request: IncomingMessage) => {\n\n incoming.on('error', error => {\n /**\n * Handle a ws instance error, which is required to prevent\n * the server from crashing when one happens\n * See https://github.com/websockets/ws/issues/1777#issuecomment-660803472\n * @private\n */\n this.debugger.log('Error emitted from webSocket instance:')\n this.debugger.log(error)\n })\n\n this.handleConnection(incoming, request)\n })\n\n const server = createServer(async (request, response) => {\n try {\n await this.hooks('onRequest', { request, response, instance: this })\n\n // default response if all prior hooks don't interfere\n response.writeHead(200, { 'Content-Type': 'text/plain' })\n response.end('OK')\n } catch (error) {\n // if a hook rejects and the error is empty, do nothing\n // this is only meant to prevent later hooks and the\n // default handler to do something. if a error is present\n // just rethrow it\n if (error) {\n throw error\n }\n }\n })\n\n server.on('upgrade', async (request, socket, head) => {\n try {\n await this.hooks('onUpgrade', {\n request,\n socket,\n head,\n instance: this,\n })\n\n // let the default websocket server handle the connection if\n // prior hooks don't interfere\n webSocketServer.handleUpgrade(request, socket, head, ws => {\n webSocketServer.emit('connection', ws, request)\n })\n } catch (error) {\n // if a hook rejects and the error is empty, do nothing\n // this is only meant to prevent later hooks and the\n // default handler to do something. if a error is present\n // just rethrow it\n\n // TODO: why?\n if (error) {\n throw error\n }\n }\n })\n\n this.httpServer = server\n this.webSocketServer = webSocketServer\n\n return new Promise((resolve: Function, reject: Function) => {\n server.listen({\n port: this.configuration.port,\n host: this.configuration.address,\n } as ListenOptions, async () => {\n if (!this.configuration.quiet && process.env.NODE_ENV !== 'testing') {\n this.showStartScreen()\n }\n\n const onListenPayload = {\n instance: this,\n configuration: this.configuration,\n port: this.address.port,\n }\n\n try {\n await this.hooks('onListen', onListenPayload)\n resolve(this)\n } catch (e) {\n reject(e)\n }\n })\n })\n }\n\n get address(): AddressInfo {\n return (this.httpServer?.address() || {\n port: this.configuration.port,\n address: this.configuration.address,\n family: 'IPv4',\n }) as AddressInfo\n }\n\n get URL(): string {\n return `${this.configuration.address}:${this.address.port}`\n }\n\n get webSocketURL(): string {\n return `ws://${this.URL}`\n }\n\n get httpURL(): string {\n return `http://${this.URL}`\n }\n\n private showStartScreen() {\n const name = this.configuration.name ? ` (${this.configuration.name})` : ''\n\n console.log()\n console.log(` ${kleur.cyan(`Hocuspocus v${meta.version}${name}`)}${kleur.green(' running at:')}`)\n console.log()\n console.log(` > HTTP: ${kleur.cyan(`${this.httpURL}`)}`)\n console.log(` > WebSocket: ${this.webSocketURL}`)\n\n const extensions = this.configuration?.extensions.map(extension => {\n return extension.constructor?.name\n })\n .filter(name => name)\n .filter(name => name !== 'Object')\n\n if (!extensions.length) {\n return\n }\n\n console.log()\n console.log(' Extensions:')\n\n extensions\n .forEach(name => {\n console.log(` - ${name}`)\n })\n\n console.log()\n console.log(` ${kleur.green('Ready.')}`)\n console.log()\n }\n\n /**\n * Get the total number of active documents\n */\n getDocumentsCount(): number {\n return this.documents.size\n }\n\n /**\n * Get the total number of active connections\n */\n getConnectionsCount(): number {\n return Array.from(this.documents.values()).reduce((acc, document) => {\n acc += document.getConnectionsCount()\n return acc\n }, 0)\n }\n\n /**\n * Force close one or more connections\n */\n closeConnections(documentName?: string) {\n // Iterate through all connections for all documents\n // and invoke their close method, which is a graceful\n // disconnect wrapper around the underlying websocket.close\n this.documents.forEach((document: Document) => {\n // If a documentName was specified, bail if it doesnt match\n if (documentName && document.name !== documentName) {\n return\n }\n\n document.connections.forEach(({ connection }) => {\n connection.close(ResetConnection)\n })\n })\n }\n\n /**\n * Destroy the server\n */\n async destroy(): Promise {\n this.httpServer?.close()\n\n try {\n this.webSocketServer?.close()\n this.webSocketServer?.clients.forEach(client => {\n client.terminate()\n })\n } catch (error) {\n console.error(error)\n //\n }\n\n this.debugger.flush()\n\n await this.hooks('onDestroy', { instance: this })\n }\n\n /**\n * The `handleConnection` method receives incoming WebSocket connections,\n * runs all hooks:\n *\n * - onConnect for all connections\n * - onAuthenticate only if required\n *\n * … and if nothings fails it’ll fully establish the connection and\n * load the Document then.\n */\n handleConnection(incoming: WebSocket, request: IncomingMessage): void {\n const clientConnection = new ClientConnection(incoming, request, this, this.hooks.bind(this), this.debugger, {\n requiresAuthentication: this.requiresAuthentication,\n timeout: this.configuration.timeout,\n })\n clientConnection.onClose((document: Document, hookPayload: onDisconnectPayload) => {\n // Check if there are still no connections to the document, as these hooks\n // may take some time to resolve (e.g. database queries). If a\n // new connection were to come in during that time it would rely on the\n // document in the map that we remove now.\n if (document.getConnectionsCount() > 0) {\n return\n }\n\n // If it’s the last connection, we need to make sure to store the\n // document. Use the debounce helper, to clear running timers,\n // but make it run immediately (`true`).\n // Only run this if the document has finished loading earlier (i.e. not to persist the empty\n // ydoc if the onLoadDocument hook returned an error)\n if (!document.isLoading) {\n this.debounce(`onStoreDocument-${document.name}`, () => {\n this.storeDocumentHooks(document, hookPayload)\n }, true)\n } else {\n // Remove document from memory immediately\n this.documents.delete(document.name)\n document.destroy()\n }\n })\n }\n\n /**\n * Handle update of the given document\n */\n private handleDocumentUpdate(document: Document, connection: Connection | undefined, update: Uint8Array, request?: IncomingMessage): void {\n const hookPayload: onChangePayload | onStoreDocumentPayload = {\n instance: this,\n clientsCount: document.getConnectionsCount(),\n context: connection?.context || {},\n document,\n documentName: document.name,\n requestHeaders: request?.headers ?? {},\n requestParameters: getParameters(request),\n socketId: connection?.socketId ?? '',\n update,\n }\n\n this.hooks('onChange', hookPayload).catch(error => {\n // TODO: what's the intention of this catch -> throw?\n throw error\n })\n\n // If the update was received through other ways than the\n // WebSocket connection, we don’t need to feel responsible for\n // storing the content.\n if (!connection) {\n return\n }\n\n this.debounce(`onStoreDocument-${document.name}`, () => {\n this.storeDocumentHooks(document, hookPayload)\n })\n }\n\n timers: Map = new Map()\n\n /**\n * debounce the given function, using the given identifier\n */\n debounce(id: string, func: Function, immediately = false) {\n const old = this.timers.get(id)\n const start = old?.start || Date.now()\n\n const run = () => {\n this.timers.delete(id)\n func()\n }\n\n if (old?.timeout) {\n clearTimeout(old.timeout)\n }\n\n if (immediately) {\n return run()\n }\n\n if (Date.now() - start >= this.configuration.maxDebounce) {\n return run()\n }\n\n this.timers.set(id, {\n start,\n timeout: setTimeout(run, this.configuration.debounce),\n })\n }\n\n /**\n * Create a new document by the given request\n */\n public async createDocument(documentName: string, request: Partial>, socketId: string, connection: ConnectionConfiguration, context?: any): Promise {\n if (this.documents.has(documentName)) {\n const document = this.documents.get(documentName)\n\n if (document) {\n return document\n }\n }\n\n const document = new Document(documentName, this.debugger, this.configuration.yDocOptions)\n this.documents.set(documentName, document)\n\n const hookPayload = {\n instance: this,\n context,\n connection,\n document,\n documentName,\n socketId,\n requestHeaders: request.headers,\n requestParameters: getParameters(request),\n }\n\n try {\n await this.hooks('onLoadDocument', hookPayload, (loadedDocument: Doc | undefined) => {\n // if a hook returns a Y-Doc, encode the document state as update\n // and apply it to the newly created document\n // Note: instanceof doesn't work, because Doc !== Doc for some reason I don't understand\n if (\n loadedDocument?.constructor.name === 'Document'\n || loadedDocument?.constructor.name === 'Doc'\n ) {\n applyUpdate(document, encodeStateAsUpdate(loadedDocument))\n }\n })\n } catch (e) {\n this.closeConnections(documentName)\n this.documents.delete(documentName)\n throw e\n }\n\n document.isLoading = false\n await this.hooks('afterLoadDocument', hookPayload)\n\n document.onUpdate((document: Document, connection: Connection, update: Uint8Array) => {\n this.handleDocumentUpdate(document, connection, update, connection?.request)\n })\n\n document.beforeBroadcastStateless((document: Document, stateless: string) => {\n const hookPayload: beforeBroadcastStatelessPayload = {\n document,\n documentName: document.name,\n payload: stateless,\n }\n\n this.hooks('beforeBroadcastStateless', hookPayload)\n })\n\n document.awareness.on('update', (update: AwarenessUpdate) => {\n this.hooks('onAwarenessUpdate', {\n ...hookPayload,\n ...update,\n awareness: document.awareness,\n states: awarenessStatesToArray(document.awareness.getStates()),\n })\n })\n\n return document\n }\n\n storeDocumentHooks(document: Document, hookPayload: onStoreDocumentPayload) {\n this.hooks('onStoreDocument', hookPayload)\n .catch(error => {\n if (error?.message) {\n throw error\n }\n })\n .then(() => {\n this.hooks('afterStoreDocument', hookPayload).then(() => {\n // Remove document from memory.\n\n if (document.getConnectionsCount() > 0) {\n return\n }\n\n this.documents.delete(document.name)\n document.destroy()\n })\n })\n }\n\n /**\n * Run the given hook on all configured extensions.\n * Runs the given callback after each hook.\n */\n hooks(name: HookName, payload: HookPayload, callback: Function | null = null): Promise {\n const { extensions } = this.configuration\n\n // create a new `thenable` chain\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve\n let chain = Promise.resolve()\n\n extensions\n // get me all extensions which have the given hook\n .filter(extension => typeof extension[name] === 'function')\n // run through all the configured hooks\n .forEach(extension => {\n chain = chain\n .then(() => (extension[name] as any)?.(payload))\n .catch(error => {\n // make sure to log error messages\n if (error?.message) {\n console.error(`[${name}]`, error.message)\n }\n\n throw error\n })\n\n if (callback) {\n chain = chain.then((...args: any[]) => callback(...args))\n }\n })\n\n return chain\n }\n\n enableDebugging() {\n this.debugger.enable()\n }\n\n enableMessageLogging() {\n this.debugger.enable()\n this.debugger.verbose()\n }\n\n disableLogging() {\n this.debugger.quiet()\n }\n\n disableDebugging() {\n this.debugger.disable()\n }\n\n flushMessageLogs() {\n this.debugger.flush()\n\n return this\n }\n\n getMessageLogs() {\n return this.debugger.get()?.logs\n }\n\n async openDirectConnection(documentName: string, context?: any): Promise {\n const connectionConfig: ConnectionConfiguration = {\n isAuthenticated: true,\n readOnly: false,\n requiresAuthentication: true,\n }\n\n const document: Document = await this.createDocument(\n documentName,\n {}, // direct connection has no request params\n uuid(),\n connectionConfig,\n context,\n )\n\n return new DirectConnection(document, this, context)\n }\n}\n\nexport const Server = new Hocuspocus()\n"],"names":["create","length","object.length","object.hasProperty","map.create","string.fromCamelCase","conditions.undefinedToNull","storage.varStorage","f.isOneOf","buffer.createUint8ArrayViewFromArrayBuffer","binary.BITS7","binary.BIT8","math.floor","string.utf8TextEncoder","string.encodeUtf8","math.min","math.max","error.create","number.MAX_SAFE_INTEGER","string.utf8TextDecoder","map.setIfUndefined","set.create","array.from","time.getUnixTime","f.equalityDeep","encoding.createEncoder","encoding.writeVarUint","encoding.writeVarString","encoding.toUint8Array","decoding.createDecoder","decoding.readVarUint","decoding.readVarString","Y","encoding.writeVarUint8Array","decoding.readVarUint8Array","MessageType","writeAuthenticated","writePermissionDenied","AsyncLock","WsReadyStates","ConnectionTimeout","Forbidden","Doc","applyUpdate","encodeStateAsUpdate","URLSearchParams","uuid","SocketIncomingMessage","Unauthorized","WebSocketServer","createServer","kleur","ResetConnection","awarenessStatesToArray"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMA,QAAM,GAAG,MAAM,IAAI,GAAG;;ACNnC;AACA;AACA;AACA;AACA;AAsCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,IAAI,GAAG,KAAK,CAAC;;AClC1B;AACA;AACA;AACA;AACA,MAAM,WAAW,GAAG,CAAC,IAAI,CAAC,CAAC,WAAW,GAAE;AACxC;AACA,MAAM,aAAa,GAAG,QAAO;AAC7B;AACA;AACA;AACA;AACA;AACO,MAAM,QAAQ,GAAG,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,aAAa,EAAE,EAAE,EAAC;AACzD;AACA,MAAM,kBAAkB,GAAG,WAAU;AACrC;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,aAAa,GAAG,CAAC,CAAC,EAAE,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,kBAAkB,EAAE,KAAK,IAAI,CAAC,EAAE,SAAS,CAAC,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAC;AAQpI;AACA;AACA;AACA;AACA;AACO,MAAM,mBAAmB,GAAG,GAAG,IAAI;AAC1C,EAAE,MAAM,aAAa,GAAG,QAAQ,CAAC,kBAAkB,CAAC,GAAG,CAAC,EAAC;AACzD,EAAE,MAAM,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A;AACd,QAAA,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAA;AAErB,QAAA,OAAO,IAAI,CAAA;KACZ;IAED,cAAc,GAAA;;QACZ,OAAO,CAAA,EAAA,GAAA,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,MAAE,IAAA,IAAA,EAAA,KAAA,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,IAAI,CAAA;KACjC;AAED,IAAA,MAAM,oBAAoB,CAAC,YAAoB,EAAE,OAAa,EAAA;AAC5D,QAAA,MAAM,gBAAgB,GAA4B;AAChD,YAAA,eAAe,EAAE,IAAI;AACrB,YAAA,QAAQ,EAAE,KAAK;AACf,YAAA,sBAAsB,EAAE,IAAI;SAC7B,CAAA;QAED,MAAM,QAAQ,GAAa,MAAM,IAAI,CAAC,cAAc,CAClD,YAAY,EACZ,EAAE;AACF,QAAAP,OAAI,EAAE,EACN,gBAAgB,EAChB,OAAO,CACR,CAAA;QAED,OAAO,IAAI,gBAAgB,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAA;KACrD;AACF,CAAA;AAEY,MAAA,MAAM,GAAG,IAAI,UAAU;;;;;;;;;;;;"} -\ No newline at end of file -diff --git a/node_modules/@hocuspocus/server/dist/hocuspocus-server.esm.js b/node_modules/@hocuspocus/server/dist/hocuspocus-server.esm.js -index e48693b..544ad88 100644 ---- a/node_modules/@hocuspocus/server/dist/hocuspocus-server.esm.js -+++ b/node_modules/@hocuspocus/server/dist/hocuspocus-server.esm.js -@@ -1,18 +1,36 @@ - import AsyncLock from 'async-lock'; --import { writeAuthenticated, writePermissionDenied, WsReadyStates, ConnectionTimeout, Forbidden, ResetConnection, Unauthorized, awarenessStatesToArray } from '@hocuspocus/common'; -+import { writeAuthenticated, writePermissionDenied, WsReadyStates, ConnectionTimeout, Forbidden, Unauthorized, ResetConnection, awarenessStatesToArray } from '@hocuspocus/common'; - import * as Y from 'yjs'; - import { Doc, applyUpdate, encodeStateAsUpdate } from 'yjs'; - import { createServer } from 'http'; --import { URLSearchParams } from 'url'; --import { WebSocketServer } from 'ws'; --import { v4 } from 'uuid'; - import kleur from 'kleur'; -+import { v4 } from 'uuid'; -+import { WebSocketServer } from 'ws'; -+import { URLSearchParams } from 'url'; -+ -+/** -+ * Utility module to work with sets. -+ * -+ * @module set -+ */ -+ -+const create$2 = () => new Set(); -+ -+/** -+ * Utility module to work with Arrays. -+ * -+ * @module array -+ */ - - /** -- * Utility module to work with strings. -+ * Transforms something array-like to an actual Array. - * -- * @module string -+ * @function -+ * @template T -+ * @param {ArrayLike|Iterable} arraylike -+ * @return {T} - */ -+const from = Array.from; - - /** - * @param {string} s -@@ -95,7 +113,7 @@ if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) { - * - * @function - */ --const create$2 = () => new Map(); -+const create$1 = () => new Map(); - - /** - * Get map property. Create T if property is undefined and set T on map. -@@ -190,30 +208,6 @@ try { - /* c8 ignore next */ - const varStorage = _localStorage; - --/** -- * Utility module to work with sets. -- * -- * @module set -- */ -- --const create$1 = () => new Set(); -- --/** -- * Utility module to work with Arrays. -- * -- * @module array -- */ -- --/** -- * Transforms something array-like to an actual Array. -- * -- * @function -- * @template T -- * @param {ArrayLike|Iterable} arraylike -- * @return {T} -- */ --const from = Array.from; -- - /** - * Utility functions for working with EcmaScript objects. - * -@@ -345,7 +339,6 @@ const equalityDeep = (a, b) => { - */ - // @ts-ignore - const isOneOf = (value, options) => options.includes(value); --/* c8 ignore stop */ - - /** - * Isomorphic module to work access the environment (query params, env variables). -@@ -371,7 +364,7 @@ let params; - const computeParams = () => { - if (params === undefined) { - if (isNode) { -- params = create$2(); -+ params = create$1(); - const pargs = process.argv; - let currParamName = null; - for (let i = 0; i < pargs.length; i++) { -@@ -393,7 +386,7 @@ const computeParams = () => { - } - // in ReactNative for example this would not be true (unless connected to the Remote Debugger) - } else if (typeof location === 'object') { -- params = create$2(); // eslint-disable-next-line no-undef -+ params = create$1(); // eslint-disable-next-line no-undef - (location.search || '?').slice(1).split('&').forEach((kv) => { - if (kv.length !== 0) { - const [key, value] = kv.split('='); -@@ -402,7 +395,7 @@ const computeParams = () => { - } - }); - } else { -- params = create$2(); -+ params = create$1(); - } - } - return params -@@ -939,109 +932,6 @@ class IncomingMessage { - } - } - --/** -- * @module sync-protocol -- */ -- --/** -- * @typedef {Map} StateMap -- */ -- --/** -- * Core Yjs defines two message types: -- * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2. -- * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it -- * received all information from the remote client. -- * -- * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection -- * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both -- * SyncStep2 and SyncDone, it is assured that it is synced to the remote client. -- * -- * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1. -- * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies -- * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the -- * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can -- * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them. -- * Therefore it is necesarry that the client initiates the sync. -- * -- * Construction of a message: -- * [messageType : varUint, message definition..] -- * -- * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol! -- * -- * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer) -- */ -- --const messageYjsSyncStep1 = 0; --const messageYjsSyncStep2 = 1; --const messageYjsUpdate = 2; -- --/** -- * Create a sync step 1 message based on the state of the current shared document. -- * -- * @param {encoding.Encoder} encoder -- * @param {Y.Doc} doc -- */ --const writeSyncStep1 = (encoder, doc) => { -- writeVarUint(encoder, messageYjsSyncStep1); -- const sv = Y.encodeStateVector(doc); -- writeVarUint8Array(encoder, sv); --}; -- --/** -- * @param {encoding.Encoder} encoder -- * @param {Y.Doc} doc -- * @param {Uint8Array} [encodedStateVector] -- */ --const writeSyncStep2 = (encoder, doc, encodedStateVector) => { -- writeVarUint(encoder, messageYjsSyncStep2); -- writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector)); --}; -- --/** -- * Read SyncStep1 message and reply with SyncStep2. -- * -- * @param {decoding.Decoder} decoder The reply to the received message -- * @param {encoding.Encoder} encoder The received message -- * @param {Y.Doc} doc -- */ --const readSyncStep1 = (decoder, encoder, doc) => -- writeSyncStep2(encoder, doc, readVarUint8Array(decoder)); -- --/** -- * Read and apply Structs and then DeleteStore to a y instance. -- * -- * @param {decoding.Decoder} decoder -- * @param {Y.Doc} doc -- * @param {any} transactionOrigin -- */ --const readSyncStep2 = (decoder, doc, transactionOrigin) => { -- try { -- Y.applyUpdate(doc, readVarUint8Array(decoder), transactionOrigin); -- } catch (error) { -- // This catches errors that are thrown by event handlers -- console.error('Caught error while handling a Yjs update', error); -- } --}; -- --/** -- * @param {encoding.Encoder} encoder -- * @param {Uint8Array} update -- */ --const writeUpdate = (encoder, update) => { -- writeVarUint(encoder, messageYjsUpdate); -- writeVarUint8Array(encoder, update); --}; -- --/** -- * Read and apply Structs and then DeleteStore to a y instance. -- * -- * @param {decoding.Decoder} decoder -- * @param {Y.Doc} doc -- * @param {any} transactionOrigin -- */ --const readUpdate = readSyncStep2; -- - /** - * Utility module to work with time. - * -@@ -1072,7 +962,7 @@ class Observable { - * Some desc. - * @type {Map} - */ -- this._observers = create$2(); -+ this._observers = create$1(); - } - - /** -@@ -1080,7 +970,7 @@ class Observable { - * @param {function} f - */ - on (name, f) { -- setIfUndefined(this._observers, name, create$1).add(f); -+ setIfUndefined(this._observers, name, create$2).add(f); - } - - /** -@@ -1123,11 +1013,11 @@ class Observable { - */ - emit (name, args) { - // 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. -- return from((this._observers.get(name) || create$2()).values()).forEach(f => f(...args)) -+ return from((this._observers.get(name) || create$1()).values()).forEach(f => f(...args)) - } - - destroy () { -- this._observers = create$2(); -+ this._observers = create$1(); - } - } - -@@ -1392,6 +1282,109 @@ const applyAwarenessUpdate = (awareness, update, origin) => { - } - }; - -+/** -+ * @module sync-protocol -+ */ -+ -+/** -+ * @typedef {Map} StateMap -+ */ -+ -+/** -+ * Core Yjs defines two message types: -+ * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2. -+ * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it -+ * received all information from the remote client. -+ * -+ * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection -+ * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both -+ * SyncStep2 and SyncDone, it is assured that it is synced to the remote client. -+ * -+ * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1. -+ * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies -+ * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the -+ * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can -+ * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them. -+ * Therefore it is necesarry that the client initiates the sync. -+ * -+ * Construction of a message: -+ * [messageType : varUint, message definition..] -+ * -+ * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol! -+ * -+ * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer) -+ */ -+ -+const messageYjsSyncStep1 = 0; -+const messageYjsSyncStep2 = 1; -+const messageYjsUpdate = 2; -+ -+/** -+ * Create a sync step 1 message based on the state of the current shared document. -+ * -+ * @param {encoding.Encoder} encoder -+ * @param {Y.Doc} doc -+ */ -+const writeSyncStep1 = (encoder, doc) => { -+ writeVarUint(encoder, messageYjsSyncStep1); -+ const sv = Y.encodeStateVector(doc); -+ writeVarUint8Array(encoder, sv); -+}; -+ -+/** -+ * @param {encoding.Encoder} encoder -+ * @param {Y.Doc} doc -+ * @param {Uint8Array} [encodedStateVector] -+ */ -+const writeSyncStep2 = (encoder, doc, encodedStateVector) => { -+ writeVarUint(encoder, messageYjsSyncStep2); -+ writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector)); -+}; -+ -+/** -+ * Read SyncStep1 message and reply with SyncStep2. -+ * -+ * @param {decoding.Decoder} decoder The reply to the received message -+ * @param {encoding.Encoder} encoder The received message -+ * @param {Y.Doc} doc -+ */ -+const readSyncStep1 = (decoder, encoder, doc) => -+ writeSyncStep2(encoder, doc, readVarUint8Array(decoder)); -+ -+/** -+ * Read and apply Structs and then DeleteStore to a y instance. -+ * -+ * @param {decoding.Decoder} decoder -+ * @param {Y.Doc} doc -+ * @param {any} transactionOrigin -+ */ -+const readSyncStep2 = (decoder, doc, transactionOrigin) => { -+ try { -+ Y.applyUpdate(doc, readVarUint8Array(decoder), transactionOrigin); -+ } catch (error) { -+ // This catches errors that are thrown by event handlers -+ console.error('Caught error while handling a Yjs update', error); -+ } -+}; -+ -+/** -+ * @param {encoding.Encoder} encoder -+ * @param {Uint8Array} update -+ */ -+const writeUpdate = (encoder, update) => { -+ writeVarUint(encoder, messageYjsUpdate); -+ writeVarUint8Array(encoder, update); -+}; -+ -+/** -+ * Read and apply Structs and then DeleteStore to a y instance. -+ * -+ * @param {decoding.Decoder} decoder -+ * @param {Y.Doc} doc -+ * @param {any} transactionOrigin -+ */ -+const readUpdate = readSyncStep2; -+ - var MessageType; - (function (MessageType) { - MessageType[MessageType["Unknown"] = -1] = "Unknown"; -@@ -1403,6 +1396,7 @@ var MessageType; - MessageType[MessageType["Stateless"] = 5] = "Stateless"; - MessageType[MessageType["BroadcastStateless"] = 6] = "BroadcastStateless"; - MessageType[MessageType["CLOSE"] = 7] = "CLOSE"; -+ MessageType[MessageType["SyncStatus"] = 8] = "SyncStatus"; - })(MessageType || (MessageType = {})); - - class OutgoingMessage { -@@ -1470,7 +1464,14 @@ class OutgoingMessage { - writeVarString(this.encoder, payload); - return this; - } -- toUint8Array() { -+ // TODO: should this be write* or create* as method name? -+ writeSyncStatus(updateSaved) { -+ this.category = 'SyncStatus'; -+ writeVarUint(this.encoder, MessageType.SyncStatus); -+ writeVarUint(this.encoder, updateSaved ? 1 : 0); -+ return this; -+ } -+ toUint8Array() { - return toUint8Array(this.encoder); - } - } -@@ -1593,9 +1594,32 @@ class MessageReceiver { - category: 'SyncStep2', - }); - if (connection === null || connection === void 0 ? void 0 : connection.readOnly) { -+ // We're in read-only mode, so we can't apply the update. -+ // Let's use snapshotContainsUpdate to see if the update actually contains changes. -+ // If not, we can still ack the update -+ const snapshot = Y.snapshot(document); -+ const update = readVarUint8Array(message.decoder); -+ if (Y.snapshotContainsUpdate(snapshot, update)) { -+ // no new changes in update -+ const ackMessage = new OutgoingMessage(document.name) -+ .writeSyncStatus(true); -+ connection.send(ackMessage.toUint8Array()); -+ } -+ else { -+ // new changes in update that we can't apply, because readOnly -+ const ackMessage = new OutgoingMessage(document.name) -+ .writeSyncStatus(false); -+ connection.send(ackMessage.toUint8Array()); -+ } - break; - } - readSyncStep2(message.decoder, document, connection); -+ if (connection) { -+ // TODO: how should this work if connection is not set? should we use reply? -+ // reply is used by redis, but I'm unsure how that code path works -+ connection.send(new OutgoingMessage(document.name) -+ .writeSyncStatus(true).toUint8Array()); -+ } - break; - case messageYjsUpdate: - this.logger.log({ -@@ -1604,9 +1628,17 @@ class MessageReceiver { - category: 'Update', - }); - if (connection === null || connection === void 0 ? void 0 : connection.readOnly) { -+ connection.send(new OutgoingMessage(document.name) -+ .writeSyncStatus(false).toUint8Array()); - break; - } - readUpdate(message.decoder, document, connection); -+ if (connection) { -+ // TODO: how should this work if connection is not set? should we use reply? -+ // reply is used by redis, but I'm unsure how that code path works -+ connection.send(new OutgoingMessage(document.name) -+ .writeSyncStatus(true).toUint8Array()); -+ } - break; - default: - throw new Error(`Received a message with an unknown type: ${type}`); -@@ -2101,7 +2133,7 @@ var devDependencies = { - }; - var peerDependencies = { - "y-protocols": "^1.0.5", -- yjs: "^13.5.29" -+ yjs: "^13.6.4" - }; - var gitHead = "b3454a4ca289a84ddfb7fa5607a2d4b8d5c37e9d"; - var meta = { -@@ -2123,6 +2155,297 @@ var meta = { - gitHead: gitHead - }; - -+/** -+ * Get parameters by the given request -+ */ -+function getParameters(request) { -+ var _a; -+ const query = ((_a = request === null || request === void 0 ? void 0 : request.url) === null || _a === void 0 ? void 0 : _a.split('?')) || []; -+ return new URLSearchParams(query[1] ? query[1] : ''); -+} -+ -+/** -+ * The `ClientConnection` class is responsible for handling an incoming WebSocket -+ * -+ * TODO-refactor: -+ * - use event handlers instead of calling hooks directly, hooks should probably be called from Hocuspocus.ts -+ */ -+class ClientConnection { -+ /** -+ * The `ClientConnection` class receives incoming WebSocket connections, -+ * runs all hooks: -+ * -+ * - onConnect for all connections -+ * - onAuthenticate only if required -+ * -+ * … and if nothings fails it’ll fully establish the connection and -+ * load the Document then. -+ */ -+ constructor(websocket, request, documentProvider, -+ // TODO: change to events -+ hooks, debuggerTool, opts) { -+ this.websocket = websocket; -+ this.request = request; -+ this.documentProvider = documentProvider; -+ this.hooks = hooks; -+ this.debuggerTool = debuggerTool; -+ this.opts = opts; -+ // this map indicates whether a `Connection` instance has already taken over for incoming message for the key (i.e. documentName) -+ this.documentConnections = {}; -+ // While the connection will be establishing messages will -+ // be queued and handled later. -+ this.incomingMessageQueue = {}; -+ // While the connection is establishing, kee -+ this.documentConnectionsEstablished = new Set(); -+ // hooks payload by Document -+ this.hookPayloads = {}; -+ this.callbacks = { -+ onClose: [(document, payload) => { }], -+ }; -+ // Every new connection gets a unique identifier. -+ this.socketId = v4(); -+ // Once all hooks are run, we’ll fully establish the connection: -+ this.setUpNewConnection = async (documentName) => { -+ // Not an idle connection anymore, no need to close it then. -+ clearTimeout(this.closeIdleConnectionTimeout); -+ const hookPayload = this.hookPayloads[documentName]; -+ // If no hook interrupts, create a document and connection -+ const document = await this.documentProvider.createDocument(documentName, hookPayload.request, hookPayload.socketId, hookPayload.connection, hookPayload.context); -+ const instance = this.createConnection(this.websocket, document); -+ instance.onClose((document, event) => { -+ delete this.hookPayloads[documentName]; -+ delete this.documentConnections[documentName]; -+ delete this.incomingMessageQueue[documentName]; -+ this.documentConnectionsEstablished.delete(documentName); -+ if (Object.keys(this.documentConnections).length === 0) { -+ instance.webSocket.close(event === null || event === void 0 ? void 0 : event.code, event === null || event === void 0 ? void 0 : event.reason); // TODO: Move this to Hocuspocus connection handler -+ } -+ }); -+ this.documentConnections[documentName] = true; -+ // There’s no need to queue messages anymore. -+ // Let’s work through queued messages. -+ this.incomingMessageQueue[documentName].forEach(input => { -+ this.websocket.emit('message', input); -+ }); -+ this.hooks('connected', { -+ ...hookPayload, -+ documentName, -+ context: hookPayload.context, -+ connectionInstance: instance, -+ }); -+ }; -+ // This listener handles authentication messages and queues everything else. -+ this.handleQueueingMessage = async (data) => { -+ var _a; -+ try { -+ const tmpMsg = new IncomingMessage(data); -+ const documentName = readVarString(tmpMsg.decoder); -+ const type = readVarUint(tmpMsg.decoder); -+ if (!(type === MessageType.Auth && !this.documentConnectionsEstablished.has(documentName))) { -+ this.incomingMessageQueue[documentName].push(data); -+ return; -+ } -+ // Okay, we’ve got the authentication message we’re waiting for: -+ this.documentConnectionsEstablished.add(documentName); -+ // The 2nd integer contains the submessage type -+ // which will always be authentication when sent from client -> server -+ readVarUint(tmpMsg.decoder); -+ const token = readVarString(tmpMsg.decoder); -+ this.debuggerTool.log({ -+ direction: 'in', -+ type, -+ category: 'Token', -+ }); -+ try { -+ const hookPayload = this.hookPayloads[documentName]; -+ await this.hooks('onAuthenticate', { -+ token, -+ ...hookPayload, -+ documentName, -+ }, (contextAdditions) => { -+ // Hooks are allowed to give us even more context and we’ll merge everything together. -+ // We’ll pass the context to other hooks then. -+ hookPayload.context = { ...hookPayload.context, ...contextAdditions }; -+ }); -+ // All `onAuthenticate` hooks passed. -+ hookPayload.connection.isAuthenticated = true; -+ // Let the client know that authentication was successful. -+ const message = new OutgoingMessage(documentName).writeAuthenticated(hookPayload.connection.readOnly); -+ this.debuggerTool.log({ -+ direction: 'out', -+ type: message.type, -+ category: message.category, -+ }); -+ this.websocket.send(message.toUint8Array()); -+ // Time to actually establish the connection. -+ await this.setUpNewConnection(documentName); -+ } -+ catch (err) { -+ const error = err || Forbidden; -+ const message = new OutgoingMessage(documentName).writePermissionDenied((_a = error.reason) !== null && _a !== void 0 ? _a : 'permission-denied'); -+ this.debuggerTool.log({ -+ direction: 'out', -+ type: message.type, -+ category: message.category, -+ }); -+ // Ensure that the permission denied message is sent before the -+ // connection is closed -+ this.websocket.send(message.toUint8Array(), () => { -+ var _a, _b; -+ if (Object.keys(this.documentConnections).length === 0) { -+ try { -+ this.websocket.close((_a = error.code) !== null && _a !== void 0 ? _a : Forbidden.code, (_b = error.reason) !== null && _b !== void 0 ? _b : Forbidden.reason); -+ } -+ catch (closeError) { -+ // catch is needed in case invalid error code is returned by hook (that would fail sending the close message) -+ console.error(closeError); -+ this.websocket.close(Forbidden.code, Forbidden.reason); -+ } -+ } -+ }); -+ } -+ // Catch errors due to failed decoding of data -+ } -+ catch (error) { -+ console.error(error); -+ this.websocket.close(Unauthorized.code, Unauthorized.reason); -+ } -+ }; -+ this.messageHandler = async (data) => { -+ var _a, _b; -+ try { -+ const tmpMsg = new IncomingMessage(data); -+ const documentName = readVarString(tmpMsg.decoder); -+ if (this.documentConnections[documentName] === true) { -+ // we already have a `Connection` set up for this document -+ return; -+ } -+ const isFirst = this.incomingMessageQueue[documentName] === undefined; -+ if (isFirst) { -+ this.incomingMessageQueue[documentName] = []; -+ if (this.hookPayloads[documentName]) { -+ throw new Error('first message, but hookPayloads exists'); -+ } -+ const hookPayload = { -+ instance: this.documentProvider, -+ request: this.request, -+ connection: { -+ readOnly: false, -+ requiresAuthentication: this.opts.requiresAuthentication, -+ isAuthenticated: false, -+ }, -+ requestHeaders: this.request.headers, -+ requestParameters: getParameters(this.request), -+ socketId: this.socketId, -+ context: {}, -+ }; -+ this.hookPayloads[documentName] = hookPayload; -+ } -+ this.handleQueueingMessage(data); -+ if (isFirst) { -+ const hookPayload = this.hookPayloads[documentName]; -+ // if this is the first message, trigger onConnect & check if we can start the connection (only if no auth is required) -+ try { -+ await this.hooks('onConnect', { ...hookPayload, documentName }, (contextAdditions) => { -+ // merge context from all hooks -+ hookPayload.context = { ...hookPayload.context, ...contextAdditions }; -+ }); -+ if (hookPayload.connection.requiresAuthentication || this.documentConnectionsEstablished.has(documentName)) { -+ // Authentication is required, we’ll need to wait for the Authentication message. -+ return; -+ } -+ this.documentConnectionsEstablished.add(documentName); -+ await this.setUpNewConnection(documentName); -+ } -+ catch (err) { -+ // if a hook interrupts, close the websocket connection -+ const error = err || Forbidden; -+ try { -+ this.websocket.close((_a = error.code) !== null && _a !== void 0 ? _a : Forbidden.code, (_b = error.reason) !== null && _b !== void 0 ? _b : Forbidden.reason); -+ } -+ catch (closeError) { -+ // catch is needed in case invalid error code is returned by hook (that would fail sending the close message) -+ console.error(closeError); -+ this.websocket.close(Unauthorized.code, Unauthorized.reason); -+ } -+ } -+ } -+ } -+ catch (closeError) { -+ // catch is needed in case an invalid payload crashes the parsing of the Uint8Array -+ console.error(closeError); -+ this.websocket.close(Unauthorized.code, Unauthorized.reason); -+ } -+ }; -+ // Make sure to close an idle connection after a while. -+ this.closeIdleConnectionTimeout = setTimeout(() => { -+ websocket.close(Unauthorized.code, Unauthorized.reason); -+ }, opts.timeout); -+ websocket.on('message', this.messageHandler); -+ } -+ /** -+ * Set a callback that will be triggered when the connection is closed -+ */ -+ onClose(callback) { -+ this.callbacks.onClose.push(callback); -+ return this; -+ } -+ /** -+ * Create a new connection by the given request and document -+ */ -+ createConnection(connection, document) { -+ const hookPayload = this.hookPayloads[document.name]; -+ const instance = new Connection(connection, hookPayload.request, document, this.opts.timeout, hookPayload.socketId, hookPayload.context, hookPayload.connection.readOnly, this.debuggerTool); -+ instance.onClose(async (document, event) => { -+ const disconnectHookPayload = { -+ instance: this.documentProvider, -+ clientsCount: document.getConnectionsCount(), -+ context: hookPayload.context, -+ document, -+ socketId: hookPayload.socketId, -+ documentName: document.name, -+ requestHeaders: hookPayload.request.headers, -+ requestParameters: getParameters(hookPayload.request), -+ }; -+ await this.hooks('onDisconnect', hookPayload); -+ this.callbacks.onClose.forEach((callback => callback(document, disconnectHookPayload))); -+ }); -+ instance.onStatelessCallback(async (payload) => { -+ try { -+ return await this.hooks('onStateless', payload); -+ } -+ catch (error) { -+ // TODO: weird pattern, what's the use of this? -+ if (error === null || error === void 0 ? void 0 : error.message) { -+ throw error; -+ } -+ } -+ }); -+ instance.beforeHandleMessage((connection, update) => { -+ const beforeHandleMessagePayload = { -+ instance: this.documentProvider, -+ clientsCount: document.getConnectionsCount(), -+ context: hookPayload.context, -+ document, -+ socketId: hookPayload.socketId, -+ connection, -+ documentName: document.name, -+ requestHeaders: hookPayload.request.headers, -+ requestParameters: getParameters(hookPayload.request), -+ update, -+ }; -+ return this.hooks('beforeHandleMessage', beforeHandleMessagePayload); -+ }); -+ // If the WebSocket has already disconnected (wow, that was fast) – then -+ // immediately call close to cleanup the connection and document in memory. -+ if (connection.readyState === WsReadyStates.Closing -+ || connection.readyState === WsReadyStates.Closed) { -+ instance.close(); -+ } -+ return instance; -+ } -+} -+ - class DirectConnection { - /** - * Constructor. -@@ -2283,14 +2606,14 @@ class Hocuspocus { - }); - this.handleConnection(incoming, request); - }); -- const server = createServer((request, response) => { -- this.hooks('onRequest', { request, response, instance: this }) -- .then(() => { -+ const server = createServer(async (request, response) => { -+ try { -+ await this.hooks('onRequest', { request, response, instance: this }); - // default response if all prior hooks don't interfere - response.writeHead(200, { 'Content-Type': 'text/plain' }); - response.end('OK'); -- }) -- .catch(error => { -+ } -+ catch (error) { - // if a hook rejects and the error is empty, do nothing - // this is only meant to prevent later hooks and the - // default handler to do something. if a error is present -@@ -2298,31 +2621,32 @@ class Hocuspocus { - if (error) { - throw error; - } -- }); -+ } - }); -- server.on('upgrade', (request, socket, head) => { -- this.hooks('onUpgrade', { -- request, -- socket, -- head, -- instance: this, -- }) -- .then(() => { -+ server.on('upgrade', async (request, socket, head) => { -+ try { -+ await this.hooks('onUpgrade', { -+ request, -+ socket, -+ head, -+ instance: this, -+ }); - // let the default websocket server handle the connection if - // prior hooks don't interfere - webSocketServer.handleUpgrade(request, socket, head, ws => { - webSocketServer.emit('connection', ws, request); - }); -- }) -- .catch(error => { -+ } -+ catch (error) { - // if a hook rejects and the error is empty, do nothing - // this is only meant to prevent later hooks and the - // default handler to do something. if a error is present - // just rethrow it -+ // TODO: why? - if (error) { - throw error; - } -- }); -+ } - }); - this.httpServer = server; - this.webSocketServer = webSocketServer; -@@ -2330,7 +2654,7 @@ class Hocuspocus { - server.listen({ - port: this.configuration.port, - host: this.configuration.address, -- }, () => { -+ }, async () => { - if (!this.configuration.quiet && process.env.NODE_ENV !== 'testing') { - this.showStartScreen(); - } -@@ -2339,9 +2663,13 @@ class Hocuspocus { - configuration: this.configuration, - port: this.address.port, - }; -- this.hooks('onListen', onListenPayload) -- .then(() => resolve(this)) -- .catch(error => reject(error)); -+ try { -+ await this.hooks('onListen', onListenPayload); -+ resolve(this); -+ } -+ catch (e) { -+ reject(e); -+ } - }); - }); - } -@@ -2448,188 +2776,35 @@ class Hocuspocus { - * … and if nothings fails it’ll fully establish the connection and - * load the Document then. - */ -- handleConnection(incoming, request, context = null) { -- // Make sure to close an idle connection after a while. -- const closeIdleConnection = setTimeout(() => { -- incoming.close(Unauthorized.code, Unauthorized.reason); -- }, this.configuration.timeout); -- // Every new connection gets a unique identifier. -- const socketId = v4(); -- // To override settings for specific connections, we’ll -- // keep track of a few things in the `ConnectionConfiguration`. -- const connection = { -- readOnly: false, -+ handleConnection(incoming, request) { -+ const clientConnection = new ClientConnection(incoming, request, this, this.hooks.bind(this), this.debugger, { - requiresAuthentication: this.requiresAuthentication, -- isAuthenticated: false, -- }; -- // The `onConnect` and `onAuthenticate` hooks need some context -- // to decide who’s connecting, so let’s put it together: -- const hookPayload = { -- instance: this, -- request, -- requestHeaders: request.headers, -- requestParameters: Hocuspocus.getParameters(request), -- socketId, -- connection, -- }; -- // this map indicates whether a `Connection` instance has already taken over for incoming message for the key (i.e. documentName) -- const documentConnections = {}; -- // While the connection will be establishing messages will -- // be queued and handled later. -- const incomingMessageQueue = {}; -- // While the connection is establishing -- const connectionEstablishing = {}; -- // Once all hooks are run, we’ll fully establish the connection: -- const setUpNewConnection = async (documentName) => { -- // Not an idle connection anymore, no need to close it then. -- clearTimeout(closeIdleConnection); -- // If no hook interrupts, create a document and connection -- const document = await this.createDocument(documentName, request, socketId, connection, context); -- const instance = this.createConnection(incoming, request, document, socketId, connection.readOnly, context); -- instance.onClose((document, event) => { -- delete documentConnections[documentName]; -- delete incomingMessageQueue[documentName]; -- delete connectionEstablishing[documentName]; -- if (Object.keys(documentConnections).length === 0) { -- instance.webSocket.close(event === null || event === void 0 ? void 0 : event.code, event === null || event === void 0 ? void 0 : event.reason); // TODO: Move this to Hocuspocus connection handler -- } -- }); -- documentConnections[documentName] = true; -- // There’s no need to queue messages anymore. -- // Let’s work through queued messages. -- incomingMessageQueue[documentName].forEach(input => { -- incoming.emit('message', input); -- }); -- this.hooks('connected', { -- ...hookPayload, -- documentName, -- context, -- connectionInstance: instance, -- }); -- }; -- // This listener handles authentication messages and queues everything else. -- const handleQueueingMessage = (data) => { -- try { -- const tmpMsg = new IncomingMessage(data); -- const documentName = readVarString(tmpMsg.decoder); -- const type = readVarUint(tmpMsg.decoder); -- // Okay, we’ve got the authentication message we’re waiting for: -- if (type === MessageType.Auth && !connectionEstablishing[documentName]) { -- connectionEstablishing[documentName] = true; -- // The 2nd integer contains the submessage type -- // which will always be authentication when sent from client -> server -- readVarUint(tmpMsg.decoder); -- const token = readVarString(tmpMsg.decoder); -- this.debugger.log({ -- direction: 'in', -- type, -- category: 'Token', -- }); -- this.hooks('onAuthenticate', { -- token, -- ...hookPayload, -- documentName, -- }, (contextAdditions) => { -- // Hooks are allowed to give us even more context and we’ll merge everything together. -- // We’ll pass the context to other hooks then. -- context = { ...context, ...contextAdditions }; -- }) -- .then(() => { -- // All `onAuthenticate` hooks passed. -- connection.isAuthenticated = true; -- // Let the client know that authentication was successful. -- const message = new OutgoingMessage(documentName).writeAuthenticated(connection.readOnly); -- this.debugger.log({ -- direction: 'out', -- type: message.type, -- category: message.category, -- }); -- incoming.send(message.toUint8Array()); -- }) -- .then(() => { -- // Time to actually establish the connection. -- return setUpNewConnection(documentName); -- }) -- .catch((error = Forbidden) => { -- var _a; -- const message = new OutgoingMessage(documentName).writePermissionDenied((_a = error.reason) !== null && _a !== void 0 ? _a : 'permission-denied'); -- this.debugger.log({ -- direction: 'out', -- type: message.type, -- category: message.category, -- }); -- // Ensure that the permission denied message is sent before the -- // connection is closed -- incoming.send(message.toUint8Array(), () => { -- var _a, _b; -- if (Object.keys(documentConnections).length === 0) { -- try { -- incoming.close((_a = error.code) !== null && _a !== void 0 ? _a : Forbidden.code, (_b = error.reason) !== null && _b !== void 0 ? _b : Forbidden.reason); -- } -- catch (closeError) { -- // catch is needed in case invalid error code is returned by hook (that would fail sending the close message) -- console.error(closeError); -- incoming.close(Forbidden.code, Forbidden.reason); -- } -- } -- }); -- }); -- } -- else { -- incomingMessageQueue[documentName].push(data); -- } -- // Catch errors due to failed decoding of data -- } -- catch (error) { -- console.error(error); -- incoming.close(Unauthorized.code, Unauthorized.reason); -+ timeout: this.configuration.timeout, -+ }); -+ clientConnection.onClose((document, hookPayload) => { -+ // Check if there are still no connections to the document, as these hooks -+ // may take some time to resolve (e.g. database queries). If a -+ // new connection were to come in during that time it would rely on the -+ // document in the map that we remove now. -+ if (document.getConnectionsCount() > 0) { -+ return; - } -- }; -- const messageHandler = (data) => { -- try { -- const tmpMsg = new IncomingMessage(data); -- const documentName = readVarString(tmpMsg.decoder); -- if (documentConnections[documentName] === true) { -- // we already have a `Connection` set up for this document -- return; -- } -- // if this is the first message, trigger onConnect & check if we can start the connection (only if no auth is required) -- if (incomingMessageQueue[documentName] === undefined) { -- incomingMessageQueue[documentName] = []; -- this.hooks('onConnect', { ...hookPayload, documentName }, (contextAdditions) => { -- // merge context from all hooks -- context = { ...context, ...contextAdditions }; -- }) -- .then(() => { -- // Authentication is required, we’ll need to wait for the Authentication message. -- if (connection.requiresAuthentication || connectionEstablishing[documentName]) { -- return; -- } -- connectionEstablishing[documentName] = true; -- return setUpNewConnection(documentName); -- }) -- .catch((error = Forbidden) => { -- var _a, _b; -- // if a hook interrupts, close the websocket connection -- try { -- incoming.close((_a = error.code) !== null && _a !== void 0 ? _a : Forbidden.code, (_b = error.reason) !== null && _b !== void 0 ? _b : Forbidden.reason); -- } -- catch (closeError) { -- // catch is needed in case invalid error code is returned by hook (that would fail sending the close message) -- console.error(closeError); -- incoming.close(Unauthorized.code, Unauthorized.reason); -- } -- }); -- } -- handleQueueingMessage(data); -+ // If it’s the last connection, we need to make sure to store the -+ // document. Use the debounce helper, to clear running timers, -+ // but make it run immediately (`true`). -+ // Only run this if the document has finished loading earlier (i.e. not to persist the empty -+ // ydoc if the onLoadDocument hook returned an error) -+ if (!document.isLoading) { -+ this.debounce(`onStoreDocument-${document.name}`, () => { -+ this.storeDocumentHooks(document, hookPayload); -+ }, true); - } -- catch (closeError) { -- // catch is needed in case an invalid payload crashes the parsing of the Uint8Array -- console.error(closeError); -- incoming.close(Unauthorized.code, Unauthorized.reason); -+ else { -+ // Remove document from memory immediately -+ this.documents.delete(document.name); -+ document.destroy(); - } -- }; -- incoming.on('message', messageHandler); -+ }); - } - /** - * Handle update of the given document -@@ -2643,11 +2818,12 @@ class Hocuspocus { - document, - documentName: document.name, - requestHeaders: (_a = request === null || request === void 0 ? void 0 : request.headers) !== null && _a !== void 0 ? _a : {}, -- requestParameters: Hocuspocus.getParameters(request), -+ requestParameters: getParameters(request), - socketId: (_b = connection === null || connection === void 0 ? void 0 : connection.socketId) !== null && _b !== void 0 ? _b : '', - update, - }; - this.hooks('onChange', hookPayload).catch(error => { -+ // TODO: what's the intention of this catch -> throw? - throw error; - }); - // If the update was received through other ways than the -@@ -2704,7 +2880,7 @@ class Hocuspocus { - documentName, - socketId, - requestHeaders: request.headers, -- requestParameters: Hocuspocus.getParameters(request), -+ requestParameters: getParameters(request), - }; - try { - await this.hooks('onLoadDocument', hookPayload, (loadedDocument) => { -@@ -2745,78 +2921,6 @@ class Hocuspocus { - }); - return document; - } -- /** -- * Create a new connection by the given request and document -- */ -- createConnection(connection, request, document, socketId, readOnly = false, context) { -- const instance = new Connection(connection, request, document, this.configuration.timeout, socketId, context, readOnly, this.debugger); -- instance.onClose(document => { -- const hookPayload = { -- instance: this, -- clientsCount: document.getConnectionsCount(), -- context, -- document, -- socketId, -- documentName: document.name, -- requestHeaders: request.headers, -- requestParameters: Hocuspocus.getParameters(request), -- }; -- this.hooks('onDisconnect', hookPayload).then(() => { -- // Check if there are still no connections to the document, as these hooks -- // may take some time to resolve (e.g. database queries). If a -- // new connection were to come in during that time it would rely on the -- // document in the map that we remove now. -- if (document.getConnectionsCount() > 0) { -- return; -- } -- // If it’s the last connection, we need to make sure to store the -- // document. Use the debounce helper, to clear running timers, -- // but make it run immediately (`true`). -- // Only run this if the document has finished loading earlier (i.e. not to persist the empty -- // ydoc if the onLoadDocument hook returned an error) -- if (!document.isLoading) { -- this.debounce(`onStoreDocument-${document.name}`, () => { -- this.storeDocumentHooks(document, hookPayload); -- }, true); -- } -- else { -- // Remove document from memory immediately -- this.documents.delete(document.name); -- document.destroy(); -- } -- }); -- }); -- instance.onStatelessCallback(payload => { -- return this.hooks('onStateless', payload) -- .catch(error => { -- if (error === null || error === void 0 ? void 0 : error.message) { -- throw error; -- } -- }); -- }); -- instance.beforeHandleMessage((connection, update) => { -- const hookPayload = { -- instance: this, -- clientsCount: document.getConnectionsCount(), -- context, -- document, -- socketId, -- connection, -- documentName: document.name, -- requestHeaders: request.headers, -- requestParameters: Hocuspocus.getParameters(request), -- update, -- }; -- return this.hooks('beforeHandleMessage', hookPayload); -- }); -- // If the WebSocket has already disconnected (wow, that was fast) – then -- // immediately call close to cleanup the connection and document in memory. -- if (connection.readyState === WsReadyStates.Closing -- || connection.readyState === WsReadyStates.Closed) { -- instance.close(); -- } -- return instance; -- } - storeDocumentHooks(document, hookPayload) { - this.hooks('onStoreDocument', hookPayload) - .catch(error => { -@@ -2864,14 +2968,6 @@ class Hocuspocus { - }); - return chain; - } -- /** -- * Get parameters by the given request -- */ -- static getParameters(request) { -- var _a; -- const query = ((_a = request === null || request === void 0 ? void 0 : request.url) === null || _a === void 0 ? void 0 : _a.split('?')) || []; -- return new URLSearchParams(query[1] ? query[1] : ''); -- } - enableDebugging() { - this.debugger.enable(); - } -diff --git a/node_modules/@hocuspocus/server/dist/hocuspocus-server.esm.js.map b/node_modules/@hocuspocus/server/dist/hocuspocus-server.esm.js.map -index 3ca6b7b..4c54e24 100644 ---- a/node_modules/@hocuspocus/server/dist/hocuspocus-server.esm.js.map -+++ b/node_modules/@hocuspocus/server/dist/hocuspocus-server.esm.js.map -@@ -1 +1 @@ --{"version":3,"file":"hocuspocus-server.esm.js","sources":["../../../node_modules/lib0/string.js","../../../node_modules/lib0/map.js","../../../node_modules/lib0/conditions.js","../../../node_modules/lib0/storage.js","../../../node_modules/lib0/set.js","../../../node_modules/lib0/array.js","../../../node_modules/lib0/object.js","../../../node_modules/lib0/function.js","../../../node_modules/lib0/environment.js","../../../node_modules/lib0/math.js","../../../node_modules/lib0/binary.js","../../../node_modules/lib0/number.js","../../../node_modules/lib0/encoding.js","../../../node_modules/lib0/buffer.js","../../../node_modules/lib0/error.js","../../../node_modules/lib0/decoding.js","../src/IncomingMessage.ts","../../../node_modules/y-protocols/sync.js","../../../node_modules/lib0/time.js","../../../node_modules/lib0/observable.js","../../../node_modules/y-protocols/awareness.js","../src/types.ts","../src/OutgoingMessage.ts","../src/MessageReceiver.ts","../src/Connection.ts","../src/Debugger.ts","../../../node_modules/lib0/mutex.js","../src/Document.ts","../src/DirectConnection.ts","../src/Hocuspocus.ts"],"sourcesContent":["/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* c8 ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* c8 ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* c8 ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* c8 ignore start */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* c8 ignore next */\n utf8TextDecoder = null\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* c8 ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n","/**\n * Utility module to work with key-value stores.\n *\n * @module map\n */\n\n/**\n * Creates a new Map instance.\n *\n * @function\n * @return {Map}\n *\n * @function\n */\nexport const create = () => new Map()\n\n/**\n * Copy a Map object into a fresh Map object.\n *\n * @function\n * @template X,Y\n * @param {Map} m\n * @return {Map}\n */\nexport const copy = m => {\n const r = create()\n m.forEach((v, k) => { r.set(k, v) })\n return r\n}\n\n/**\n * Get map property. Create T if property is undefined and set T on map.\n *\n * ```js\n * const listeners = map.setIfUndefined(events, 'eventName', set.create)\n * listeners.add(listener)\n * ```\n *\n * @function\n * @template V,K\n * @template {Map} MAP\n * @param {MAP} map\n * @param {K} key\n * @param {function():V} createT\n * @return {V}\n */\nexport const setIfUndefined = (map, key, createT) => {\n let set = map.get(key)\n if (set === undefined) {\n map.set(key, set = createT())\n }\n return set\n}\n\n/**\n * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function.\n *\n * @function\n * @template K\n * @template V\n * @template R\n * @param {Map} m\n * @param {function(V,K):R} f\n * @return {Array}\n */\nexport const map = (m, f) => {\n const res = []\n for (const [key, value] of m) {\n res.push(f(value, key))\n }\n return res\n}\n\n/**\n * Tests whether any key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @todo should rename to some - similarly to Array.some\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const any = (m, f) => {\n for (const [key, value] of m) {\n if (f(value, key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * Tests whether all key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const all = (m, f) => {\n for (const [key, value] of m) {\n if (!f(value, key)) {\n return false\n }\n }\n return true\n}\n","/**\n * Often used conditions.\n *\n * @module conditions\n */\n\n/**\n * @template T\n * @param {T|null|undefined} v\n * @return {T|null}\n */\n/* c8 ignore next */\nexport const undefinedToNull = v => v === undefined ? null : v\n","/* eslint-env browser */\n\n/**\n * Isomorphic variable storage.\n *\n * Uses LocalStorage in the browser and falls back to in-memory storage.\n *\n * @module storage\n */\n\n/* c8 ignore start */\nclass VarStoragePolyfill {\n constructor () {\n this.map = new Map()\n }\n\n /**\n * @param {string} key\n * @param {any} newValue\n */\n setItem (key, newValue) {\n this.map.set(key, newValue)\n }\n\n /**\n * @param {string} key\n */\n getItem (key) {\n return this.map.get(key)\n }\n}\n/* c8 ignore stop */\n\n/**\n * @type {any}\n */\nlet _localStorage = new VarStoragePolyfill()\nlet usePolyfill = true\n\n/* c8 ignore start */\ntry {\n // if the same-origin rule is violated, accessing localStorage might thrown an error\n if (typeof localStorage !== 'undefined') {\n _localStorage = localStorage\n usePolyfill = false\n }\n} catch (e) { }\n/* c8 ignore stop */\n\n/**\n * This is basically localStorage in browser, or a polyfill in nodejs\n */\n/* c8 ignore next */\nexport const varStorage = _localStorage\n\n/**\n * A polyfill for `addEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler))\n\n/**\n * A polyfill for `removeEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler))\n","/**\n * Utility module to work with sets.\n *\n * @module set\n */\n\nexport const create = () => new Set()\n\n/**\n * @template T\n * @param {Set} set\n * @return {Array}\n */\nexport const toArray = set => Array.from(set)\n\n/**\n * @template T\n * @param {Set} set\n * @return {T}\n */\nexport const first = set =>\n set.values().next().value || undefined\n\n/**\n * @template T\n * @param {Iterable} entries\n * @return {Set}\n */\nexport const from = entries => new Set(entries)\n","/**\n * Utility module to work with Arrays.\n *\n * @module array\n */\n\nimport * as set from './set.js'\n\n/**\n * Return the last element of an array. The element must exist\n *\n * @template L\n * @param {ArrayLike} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array}\n */\nexport const create = () => /** @type {Array} */ ([])\n\n/**\n * @template D\n * @param {Array} a\n * @return {Array}\n */\nexport const copy = a => /** @type {Array} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array} dest\n * @param {Array} src\n */\nexport const appendTo = (dest, src) => {\n for (let i = 0; i < src.length; i++) {\n dest.push(src[i])\n }\n}\n\n/**\n * Transforms something array-like to an actual Array.\n *\n * @function\n * @template T\n * @param {ArrayLike|Iterable} arraylike\n * @return {T}\n */\nexport const from = Array.from\n\n/**\n * True iff condition holds on every element in the Array.\n *\n * @function\n * @template ITEM\n * @template {ArrayLike} ARR\n *\n * @param {ARR} arr\n * @param {function(ITEM, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const every = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (!f(arr[i], i, arr)) {\n return false\n }\n }\n return true\n}\n\n/**\n * True iff condition holds on some element in the Array.\n *\n * @function\n * @template S\n * @template {ArrayLike} ARR\n * @param {ARR} arr\n * @param {function(S, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const some = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (f(arr[i], i, arr)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @template ELEM\n *\n * @param {ArrayLike} a\n * @param {ArrayLike} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a.length === b.length && every(a, (item, index) => item === b[index])\n\n/**\n * @template ELEM\n * @param {Array>} arr\n * @return {Array}\n */\nexport const flatten = arr => arr.reduce((acc, val) => acc.concat(val), [])\n\nexport const isArray = Array.isArray\n\n/**\n * @template T\n * @param {Array} arr\n * @return {Array}\n */\nexport const unique = arr => from(set.from(arr))\n\n/**\n * @template T\n * @template M\n * @param {ArrayLike} arr\n * @param {function(T):M} mapper\n * @return {Array}\n */\nexport const uniqueBy = (arr, mapper) => {\n /**\n * @type {Set}\n */\n const happened = set.create()\n /**\n * @type {Array}\n */\n const result = []\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i]\n const mapped = mapper(el)\n if (!happened.has(mapped)) {\n happened.add(mapped)\n result.push(el)\n }\n }\n return result\n}\n","/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object} obj\n */\nexport const keys = Object.keys\n\n/**\n * @template V\n * @param {{[k:string]:V}} obj\n * @param {function(V,string):any} f\n */\nexport const forEach = (obj, f) => {\n for (const key in obj) {\n f(obj[key], key)\n }\n}\n\n/**\n * @todo implement mapToArray & map\n *\n * @template R\n * @param {Object} obj\n * @param {function(any,string):R} f\n * @return {Array}\n */\nexport const map = (obj, f) => {\n const results = []\n for (const key in obj) {\n results.push(f(obj[key], key))\n }\n return results\n}\n\n/**\n * @param {Object} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n for (const key in obj) {\n if (f(obj[key], key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {Object|undefined} obj\n */\nexport const isEmpty = obj => {\n for (const _k in obj) {\n return false\n }\n return true\n}\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n for (const key in obj) {\n if (!f(obj[key], key)) {\n return false\n }\n }\n return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object} a\n * @param {Object} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val))\n","/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array} fs\n * @param {Array} args\n */\nexport const callAll = (fs, args, i = 0) => {\n try {\n for (; i < fs.length; i++) {\n fs[i](...args)\n }\n } finally {\n if (i < fs.length) {\n callAll(fs, args, i + 1)\n }\n }\n}\n\nexport const nop = () => {}\n\n/**\n * @template T\n * @param {function():T} f\n * @return {T}\n */\nexport const apply = f => f()\n\n/**\n * @template A\n *\n * @param {A} a\n * @return {A}\n */\nexport const id = a => a\n\n/**\n * @template T\n *\n * @param {T} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equalityStrict = (a, b) => a === b\n\n/**\n * @template T\n *\n * @param {Array|object} a\n * @param {Array|object} b\n * @return {boolean}\n */\nexport const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((a instanceof Array && array.equalFlat(a, /** @type {Array} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/* c8 ignore start */\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a == null || b == null) {\n return equalityStrict(a, b)\n }\n if (a.constructor !== b.constructor) {\n return false\n }\n if (a === b) {\n return true\n }\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n break\n }\n case Map: {\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n return false\n }\n }\n break\n }\n case Object:\n if (object.length(a) !== object.length(b)) {\n return false\n }\n for (const key in a) {\n if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n return false\n }\n }\n break\n case Array:\n if (a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!equalityDeep(a[i], b[i])) {\n return false\n }\n }\n break\n default:\n return false\n }\n return true\n}\n\n/**\n * @template V\n * @template {V} OPTS\n *\n * @param {V} value\n * @param {Array} options\n */\n// @ts-ignore\nexport const isOneOf = (value, options) => options.includes(value)\n/* c8 ignore stop */\n","/**\n * Isomorphic module to work access the environment (query params, env variables).\n *\n * @module map\n */\n\nimport * as map from './map.js'\nimport * as string from './string.js'\nimport * as conditions from './conditions.js'\nimport * as storage from './storage.js'\nimport * as f from './function.js'\n\n/* c8 ignore next */\n// @ts-ignore\nexport const isNode = typeof process !== 'undefined' && process.release &&\n /node|io\\.js/.test(process.release.name)\n/* c8 ignore next */\nexport const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && !isNode\n/* c8 ignore next 3 */\nexport const isMac = typeof navigator !== 'undefined'\n ? /Mac/.test(navigator.platform)\n : false\n\n/**\n * @type {Map}\n */\nlet params\nconst args = []\n\n/* c8 ignore start */\nconst computeParams = () => {\n if (params === undefined) {\n if (isNode) {\n params = map.create()\n const pargs = process.argv\n let currParamName = null\n for (let i = 0; i < pargs.length; i++) {\n const parg = pargs[i]\n if (parg[0] === '-') {\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n currParamName = parg\n } else {\n if (currParamName !== null) {\n params.set(currParamName, parg)\n currParamName = null\n } else {\n args.push(parg)\n }\n }\n }\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n // in ReactNative for example this would not be true (unless connected to the Remote Debugger)\n } else if (typeof location === 'object') {\n params = map.create(); // eslint-disable-next-line no-undef\n (location.search || '?').slice(1).split('&').forEach((kv) => {\n if (kv.length !== 0) {\n const [key, value] = kv.split('=')\n params.set(`--${string.fromCamelCase(key, '-')}`, value)\n params.set(`-${string.fromCamelCase(key, '-')}`, value)\n }\n })\n } else {\n params = map.create()\n }\n }\n return params\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next */\nexport const hasParam = (name) => computeParams().has(name)\n\n/**\n * @param {string} name\n * @param {string} defaultVal\n * @return {string}\n */\n/* c8 ignore next 2 */\nexport const getParam = (name, defaultVal) =>\n computeParams().get(name) || defaultVal\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 4 */\nexport const getVariable = (name) =>\n isNode\n ? conditions.undefinedToNull(process.env[name.toUpperCase()])\n : conditions.undefinedToNull(storage.varStorage.getItem(name))\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 2 */\nexport const getConf = (name) =>\n computeParams().get('--' + name) || getVariable(name)\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next 2 */\nexport const hasConf = (name) =>\n hasParam('--' + name) || getVariable(name) !== null\n\n/* c8 ignore next */\nexport const production = hasConf('production')\n\n/* c8 ignore next 2 */\nconst forceColor = isNode &&\n f.isOneOf(process.env.FORCE_COLOR, ['true', '1', '2'])\n\n/* c8 ignore start */\nexport const supportsColor = !hasParam('no-colors') &&\n (!isNode || process.stdout.isTTY || forceColor) && (\n !isNode || hasParam('color') || forceColor ||\n getVariable('COLORTERM') !== null ||\n (getVariable('TERM') || '').includes('color')\n)\n/* c8 ignore stop */\n","/**\n * Common Math expressions.\n *\n * @module math\n */\n\nexport const floor = Math.floor\nexport const ceil = Math.ceil\nexport const abs = Math.abs\nexport const imul = Math.imul\nexport const round = Math.round\nexport const log10 = Math.log10\nexport const log2 = Math.log2\nexport const log = Math.log\nexport const sqrt = Math.sqrt\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The sum of a and b\n */\nexport const add = (a, b) => a + b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The smaller element of a and b\n */\nexport const min = (a, b) => a < b ? a : b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The bigger element of a and b\n */\nexport const max = (a, b) => a > b ? a : b\n\nexport const isNaN = Number.isNaN\n\nexport const pow = Math.pow\n/**\n * Base 10 exponential function. Returns the value of 10 raised to the power of pow.\n *\n * @param {number} exp\n * @return {number}\n */\nexport const exp10 = exp => Math.pow(10, exp)\n\nexport const sign = Math.sign\n\n/**\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\n/**\n * @type {number}\n */\nexport const HIGHEST_INT32 = binary.BITS31\n\n/**\n * @module number\n */\n\n/* c8 ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n","/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\nimport * as string from './string.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nexport const verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer. Max encodable integer is 2^53.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num = math.floor(num / 64) // shift >>> 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n}\n\n/**\n * A cache to store strings temporarily\n */\nconst _strBuffer = new Uint8Array(30000)\nconst _maxStrBSize = _strBuffer.length / 3\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringNative = (encoder, str) => {\n if (str.length < _maxStrBSize) {\n // We can encode the string into the existing buffer\n /* c8 ignore next */\n const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0\n writeVarUint(encoder, written)\n for (let i = 0; i < written; i++) {\n write(encoder, _strBuffer[i])\n }\n } else {\n writeVarUint8Array(encoder, string.encodeUtf8(str))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringPolyfill = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\n/* c8 ignore next */\nexport const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && math.abs(data) <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (data instanceof Array) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n","/**\n * Utility functions to work with buffers (Uint8Array).\n *\n * @module buffer\n */\n\nimport * as string from './string.js'\nimport * as env from './environment.js'\nimport * as encoding from './encoding.js'\nimport * as decoding from './decoding.js'\n\n/**\n * @param {number} len\n */\nexport const createUint8ArrayFromLen = len => new Uint8Array(len)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n * @param {number} byteOffset\n * @param {number} length\n */\nexport const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n */\nexport const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer)\n\n/* c8 ignore start */\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Browser = bytes => {\n let s = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n s += string.fromCharCode(bytes[i])\n }\n // eslint-disable-next-line no-undef\n return btoa(s)\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')\n\n/* c8 ignore start */\n/**\n * @param {string} s\n * @return {Uint8Array}\n */\nconst fromBase64Browser = s => {\n // eslint-disable-next-line no-undef\n const a = atob(s)\n const bytes = createUint8ArrayFromLen(a.length)\n for (let i = 0; i < a.length; i++) {\n bytes[i] = a.charCodeAt(i)\n }\n return bytes\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} s\n */\nconst fromBase64Node = s => {\n const buf = Buffer.from(s, 'base64')\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n}\n\n/* c8 ignore next */\nexport const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node\n\n/* c8 ignore next */\nexport const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node\n\n/**\n * Copy the content of an Uint8Array view to a new ArrayBuffer.\n *\n * @param {Uint8Array} uint8Array\n * @return {Uint8Array}\n */\nexport const copyUint8Array = uint8Array => {\n const newBuf = createUint8ArrayFromLen(uint8Array.byteLength)\n newBuf.set(uint8Array)\n return newBuf\n}\n\n/**\n * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type.\n * See encoding.writeAny for more information.\n *\n * @param {any} data\n * @return {Uint8Array}\n */\nexport const encodeAny = data => {\n const encoder = encoding.createEncoder()\n encoding.writeAny(encoder, data)\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Decode an any-encoded value.\n *\n * @param {Uint8Array} buf\n * @return {any}\n */\nexport const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf))\n","/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* c8 ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n","/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as binary from './binary.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as string from './string.js'\nimport * as error from './error.js'\n\nconst errorUnexpectedEndOfArray = error.create('Unexpected end of array')\nconst errorIntegerOutOfRange = error.create('Integer out of Range')\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n */\nexport class Decoder {\n /**\n * @param {Uint8Array} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @param {Uint8Array} uint8Array\n * @return {Decoder}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = buffer.createUint8ArrayViewFromArrayBuffer(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let mult = 1\n const len = decoder.arr.length\n while (decoder.pos < len) {\n const r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num\n mult *= 128 // next iteration, shift 7 \"more\" to the left\n if (r < binary.BIT8) {\n return num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let mult = 64\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n const len = decoder.arr.length\n while (decoder.pos < len) {\n r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult\n mult *= 128\n if (r < binary.BIT8) {\n return sign * num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * We don't test this function anymore as we use native decoding/encoding by default now.\n * Better not modify this anymore..\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\n/* c8 ignore start */\nexport const _readVarStringPolyfill = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n/* c8 ignore stop */\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n */\nexport const _readVarStringNative = decoder =>\n /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder))\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n *\n */\n/* c8 ignore next */\nexport const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object\n const len = readVarUint(decoder)\n /**\n * @type {Object}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = math.floor(diff / 2) // shift >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n","import {\n createDecoder,\n Decoder,\n readVarUint,\n readVarUint8Array,\n readVarString,\n} from 'lib0/decoding'\nimport {\n createEncoder,\n Encoder,\n toUint8Array,\n writeVarUint,\n writeVarString,\n length,\n} from 'lib0/encoding'\nimport { MessageType } from './types.js'\n\nexport class IncomingMessage {\n /**\n * Access to the received message.\n */\n decoder: Decoder\n\n /**\n * Access to the reply.\n */\n encoder: Encoder\n\n constructor(input: any) {\n if (!(input instanceof Uint8Array)) {\n input = new Uint8Array(input)\n }\n\n this.encoder = createEncoder()\n this.decoder = createDecoder(input)\n }\n\n readVarUint8Array() {\n return readVarUint8Array(this.decoder)\n }\n\n readVarUint() {\n return readVarUint(this.decoder)\n }\n\n readVarString() {\n return readVarString(this.decoder)\n }\n\n toUint8Array() {\n return toUint8Array(this.encoder)\n }\n\n writeVarUint(type: MessageType) {\n writeVarUint(this.encoder, type)\n }\n\n writeVarString(string: string) {\n writeVarString(this.encoder, string)\n }\n\n get length(): number {\n return length(this.encoder)\n }\n}\n","/**\n * @module sync-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as Y from 'yjs'\n\n/**\n * @typedef {Map} StateMap\n */\n\n/**\n * Core Yjs defines two message types:\n * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.\n * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it\n * received all information from the remote client.\n *\n * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection\n * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both\n * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.\n *\n * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.\n * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies\n * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the\n * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can\n * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them.\n * Therefore it is necesarry that the client initiates the sync.\n *\n * Construction of a message:\n * [messageType : varUint, message definition..]\n *\n * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!\n *\n * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)\n */\n\nexport const messageYjsSyncStep1 = 0\nexport const messageYjsSyncStep2 = 1\nexport const messageYjsUpdate = 2\n\n/**\n * Create a sync step 1 message based on the state of the current shared document.\n *\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n */\nexport const writeSyncStep1 = (encoder, doc) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep1)\n const sv = Y.encodeStateVector(doc)\n encoding.writeVarUint8Array(encoder, sv)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n * @param {Uint8Array} [encodedStateVector]\n */\nexport const writeSyncStep2 = (encoder, doc, encodedStateVector) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep2)\n encoding.writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector))\n}\n\n/**\n * Read SyncStep1 message and reply with SyncStep2.\n *\n * @param {decoding.Decoder} decoder The reply to the received message\n * @param {encoding.Encoder} encoder The received message\n * @param {Y.Doc} doc\n */\nexport const readSyncStep1 = (decoder, encoder, doc) =>\n writeSyncStep2(encoder, doc, decoding.readVarUint8Array(decoder))\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin) => {\n try {\n Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n } catch (error) {\n // This catches errors that are thrown by event handlers\n console.error('Caught error while handling a Yjs update', error)\n }\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Uint8Array} update\n */\nexport const writeUpdate = (encoder, update) => {\n encoding.writeVarUint(encoder, messageYjsUpdate)\n encoding.writeVarUint8Array(encoder, update)\n}\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readUpdate = readSyncStep2\n\n/**\n * @param {decoding.Decoder} decoder A message received from another client\n * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => {\n const messageType = decoding.readVarUint(decoder)\n switch (messageType) {\n case messageYjsSyncStep1:\n readSyncStep1(decoder, encoder, doc)\n break\n case messageYjsSyncStep2:\n readSyncStep2(decoder, doc, transactionOrigin)\n break\n case messageYjsUpdate:\n readUpdate(decoder, doc, transactionOrigin)\n break\n default:\n throw new Error('Unknown message type')\n }\n return messageType\n}\n","/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* c8 ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n","/**\n * Observable class prototype.\n *\n * @module observable\n */\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as array from './array.js'\n\n/**\n * Handles named events.\n *\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map}\n */\n this._observers = map.create()\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, name, set.create).add(f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, _f)\n f(...args)\n }\n this.on(name, _f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @param {N} name The event name.\n * @param {Array} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // 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.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n","/**\n * @module awareness-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as time from 'lib0/time'\nimport * as math from 'lib0/math'\nimport { Observable } from 'lib0/observable'\nimport * as f from 'lib0/function'\nimport * as Y from 'yjs' // eslint-disable-line\n\nexport const outdatedTimeout = 30000\n\n/**\n * @typedef {Object} MetaClientState\n * @property {number} MetaClientState.clock\n * @property {number} MetaClientState.lastUpdated unix timestamp\n */\n\n/**\n * The Awareness class implements a simple shared state protocol that can be used for non-persistent data like awareness information\n * (cursor, username, status, ..). Each client can update its own local state and listen to state changes of\n * remote clients. Every client may set a state of a remote peer to `null` to mark the client as offline.\n *\n * Each client is identified by a unique client id (something we borrow from `doc.clientID`). A client can override\n * its own state by propagating a message with an increasing timestamp (`clock`). If such a message is received, it is\n * applied if the known state of that client is older than the new state (`clock < newClock`). If a client thinks that\n * a remote client is offline, it may propagate a message with\n * `{ clock: currentClientClock, state: null, client: remoteClient }`. If such a\n * message is received, and the known clock of that client equals the received clock, it will override the state with `null`.\n *\n * Before a client disconnects, it should propagate a `null` state with an updated clock.\n *\n * Awareness states must be updated every 30 seconds. Otherwise the Awareness instance will delete the client state.\n *\n * @extends {Observable}\n */\nexport class Awareness extends Observable {\n /**\n * @param {Y.Doc} doc\n */\n constructor (doc) {\n super()\n this.doc = doc\n /**\n * @type {number}\n */\n this.clientID = doc.clientID\n /**\n * Maps from client id to client state\n * @type {Map>}\n */\n this.states = new Map()\n /**\n * @type {Map}\n */\n this.meta = new Map()\n this._checkInterval = /** @type {any} */ (setInterval(() => {\n const now = time.getUnixTime()\n if (this.getLocalState() !== null && (outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ (this.meta.get(this.clientID)).lastUpdated)) {\n // renew local clock\n this.setLocalState(this.getLocalState())\n }\n /**\n * @type {Array}\n */\n const remove = []\n this.meta.forEach((meta, clientid) => {\n if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) {\n remove.push(clientid)\n }\n })\n if (remove.length > 0) {\n removeAwarenessStates(this, remove, 'timeout')\n }\n }, math.floor(outdatedTimeout / 10)))\n doc.on('destroy', () => {\n this.destroy()\n })\n this.setLocalState({})\n }\n\n destroy () {\n this.emit('destroy', [this])\n this.setLocalState(null)\n super.destroy()\n clearInterval(this._checkInterval)\n }\n\n /**\n * @return {Object|null}\n */\n getLocalState () {\n return this.states.get(this.clientID) || null\n }\n\n /**\n * @param {Object|null} state\n */\n setLocalState (state) {\n const clientID = this.clientID\n const currLocalMeta = this.meta.get(clientID)\n const clock = currLocalMeta === undefined ? 0 : currLocalMeta.clock + 1\n const prevState = this.states.get(clientID)\n if (state === null) {\n this.states.delete(clientID)\n } else {\n this.states.set(clientID, state)\n }\n this.meta.set(clientID, {\n clock,\n lastUpdated: time.getUnixTime()\n })\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n if (state === null) {\n removed.push(clientID)\n } else if (prevState == null) {\n if (state != null) {\n added.push(clientID)\n }\n } else {\n updated.push(clientID)\n if (!f.equalityDeep(prevState, state)) {\n filteredUpdated.push(clientID)\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n this.emit('change', [{ added, updated: filteredUpdated, removed }, 'local'])\n }\n this.emit('update', [{ added, updated, removed }, 'local'])\n }\n\n /**\n * @param {string} field\n * @param {any} value\n */\n setLocalStateField (field, value) {\n const state = this.getLocalState()\n if (state !== null) {\n this.setLocalState({\n ...state,\n [field]: value\n })\n }\n }\n\n /**\n * @return {Map>}\n */\n getStates () {\n return this.states\n }\n}\n\n/**\n * Mark (remote) clients as inactive and remove them from the list of active peers.\n * This change will be propagated to remote clients.\n *\n * @param {Awareness} awareness\n * @param {Array} clients\n * @param {any} origin\n */\nexport const removeAwarenessStates = (awareness, clients, origin) => {\n const removed = []\n for (let i = 0; i < clients.length; i++) {\n const clientID = clients[i]\n if (awareness.states.has(clientID)) {\n awareness.states.delete(clientID)\n if (clientID === awareness.clientID) {\n const curMeta = /** @type {MetaClientState} */ (awareness.meta.get(clientID))\n awareness.meta.set(clientID, {\n clock: curMeta.clock + 1,\n lastUpdated: time.getUnixTime()\n })\n }\n removed.push(clientID)\n }\n }\n if (removed.length > 0) {\n awareness.emit('change', [{ added: [], updated: [], removed }, origin])\n awareness.emit('update', [{ added: [], updated: [], removed }, origin])\n }\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Array} clients\n * @return {Uint8Array}\n */\nexport const encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {\n const len = clients.length\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = clients[i]\n const state = states.get(clientID) || null\n const clock = /** @type {MetaClientState} */ (awareness.meta.get(clientID)).clock\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(state))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Modify the content of an awareness update before re-encoding it to an awareness update.\n *\n * This might be useful when you have a central server that wants to ensure that clients\n * cant hijack somebody elses identity.\n *\n * @param {Uint8Array} update\n * @param {function(any):any} modify\n * @return {Uint8Array}\n */\nexport const modifyAwarenessUpdate = (update, modify) => {\n const decoder = decoding.createDecoder(update)\n const encoder = encoding.createEncoder()\n const len = decoding.readVarUint(decoder)\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n const clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const modifiedState = modify(state)\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(modifiedState))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Uint8Array} update\n * @param {any} origin This will be added to the emitted change event\n */\nexport const applyAwarenessUpdate = (awareness, update, origin) => {\n const decoder = decoding.createDecoder(update)\n const timestamp = time.getUnixTime()\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n const len = decoding.readVarUint(decoder)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n let clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const clientMeta = awareness.meta.get(clientID)\n const prevState = awareness.states.get(clientID)\n const currClock = clientMeta === undefined ? 0 : clientMeta.clock\n if (currClock < clock || (currClock === clock && state === null && awareness.states.has(clientID))) {\n if (state === null) {\n // never let a remote client remove this local state\n if (clientID === awareness.clientID && awareness.getLocalState() != null) {\n // remote client removed the local state. Do not remote state. Broadcast a message indicating\n // that this client still exists by increasing the clock\n clock++\n } else {\n awareness.states.delete(clientID)\n }\n } else {\n awareness.states.set(clientID, state)\n }\n awareness.meta.set(clientID, {\n clock,\n lastUpdated: timestamp\n })\n if (clientMeta === undefined && state !== null) {\n added.push(clientID)\n } else if (clientMeta !== undefined && state === null) {\n removed.push(clientID)\n } else if (state !== null) {\n if (!f.equalityDeep(state, prevState)) {\n filteredUpdated.push(clientID)\n }\n updated.push(clientID)\n }\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n awareness.emit('change', [{\n added, updated: filteredUpdated, removed\n }, origin])\n }\n if (added.length > 0 || updated.length > 0 || removed.length > 0) {\n awareness.emit('update', [{\n added, updated, removed\n }, origin])\n }\n}\n","import {\n IncomingHttpHeaders, IncomingMessage, ServerResponse,\n} from 'http'\nimport { URLSearchParams } from 'url'\nimport { Awareness } from 'y-protocols/awareness'\nimport Document from './Document.js'\nimport { Hocuspocus } from './Hocuspocus.js'\nimport Connection from './Connection.js'\n\nexport enum MessageType {\n Unknown = -1,\n Sync = 0,\n Awareness = 1,\n Auth = 2,\n QueryAwareness = 3,\n SyncReply = 4, // same as Sync, but won't trigger another 'SyncStep1'\n Stateless = 5,\n BroadcastStateless = 6,\n\n CLOSE = 7,\n}\n\nexport interface AwarenessUpdate {\n added: Array,\n updated: Array,\n removed: Array,\n}\n\nexport interface ConnectionConfiguration {\n readOnly: boolean\n requiresAuthentication: boolean\n isAuthenticated: boolean\n}\n\nexport interface Extension {\n priority?: number,\n onConfigure?(data: onConfigurePayload): Promise,\n onListen?(data: onListenPayload): Promise,\n onUpgrade?(data: onUpgradePayload): Promise,\n onConnect?(data: onConnectPayload): Promise,\n connected?(data: connectedPayload): Promise,\n onAuthenticate?(data: onAuthenticatePayload): Promise,\n onLoadDocument?(data: onLoadDocumentPayload): Promise,\n afterLoadDocument?(data: onLoadDocumentPayload): Promise,\n beforeHandleMessage?(data: beforeHandleMessagePayload): Promise,\n beforeBroadcastStateless?(data: beforeBroadcastStatelessPayload): Promise,\n onStateless?(payload: onStatelessPayload): Promise;\n onChange?(data: onChangePayload): Promise,\n onStoreDocument?(data: onStoreDocumentPayload): Promise,\n afterStoreDocument?(data: afterStoreDocumentPayload): Promise,\n onAwarenessUpdate?(data: onAwarenessUpdatePayload): Promise,\n onRequest?(data: onRequestPayload): Promise,\n onDisconnect?(data: onDisconnectPayload): Promise\n onDestroy?(data: onDestroyPayload): Promise,\n}\n\nexport type HookName =\n 'onConfigure' |\n 'onListen' |\n 'onUpgrade' |\n 'onConnect' |\n 'connected' |\n 'onAuthenticate' |\n 'onLoadDocument' |\n 'afterLoadDocument' |\n 'beforeHandleMessage' |\n 'beforeBroadcastStateless' |\n 'onStateless' |\n 'onChange' |\n 'onStoreDocument' |\n 'afterStoreDocument' |\n 'onAwarenessUpdate' |\n 'onRequest' |\n 'onDisconnect' |\n 'onDestroy'\n\nexport type HookPayload =\n onConfigurePayload |\n onListenPayload |\n onUpgradePayload |\n onConnectPayload |\n connectedPayload |\n onAuthenticatePayload |\n onLoadDocumentPayload |\n onStatelessPayload |\n beforeHandleMessagePayload |\n beforeBroadcastStatelessPayload |\n onChangePayload |\n onStoreDocumentPayload |\n afterStoreDocumentPayload |\n onAwarenessUpdatePayload |\n onRequestPayload |\n onDisconnectPayload |\n onDestroyPayload\n\nexport interface Configuration extends Extension {\n /**\n * A name for the instance, used for logging.\n */\n name: string | null,\n /**\n * A list of hocuspocus extenions.\n */\n extensions: Array,\n /**\n * The port which the server listens on.\n */\n port?: number,\n /**\n * The address which the server listens on.\n */\n address?: string,\n /**\n * Defines in which interval the server sends a ping, and closes the connection when no pong is sent back.\n */\n timeout: number,\n /**\n * Debounces the call of the `onStoreDocument` hook for the given amount of time in ms.\n * Otherwise every single update would be persisted.\n */\n debounce: number,\n /**\n * Makes sure to call `onStoreDocument` at least in the given amount of time (ms).\n */\n maxDebounce: number\n /**\n * By default, the servers show a start screen. If passed false, the server will start quietly.\n */\n quiet: boolean,\n\n /**\n * options to pass to the ydoc document\n */\n yDocOptions: {\n gc: boolean, // enable or disable garbage collection (see https://github.com/yjs/yjs/blob/main/INTERNALS.md#deletions)\n gcFilter: () => boolean, // will be called before garbage collecting ; return false to keep it\n },\n /**\n * Function which returns the (customized) document name based on the request\n */\n getDocumentName?(data: getDocumentNamePayload): string | Promise,\n}\n\nexport interface getDocumentNamePayload {\n documentName: string,\n request: IncomingMessage,\n requestParameters: URLSearchParams,\n}\n\nexport interface onStatelessPayload {\n connection: Connection,\n documentName: string,\n document: Document,\n payload: string,\n}\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface onAuthenticatePayload {\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n token: string,\n connection: ConnectionConfiguration\n}\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface onConnectPayload {\n documentName: string,\n instance: Hocuspocus,\n request: IncomingMessage,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration\n}\n\n// @todo Change 'connection' to 'connectionConfig', and 'connectionInstance' to 'connection' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface connectedPayload {\n context: any,\n documentName: string,\n instance: Hocuspocus,\n request: IncomingMessage,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration,\n connectionInstance: Connection\n}\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface onLoadDocumentPayload {\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration\n}\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface afterLoadDocumentPayload {\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration\n}\n\nexport interface onChangePayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n update: Uint8Array,\n socketId: string,\n}\n\nexport interface beforeHandleMessagePayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n update: Uint8Array,\n socketId: string,\n connection: Connection\n}\n\nexport interface beforeBroadcastStatelessPayload {\n document: Document,\n documentName: string,\n payload: string,\n}\n\nexport interface onStoreDocumentPayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n}\n\nexport interface afterStoreDocumentPayload extends onStoreDocumentPayload {}\n\nexport interface onAwarenessUpdatePayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n update: Uint8Array,\n socketId: string,\n added: number[],\n updated: number[],\n removed: number[],\n awareness: Awareness,\n states: StatesArray,\n}\n\nexport type StatesArray = { clientId: number, [key: string | number]: any }[]\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface fetchPayload {\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration\n}\n\nexport interface storePayload extends onStoreDocumentPayload {\n state: Buffer,\n}\n\nexport interface onDisconnectPayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n}\n\nexport interface onRequestPayload {\n request: IncomingMessage,\n response: ServerResponse,\n instance: Hocuspocus,\n}\n\nexport interface onUpgradePayload {\n request: IncomingMessage,\n socket: any,\n head: any,\n instance: Hocuspocus,\n}\n\nexport interface onListenPayload {\n instance: Hocuspocus,\n configuration: Configuration,\n port: number,\n}\n\nexport interface onDestroyPayload {\n instance: Hocuspocus,\n}\n\nexport interface onConfigurePayload {\n instance: Hocuspocus,\n configuration: Configuration,\n version: string,\n}\n","import {\n createEncoder,\n Encoder,\n toUint8Array,\n writeVarString,\n writeVarUint,\n writeVarUint8Array,\n} from 'lib0/encoding'\nimport { writeSyncStep1, writeUpdate } from 'y-protocols/sync'\nimport { Awareness, encodeAwarenessUpdate } from 'y-protocols/awareness'\n\nimport { writeAuthenticated, writePermissionDenied } from '@hocuspocus/common'\nimport { MessageType } from './types.js'\nimport Document from './Document.js'\n\nexport class OutgoingMessage {\n\n encoder: Encoder\n\n type?: number\n\n category?: string\n\n constructor(documentName: string) {\n this.encoder = createEncoder()\n\n writeVarString(this.encoder, documentName)\n }\n\n createSyncMessage(): OutgoingMessage {\n this.type = MessageType.Sync\n\n writeVarUint(this.encoder, MessageType.Sync)\n\n return this\n }\n\n createSyncReplyMessage(): OutgoingMessage {\n this.type = MessageType.SyncReply\n\n writeVarUint(this.encoder, MessageType.SyncReply)\n\n return this\n }\n\n createAwarenessUpdateMessage(awareness: Awareness, changedClients?: Array): OutgoingMessage {\n this.type = MessageType.Awareness\n this.category = 'Update'\n\n const message = encodeAwarenessUpdate(\n awareness,\n changedClients || Array.from(awareness.getStates().keys()),\n )\n\n writeVarUint(this.encoder, MessageType.Awareness)\n writeVarUint8Array(this.encoder, message)\n\n return this\n }\n\n writeQueryAwareness(): OutgoingMessage {\n this.type = MessageType.QueryAwareness\n this.category = 'Update'\n\n writeVarUint(this.encoder, MessageType.QueryAwareness)\n\n return this\n }\n\n writeAuthenticated(readonly: boolean): OutgoingMessage {\n this.type = MessageType.Auth\n this.category = 'Authenticated'\n\n writeVarUint(this.encoder, MessageType.Auth)\n writeAuthenticated(this.encoder, readonly ? 'readonly' : 'read-write')\n\n return this\n }\n\n writePermissionDenied(reason: string): OutgoingMessage {\n this.type = MessageType.Auth\n this.category = 'PermissionDenied'\n\n writeVarUint(this.encoder, MessageType.Auth)\n writePermissionDenied(this.encoder, reason)\n\n return this\n }\n\n writeFirstSyncStepFor(document: Document): OutgoingMessage {\n this.category = 'SyncStep1'\n\n writeSyncStep1(this.encoder, document)\n\n return this\n }\n\n writeUpdate(update: Uint8Array): OutgoingMessage {\n this.category = 'Update'\n\n writeUpdate(this.encoder, update)\n\n return this\n }\n\n writeStateless(payload: string): OutgoingMessage {\n this.category = 'Stateless'\n\n writeVarUint(this.encoder, MessageType.Stateless)\n writeVarString(this.encoder, payload)\n\n return this\n }\n\n writeBroadcastStateless(payload: string): OutgoingMessage {\n this.category = 'Stateless'\n\n writeVarUint(this.encoder, MessageType.BroadcastStateless)\n writeVarString(this.encoder, payload)\n\n return this\n }\n\n toUint8Array(): Uint8Array {\n return toUint8Array(this.encoder)\n }\n\n}\n","import {\n messageYjsSyncStep1,\n messageYjsSyncStep2,\n messageYjsUpdate,\n readSyncStep1,\n readSyncStep2,\n readUpdate,\n} from 'y-protocols/sync'\nimport { applyAwarenessUpdate } from 'y-protocols/awareness'\nimport { readVarString } from 'lib0/decoding'\nimport { MessageType } from './types.js'\nimport Connection from './Connection.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { Debugger } from './Debugger.js'\nimport Document from './Document.js'\n\nexport class MessageReceiver {\n\n message: IncomingMessage\n\n logger: Debugger\n\n constructor(message: IncomingMessage, logger: Debugger) {\n this.message = message\n this.logger = logger\n }\n\n public apply(document: Document, connection?: Connection, reply?: (message: Uint8Array) => void) {\n const { message } = this\n const type = message.readVarUint()\n const emptyMessageLength = message.length\n\n switch (type) {\n case MessageType.Sync:\n case MessageType.SyncReply: {\n message.writeVarUint(MessageType.Sync)\n this.readSyncMessage(message, document, connection, reply, type !== MessageType.SyncReply)\n\n if (message.length > emptyMessageLength + 1) {\n if (reply) {\n reply(message.toUint8Array())\n } else if (connection) {\n // TODO: We should log this, shouldn’t we?\n // this.logger.log({\n // direction: 'out',\n // type: MessageType.Awareness,\n // category: 'Update',\n // })\n connection.send(message.toUint8Array())\n }\n }\n\n break\n }\n case MessageType.Awareness: {\n this.logger.log({\n direction: 'in',\n type: MessageType.Awareness,\n category: 'Update',\n })\n\n applyAwarenessUpdate(document.awareness, message.readVarUint8Array(), connection)\n\n break\n }\n case MessageType.QueryAwareness: {\n\n this.applyQueryAwarenessMessage(document, reply)\n\n break\n }\n case MessageType.Stateless: {\n connection?.callbacks.statelessCallback({\n connection,\n documentName: document.name,\n document,\n payload: readVarString(message.decoder),\n })\n\n break\n }\n case MessageType.BroadcastStateless: {\n const msg = message.readVarString()\n document.getConnections().forEach(connection => {\n connection.sendStateless(msg)\n })\n break\n }\n\n case MessageType.CLOSE: {\n connection?.close({\n code: 1000,\n reason: 'provider_initiated',\n })\n break\n }\n default:\n console.error(`Unable to handle message of type ${type}: no handler defined!`)\n // Do nothing\n }\n }\n\n readSyncMessage(message: IncomingMessage, document: Document, connection?: Connection, reply?: (message: Uint8Array) => void, requestFirstSync = true) {\n const type = message.readVarUint()\n\n switch (type) {\n case messageYjsSyncStep1: {\n this.logger.log({\n direction: 'in',\n type: MessageType.Sync,\n category: 'SyncStep1',\n })\n\n readSyncStep1(message.decoder, message.encoder, document)\n\n // When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1.\n this.logger.log({\n direction: 'out',\n type: MessageType.Sync,\n category: 'SyncStep2',\n })\n\n if (reply && requestFirstSync) {\n const syncMessage = (new OutgoingMessage(document.name)\n .createSyncReplyMessage()\n .writeFirstSyncStepFor(document))\n\n this.logger.log({\n direction: 'out',\n type: MessageType.Sync,\n category: 'SyncStep1',\n })\n\n reply(syncMessage.toUint8Array())\n } else if (connection) {\n const syncMessage = (new OutgoingMessage(document.name)\n .createSyncMessage()\n .writeFirstSyncStepFor(document))\n\n this.logger.log({\n direction: 'out',\n type: MessageType.Sync,\n category: 'SyncStep1',\n })\n\n connection.send(syncMessage.toUint8Array())\n }\n break\n }\n case messageYjsSyncStep2:\n this.logger.log({\n direction: 'in',\n type: MessageType.Sync,\n category: 'SyncStep2',\n })\n\n if (connection?.readOnly) {\n break\n }\n\n readSyncStep2(message.decoder, document, connection)\n break\n case messageYjsUpdate:\n this.logger.log({\n direction: 'in',\n type: MessageType.Sync,\n category: 'Update',\n })\n\n if (connection?.readOnly) {\n break\n }\n\n readUpdate(message.decoder, document, connection)\n break\n default:\n throw new Error(`Received a message with an unknown type: ${type}`)\n }\n\n return type\n }\n\n applyQueryAwarenessMessage(document: Document, reply?: (message: Uint8Array) => void) {\n const message = new OutgoingMessage(document.name)\n .createAwarenessUpdateMessage(document.awareness)\n\n if (reply) {\n reply(message.toUint8Array())\n }\n\n // TODO: We should add support for WebSocket connections, too, right?\n // this.logger.log({\n // direction: 'out',\n // type: MessageType.Sync,\n // category: 'SyncStep1',\n // })\n\n // connection.send(syncMessage.toUint8Array())\n }\n}\n","import { IncomingMessage as HTTPIncomingMessage } from 'http'\nimport AsyncLock from 'async-lock'\nimport WebSocket from 'ws'\nimport {\n CloseEvent, ConnectionTimeout, Forbidden, WsReadyStates,\n} from '@hocuspocus/common'\nimport Document from './Document.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { MessageReceiver } from './MessageReceiver.js'\nimport { Debugger } from './Debugger.js'\nimport { onStatelessPayload } from './types.js'\n\nexport class Connection {\n\n webSocket: WebSocket\n\n context: any\n\n document: Document\n\n pingInterval: NodeJS.Timeout\n\n pongReceived = true\n\n request: HTTPIncomingMessage\n\n timeout: number\n\n callbacks: any = {\n onClose: [(document: Document, event?: CloseEvent) => null],\n beforeHandleMessage: (connection: Connection, update: Uint8Array) => Promise,\n statelessCallback: () => Promise,\n }\n\n socketId: string\n\n lock: AsyncLock\n\n readOnly: Boolean\n\n logger: Debugger\n\n /**\n * Constructor.\n */\n constructor(\n connection: WebSocket,\n request: HTTPIncomingMessage,\n document: Document,\n timeout: number,\n socketId: string,\n context: any,\n readOnly = false,\n logger: Debugger,\n ) {\n this.webSocket = connection\n this.context = context\n this.document = document\n this.request = request\n this.timeout = timeout\n this.socketId = socketId\n this.readOnly = readOnly\n this.logger = logger\n\n this.lock = new AsyncLock()\n\n this.webSocket.binaryType = 'arraybuffer'\n this.document.addConnection(this)\n\n this.pingInterval = setInterval(this.check.bind(this), this.timeout)\n\n this.webSocket.on('close', this.boundClose)\n this.webSocket.on('message', this.boundHandleMessage)\n this.webSocket.on('pong', this.boundHandlePong)\n\n this.sendCurrentAwareness()\n }\n\n boundClose = this.close.bind(this)\n\n boundHandleMessage = this.handleMessage.bind(this)\n\n boundHandlePong = this.handlePong.bind(this)\n\n handlePong() {\n this.pongReceived = true\n }\n\n /**\n * Set a callback that will be triggered when the connection is closed\n */\n onClose(callback: (document: Document, event?: CloseEvent) => void): Connection {\n this.callbacks.onClose.push(callback)\n\n return this\n }\n\n /**\n * Set a callback that will be triggered when an stateless message is received\n */\n onStatelessCallback(callback: (payload: onStatelessPayload) => Promise): Connection {\n this.callbacks.statelessCallback = callback\n\n return this\n }\n\n /**\n * Set a callback that will be triggered before an message is handled\n */\n beforeHandleMessage(callback: (connection: Connection, update: Uint8Array) => Promise): Connection {\n this.callbacks.beforeHandleMessage = callback\n\n return this\n }\n\n /**\n * Send the given message\n */\n send(message: any): void {\n if (\n this.webSocket.readyState === WsReadyStates.Closing\n || this.webSocket.readyState === WsReadyStates.Closed\n ) {\n this.close()\n }\n\n try {\n this.webSocket.send(message, (error: any) => {\n if (error != null) this.close()\n })\n } catch (exception) {\n this.close()\n }\n }\n\n /**\n * Send a stateless message with payload\n */\n public sendStateless(payload: string): void {\n const message = new OutgoingMessage(this.document.name)\n .writeStateless(payload)\n\n this.logger.log({\n direction: 'out',\n type: message.type,\n category: message.category,\n })\n\n this.send(\n message.toUint8Array(),\n )\n }\n\n /**\n * Graceful wrapper around the WebSocket close method.\n */\n close(event?: CloseEvent): void {\n this.lock.acquire('close', (done: Function) => {\n if (this.pingInterval) {\n clearInterval(this.pingInterval)\n }\n\n if (this.document.hasConnection(this)) {\n this.document.removeConnection(this)\n clearInterval(this.pingInterval)\n\n this.webSocket.removeListener('close', this.boundClose)\n this.webSocket.removeListener('message', this.boundHandleMessage)\n this.webSocket.removeListener('pong', this.boundHandlePong)\n\n this.callbacks.onClose.forEach((callback: (arg0: Document, arg1?: CloseEvent) => any) => callback(this.document, event))\n }\n\n done()\n })\n }\n\n /**\n * Check if pong was received and close the connection otherwise\n * @private\n */\n private check(): void {\n if (!this.pongReceived) {\n return this.close(ConnectionTimeout)\n }\n\n if (this.document.hasConnection(this)) {\n this.pongReceived = false\n\n try {\n this.webSocket.ping()\n } catch (error) {\n this.close(ConnectionTimeout)\n }\n }\n }\n\n /**\n * Send the current document awareness to the client, if any\n * @private\n */\n private sendCurrentAwareness(): void {\n if (!this.document.hasAwarenessStates()) {\n return\n }\n\n const awarenessMessage = new OutgoingMessage(this.document.name)\n .createAwarenessUpdateMessage(this.document.awareness)\n\n this.logger.log({\n direction: 'out',\n type: awarenessMessage.type,\n category: awarenessMessage.category,\n })\n\n this.send(awarenessMessage.toUint8Array())\n }\n\n /**\n * Handle an incoming message\n * @private\n */\n private handleMessage(data: Uint8Array): void {\n const message = new IncomingMessage(data)\n const documentName = message.readVarString()\n\n if (documentName !== this.document.name) return\n\n message.writeVarString(documentName)\n\n this.callbacks.beforeHandleMessage(this, data)\n .then(() => {\n new MessageReceiver(\n message,\n this.logger,\n ).apply(this.document, this)\n })\n .catch((e: any) => {\n console.log('closing connection because of exception', e)\n this.close({\n code: 'code' in e ? e.code : Forbidden.code,\n reason: 'reason' in e ? e.reason : Forbidden.reason,\n })\n })\n }\n\n}\n\nexport default Connection\n","// import * as time from 'lib0/time'\nimport { MessageType } from './types.js'\n\nexport class Debugger {\n logs: any[] = []\n\n listen = false\n\n output = false\n\n enable() {\n this.flush()\n\n this.listen = true\n }\n\n disable() {\n this.listen = false\n }\n\n verbose() {\n this.output = true\n }\n\n quiet() {\n this.output = false\n }\n\n log(message: any) {\n if (!this.listen) {\n return this\n }\n\n const item = {\n ...message,\n type: MessageType[message.type],\n // time: time.getUnixTime(),\n }\n\n this.logs.push(item)\n\n if (this.output) {\n console.log('[DEBUGGER]', item.direction === 'in' ? 'IN –>' : 'OUT <–', `${item.type}/${item.category}`)\n }\n\n return this\n }\n\n flush() {\n this.logs = []\n\n return this\n }\n\n get() {\n return {\n logs: this.logs,\n }\n }\n}\n","/**\n * Mutual exclude for JavaScript.\n *\n * @module mutex\n */\n\n/**\n * @callback mutex\n * @param {function():void} cb Only executed when this mutex is not in the current stack\n * @param {function():void} [elseCb] Executed when this mutex is in the current stack\n */\n\n/**\n * Creates a mutual exclude function with the following property:\n *\n * ```js\n * const mutex = createMutex()\n * mutex(() => {\n * // This function is immediately executed\n * mutex(() => {\n * // This function is not executed, as the mutex is already active.\n * })\n * })\n * ```\n *\n * @return {mutex} A mutual exclude function\n * @public\n */\nexport const createMutex = () => {\n let token = true\n return (f, g) => {\n if (token) {\n token = false\n try {\n f()\n } finally {\n token = true\n }\n } else if (g !== undefined) {\n g()\n }\n }\n}\n","import WebSocket from 'ws'\nimport { Awareness, removeAwarenessStates, applyAwarenessUpdate } from 'y-protocols/awareness'\nimport { applyUpdate, Doc, encodeStateAsUpdate } from 'yjs'\nimport { mutex, createMutex } from 'lib0/mutex.js'\nimport { AwarenessUpdate } from './types.js'\nimport Connection from './Connection.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { Debugger } from './Debugger.js'\n\nexport class Document extends Doc {\n\n awareness: Awareness\n\n callbacks = {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n onUpdate: (document: Document, connection: Connection, update: Uint8Array) => {},\n beforeBroadcastStateless: (document: Document, stateless: string) => {},\n }\n\n connections: Map,\n connection: Connection\n }> = new Map()\n\n // The number of direct (non-websocket) connections to this document\n directConnectionsCount = 0\n\n name: string\n\n mux: mutex\n\n logger: Debugger\n\n isLoading: boolean\n\n /**\n * Constructor.\n */\n constructor(name: string, logger: Debugger, yDocOptions: {}) {\n super(yDocOptions)\n\n this.name = name\n this.mux = createMutex()\n\n this.awareness = new Awareness(this)\n this.awareness.setLocalState(null)\n\n this.awareness.on('update', this.handleAwarenessUpdate.bind(this))\n this.on('update', this.handleUpdate.bind(this))\n\n this.logger = logger\n this.isLoading = true\n }\n\n /**\n * Check if the Document is empty\n */\n isEmpty(fieldName: string): boolean {\n // eslint-disable-next-line no-underscore-dangle\n return !this.get(fieldName)._start\n }\n\n /**\n * Merge the given document(s) into this one\n */\n merge(documents: Doc|Array): Document {\n (Array.isArray(documents) ? documents : [documents]).forEach(document => {\n applyUpdate(this, encodeStateAsUpdate(document))\n })\n\n return this\n }\n\n /**\n * Set a callback that will be triggered when the document is updated\n */\n onUpdate(callback: (document: Document, connection: Connection, update: Uint8Array) => void): Document {\n this.callbacks.onUpdate = callback\n\n return this\n }\n\n /**\n * Set a callback that will be triggered before a stateless message is broadcasted\n */\n beforeBroadcastStateless(callback: (document: Document, stateless: string) => void): Document {\n this.callbacks.beforeBroadcastStateless = callback\n\n return this\n }\n\n /**\n * Register a connection and a set of clients on this document keyed by the\n * underlying websocket connection\n */\n addConnection(connection: Connection): Document {\n this.connections.set(connection.webSocket, {\n clients: new Set(),\n connection,\n })\n\n return this\n }\n\n /**\n * Is the given connection registered on this document\n */\n hasConnection(connection: Connection): boolean {\n return this.connections.has(connection.webSocket)\n }\n\n /**\n * Remove the given connection from this document\n */\n removeConnection(connection: Connection): Document {\n removeAwarenessStates(\n this.awareness,\n Array.from(this.getClients(connection.webSocket)),\n null,\n )\n\n this.connections.delete(connection.webSocket)\n\n return this\n }\n\n addDirectConnection(): Document {\n this.directConnectionsCount += 1\n\n return this\n }\n\n removeDirectConnection(): Document {\n if (this.directConnectionsCount > 0) {\n this.directConnectionsCount -= 1\n }\n\n return this\n }\n\n /**\n * Get the number of active connections for this document\n */\n getConnectionsCount(): number {\n return this.connections.size + this.directConnectionsCount\n }\n\n /**\n * Get an array of registered connections\n */\n getConnections(): Array {\n return Array.from(this.connections.values()).map(data => data.connection)\n }\n\n /**\n * Get the client ids for the given connection instance\n */\n getClients(connectionInstance: WebSocket): Set {\n const connection = this.connections.get(connectionInstance)\n\n return connection?.clients === undefined ? new Set() : connection.clients\n }\n\n /**\n * Has the document awareness states\n */\n hasAwarenessStates(): boolean {\n return this.awareness.getStates().size > 0\n }\n\n /**\n * Apply the given awareness update\n */\n applyAwarenessUpdate(connection: Connection, update: Uint8Array): Document {\n applyAwarenessUpdate(\n this.awareness,\n update,\n connection.webSocket,\n )\n\n return this\n }\n\n /**\n * Handle an awareness update and sync changes to clients\n * @private\n */\n private handleAwarenessUpdate(\n { added, updated, removed }: AwarenessUpdate,\n connectionInstance: WebSocket,\n ): Document {\n const changedClients = added.concat(updated, removed)\n\n if (connectionInstance !== null) {\n const connection = this.connections.get(connectionInstance)\n\n if (connection) {\n added.forEach((clientId: any) => connection.clients.add(clientId))\n removed.forEach((clientId: any) => connection.clients.delete(clientId))\n }\n }\n\n this.getConnections().forEach(connection => {\n const awarenessMessage = new OutgoingMessage(this.name)\n .createAwarenessUpdateMessage(this.awareness, changedClients)\n\n this.logger.log({\n direction: 'out',\n type: awarenessMessage.type,\n category: awarenessMessage.category,\n })\n\n connection.send(\n awarenessMessage.toUint8Array(),\n )\n })\n\n return this\n }\n\n /**\n * Handle an updated document and sync changes to clients\n */\n private handleUpdate(update: Uint8Array, connection: Connection): Document {\n this.callbacks.onUpdate(this, connection, update)\n\n const message = new OutgoingMessage(this.name)\n .createSyncMessage()\n .writeUpdate(update)\n\n this.getConnections().forEach(connection => {\n this.logger.log({\n direction: 'out',\n type: message.type,\n category: message.category,\n })\n\n connection.send(\n message.toUint8Array(),\n )\n })\n\n return this\n }\n\n /**\n * Broadcast stateless message to all connections\n */\n public broadcastStateless(payload: string): void {\n this.callbacks.beforeBroadcastStateless(this, payload)\n\n this.getConnections().forEach(connection => {\n connection.sendStateless(payload)\n })\n }\n}\n\nexport default Document\n","import { URLSearchParams } from 'url'\nimport Document from './Document.js'\nimport type { Hocuspocus } from './Hocuspocus.js'\n\nexport class DirectConnection {\n document: Document | null = null\n\n instance!: Hocuspocus\n\n context: any\n\n /**\n * Constructor.\n */\n constructor(\n document: Document,\n instance: Hocuspocus,\n context?: any,\n ) {\n this.document = document\n this.instance = instance\n this.context = context\n\n this.document.addDirectConnection()\n }\n\n async transact(transaction: (document: Document) => void) {\n if (!this.document) {\n throw new Error('direct connection closed')\n }\n\n transaction(this.document)\n\n this.instance.storeDocumentHooks(this.document, {\n clientsCount: this.document.getConnectionsCount(),\n context: this.context,\n document: this.document,\n documentName: this.document.name,\n instance: this.instance,\n requestHeaders: {},\n requestParameters: new URLSearchParams(),\n socketId: 'server',\n })\n }\n\n disconnect() {\n this.document?.removeDirectConnection()\n this.document = null\n }\n}\n","import { createServer, IncomingMessage, Server as HTTPServer } from 'http'\nimport { URLSearchParams } from 'url'\nimport { ListenOptions } from 'net'\nimport * as decoding from 'lib0/decoding'\nimport WebSocket, { AddressInfo, WebSocketServer } from 'ws'\nimport { Doc, encodeStateAsUpdate, applyUpdate } from 'yjs'\nimport { v4 as uuid } from 'uuid'\nimport kleur from 'kleur'\nimport {\n ResetConnection,\n Unauthorized,\n Forbidden,\n awarenessStatesToArray,\n WsReadyStates,\n} from '@hocuspocus/common'\nimport meta from '../package.json' assert {type: 'json'}\nimport { IncomingMessage as SocketIncomingMessage } from './IncomingMessage.js'\nimport {\n MessageType,\n Configuration,\n ConnectionConfiguration,\n HookName,\n AwarenessUpdate,\n HookPayload,\n beforeHandleMessagePayload,\n beforeBroadcastStatelessPayload,\n onListenPayload,\n onStoreDocumentPayload,\n} from './types.js'\nimport Document from './Document.js'\nimport Connection from './Connection.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { Debugger } from './Debugger.js'\nimport { DirectConnection } from './DirectConnection.js'\n\nexport const defaultConfiguration = {\n name: null,\n port: 80,\n address: '0.0.0.0',\n timeout: 30000,\n debounce: 2000,\n maxDebounce: 10000,\n quiet: false,\n yDocOptions: {\n gc: true,\n gcFilter: () => true,\n },\n}\n\n/**\n * Hocuspocus Server\n */\nexport class Hocuspocus {\n configuration: Configuration = {\n ...defaultConfiguration,\n extensions: [],\n onConfigure: () => new Promise(r => r(null)),\n onListen: () => new Promise(r => r(null)),\n onUpgrade: () => new Promise(r => r(null)),\n onConnect: () => new Promise(r => r(null)),\n connected: () => new Promise(r => r(null)),\n beforeHandleMessage: () => new Promise(r => r(null)),\n beforeBroadcastStateless: () => new Promise(r => r(null)),\n onStateless: () => new Promise(r => r(null)),\n onChange: () => new Promise(r => r(null)),\n onLoadDocument: () => new Promise(r => r(null)),\n onStoreDocument: () => new Promise(r => r(null)),\n afterStoreDocument: () => new Promise(r => r(null)),\n onAwarenessUpdate: () => new Promise(r => r(null)),\n onRequest: () => new Promise(r => r(null)),\n onDisconnect: () => new Promise(r => r(null)),\n onDestroy: () => new Promise(r => r(null)),\n }\n\n documents: Map = new Map()\n\n httpServer?: HTTPServer\n\n webSocketServer?: WebSocketServer\n\n debugger = new Debugger()\n\n constructor(configuration?: Partial) {\n if (configuration) {\n this.configure(configuration)\n }\n }\n\n /**\n * Configure the server\n */\n configure(configuration: Partial): Hocuspocus {\n this.configuration = {\n ...this.configuration,\n ...configuration,\n }\n\n this.configuration.extensions.sort((a, b) => {\n const one = typeof a.priority === 'undefined' ? 100 : a.priority\n const two = typeof b.priority === 'undefined' ? 100 : b.priority\n\n if (one > two) {\n return -1\n }\n\n if (one < two) {\n return 1\n }\n\n return 0\n })\n\n this.configuration.extensions.push({\n onConfigure: this.configuration.onConfigure,\n onListen: this.configuration.onListen,\n onUpgrade: this.configuration.onUpgrade,\n onConnect: this.configuration.onConnect,\n connected: this.configuration.connected,\n onAuthenticate: this.configuration.onAuthenticate,\n onLoadDocument: this.configuration.onLoadDocument,\n beforeHandleMessage: this.configuration.beforeHandleMessage,\n beforeBroadcastStateless: this.configuration.beforeBroadcastStateless,\n onStateless: this.configuration.onStateless,\n onChange: this.configuration.onChange,\n onStoreDocument: this.configuration.onStoreDocument,\n afterStoreDocument: this.configuration.afterStoreDocument,\n onAwarenessUpdate: this.configuration.onAwarenessUpdate,\n onRequest: this.configuration.onRequest,\n onDisconnect: this.configuration.onDisconnect,\n onDestroy: this.configuration.onDestroy,\n })\n\n this.hooks('onConfigure', {\n configuration: this.configuration,\n version: meta.version,\n instance: this,\n })\n\n return this\n }\n\n get requiresAuthentication(): boolean {\n return !!this.configuration.extensions.find(extension => {\n return extension.onAuthenticate !== undefined\n })\n }\n\n /**\n * Start the server\n */\n async listen(\n portOrCallback: number | ((data: onListenPayload) => Promise) | null = null,\n callback: any = null,\n ): Promise {\n if (typeof portOrCallback === 'number') {\n this.configuration.port = portOrCallback\n }\n\n if (typeof portOrCallback === 'function') {\n this.configuration.extensions.push({\n onListen: portOrCallback,\n })\n }\n\n if (typeof callback === 'function') {\n this.configuration.extensions.push({\n onListen: callback,\n })\n }\n\n const webSocketServer = new WebSocketServer({ noServer: true })\n\n webSocketServer.on('connection', async (incoming: WebSocket, request: IncomingMessage) => {\n\n incoming.on('error', error => {\n /**\n * Handle a ws instance error, which is required to prevent\n * the server from crashing when one happens\n * See https://github.com/websockets/ws/issues/1777#issuecomment-660803472\n * @private\n */\n this.debugger.log('Error emitted from webSocket instance:')\n this.debugger.log(error)\n })\n\n this.handleConnection(incoming, request)\n })\n\n const server = createServer((request, response) => {\n this.hooks('onRequest', { request, response, instance: this })\n .then(() => {\n // default response if all prior hooks don't interfere\n response.writeHead(200, { 'Content-Type': 'text/plain' })\n response.end('OK')\n })\n .catch(error => {\n // if a hook rejects and the error is empty, do nothing\n // this is only meant to prevent later hooks and the\n // default handler to do something. if a error is present\n // just rethrow it\n if (error) {\n throw error\n }\n })\n })\n\n server.on('upgrade', (request, socket, head) => {\n this.hooks('onUpgrade', {\n request,\n socket,\n head,\n instance: this,\n })\n .then(() => {\n // let the default websocket server handle the connection if\n // prior hooks don't interfere\n webSocketServer.handleUpgrade(request, socket, head, ws => {\n webSocketServer.emit('connection', ws, request)\n })\n })\n .catch(error => {\n // if a hook rejects and the error is empty, do nothing\n // this is only meant to prevent later hooks and the\n // default handler to do something. if a error is present\n // just rethrow it\n if (error) {\n throw error\n }\n })\n })\n\n this.httpServer = server\n this.webSocketServer = webSocketServer\n\n return new Promise((resolve: Function, reject: Function) => {\n server.listen({\n port: this.configuration.port,\n host: this.configuration.address,\n } as ListenOptions, () => {\n if (!this.configuration.quiet && process.env.NODE_ENV !== 'testing') {\n this.showStartScreen()\n }\n\n const onListenPayload = {\n instance: this,\n configuration: this.configuration,\n port: this.address.port,\n }\n\n this.hooks('onListen', onListenPayload)\n .then(() => resolve(this))\n .catch(error => reject(error))\n })\n })\n }\n\n get address(): AddressInfo {\n return (this.httpServer?.address() || {\n port: this.configuration.port,\n address: this.configuration.address,\n family: 'IPv4',\n }) as AddressInfo\n }\n\n get URL(): string {\n return `${this.configuration.address}:${this.address.port}`\n }\n\n get webSocketURL(): string {\n return `ws://${this.URL}`\n }\n\n get httpURL(): string {\n return `http://${this.URL}`\n }\n\n private showStartScreen() {\n const name = this.configuration.name ? ` (${this.configuration.name})` : ''\n\n console.log()\n console.log(` ${kleur.cyan(`Hocuspocus v${meta.version}${name}`)}${kleur.green(' running at:')}`)\n console.log()\n console.log(` > HTTP: ${kleur.cyan(`${this.httpURL}`)}`)\n console.log(` > WebSocket: ${this.webSocketURL}`)\n\n const extensions = this.configuration?.extensions.map(extension => {\n return extension.constructor?.name\n })\n .filter(name => name)\n .filter(name => name !== 'Object')\n\n if (!extensions.length) {\n return\n }\n\n console.log()\n console.log(' Extensions:')\n\n extensions\n .forEach(name => {\n console.log(` - ${name}`)\n })\n\n console.log()\n console.log(` ${kleur.green('Ready.')}`)\n console.log()\n }\n\n /**\n * Get the total number of active documents\n */\n getDocumentsCount(): number {\n return this.documents.size\n }\n\n /**\n * Get the total number of active connections\n */\n getConnectionsCount(): number {\n return Array.from(this.documents.values()).reduce((acc, document) => {\n acc += document.getConnectionsCount()\n return acc\n }, 0)\n }\n\n /**\n * Force close one or more connections\n */\n closeConnections(documentName?: string) {\n // Iterate through all connections for all documents\n // and invoke their close method, which is a graceful\n // disconnect wrapper around the underlying websocket.close\n this.documents.forEach((document: Document) => {\n // If a documentName was specified, bail if it doesnt match\n if (documentName && document.name !== documentName) {\n return\n }\n\n document.connections.forEach(({ connection }) => {\n connection.close(ResetConnection)\n })\n })\n }\n\n /**\n * Destroy the server\n */\n async destroy(): Promise {\n this.httpServer?.close()\n\n try {\n this.webSocketServer?.close()\n this.webSocketServer?.clients.forEach(client => {\n client.terminate()\n })\n } catch (error) {\n console.error(error)\n //\n }\n\n this.debugger.flush()\n\n await this.hooks('onDestroy', { instance: this })\n }\n\n /**\n * The `handleConnection` method receives incoming WebSocket connections,\n * runs all hooks:\n *\n * - onConnect for all connections\n * - onAuthenticate only if required\n *\n * … and if nothings fails it’ll fully establish the connection and\n * load the Document then.\n */\n handleConnection(incoming: WebSocket, request: IncomingMessage, context: any = null): void {\n // Make sure to close an idle connection after a while.\n const closeIdleConnection = setTimeout(() => {\n incoming.close(Unauthorized.code, Unauthorized.reason)\n }, this.configuration.timeout)\n\n // Every new connection gets a unique identifier.\n const socketId = uuid()\n\n // To override settings for specific connections, we’ll\n // keep track of a few things in the `ConnectionConfiguration`.\n const connection: ConnectionConfiguration = {\n readOnly: false,\n requiresAuthentication: this.requiresAuthentication,\n isAuthenticated: false,\n }\n\n // The `onConnect` and `onAuthenticate` hooks need some context\n // to decide who’s connecting, so let’s put it together:\n const hookPayload = {\n instance: this,\n request,\n requestHeaders: request.headers,\n requestParameters: Hocuspocus.getParameters(request),\n socketId,\n connection,\n }\n\n // this map indicates whether a `Connection` instance has already taken over for incoming message for the key (i.e. documentName)\n const documentConnections: Record = {}\n\n // While the connection will be establishing messages will\n // be queued and handled later.\n const incomingMessageQueue: Record = {}\n\n // While the connection is establishing\n const connectionEstablishing: Record = {}\n\n // Once all hooks are run, we’ll fully establish the connection:\n const setUpNewConnection = async (documentName: string) => {\n // Not an idle connection anymore, no need to close it then.\n clearTimeout(closeIdleConnection)\n\n // If no hook interrupts, create a document and connection\n const document = await this.createDocument(documentName, request, socketId, connection, context)\n const instance = this.createConnection(incoming, request, document, socketId, connection.readOnly, context)\n\n instance.onClose((document, event) => {\n delete documentConnections[documentName]\n delete incomingMessageQueue[documentName]\n delete connectionEstablishing[documentName]\n\n if (Object.keys(documentConnections).length === 0) {\n instance.webSocket.close(event?.code, event?.reason) // TODO: Move this to Hocuspocus connection handler\n }\n })\n\n documentConnections[documentName] = true\n\n // There’s no need to queue messages anymore.\n // Let’s work through queued messages.\n incomingMessageQueue[documentName].forEach(input => {\n incoming.emit('message', input)\n })\n\n this.hooks('connected', {\n ...hookPayload,\n documentName,\n context,\n connectionInstance: instance,\n })\n }\n\n // This listener handles authentication messages and queues everything else.\n const handleQueueingMessage = (data: Uint8Array) => {\n try {\n const tmpMsg = new SocketIncomingMessage(data)\n\n const documentName = decoding.readVarString(tmpMsg.decoder)\n const type = decoding.readVarUint(tmpMsg.decoder)\n\n // Okay, we’ve got the authentication message we’re waiting for:\n if (type === MessageType.Auth && !connectionEstablishing[documentName]) {\n connectionEstablishing[documentName] = true\n\n // The 2nd integer contains the submessage type\n // which will always be authentication when sent from client -> server\n decoding.readVarUint(tmpMsg.decoder)\n const token = decoding.readVarString(tmpMsg.decoder)\n\n this.debugger.log({\n direction: 'in',\n type,\n category: 'Token',\n })\n\n this.hooks('onAuthenticate', {\n token,\n ...hookPayload,\n documentName,\n }, (contextAdditions: any) => {\n // Hooks are allowed to give us even more context and we’ll merge everything together.\n // We’ll pass the context to other hooks then.\n context = { ...context, ...contextAdditions }\n })\n .then(() => {\n // All `onAuthenticate` hooks passed.\n connection.isAuthenticated = true\n\n // Let the client know that authentication was successful.\n const message = new OutgoingMessage(documentName).writeAuthenticated(connection.readOnly)\n\n this.debugger.log({\n direction: 'out',\n type: message.type,\n category: message.category,\n })\n\n incoming.send(message.toUint8Array())\n })\n .then(() => {\n // Time to actually establish the connection.\n return setUpNewConnection(documentName)\n })\n .catch((error = Forbidden) => {\n const message = new OutgoingMessage(documentName).writePermissionDenied(error.reason ?? 'permission-denied')\n\n this.debugger.log({\n direction: 'out',\n type: message.type,\n category: message.category,\n })\n\n // Ensure that the permission denied message is sent before the\n // connection is closed\n incoming.send(message.toUint8Array(), () => {\n if (Object.keys(documentConnections).length === 0) {\n try {\n incoming.close(error.code ?? Forbidden.code, error.reason ?? Forbidden.reason)\n } catch (closeError) {\n // catch is needed in case invalid error code is returned by hook (that would fail sending the close message)\n console.error(closeError)\n incoming.close(Forbidden.code, Forbidden.reason)\n }\n }\n })\n })\n } else {\n incomingMessageQueue[documentName].push(data)\n }\n\n // Catch errors due to failed decoding of data\n } catch (error) {\n console.error(error)\n incoming.close(Unauthorized.code, Unauthorized.reason)\n }\n }\n\n const messageHandler = (data: Uint8Array) => {\n try {\n const tmpMsg = new SocketIncomingMessage(data)\n\n const documentName = decoding.readVarString(tmpMsg.decoder)\n\n if (documentConnections[documentName] === true) {\n // we already have a `Connection` set up for this document\n return\n }\n\n // if this is the first message, trigger onConnect & check if we can start the connection (only if no auth is required)\n if (incomingMessageQueue[documentName] === undefined) {\n incomingMessageQueue[documentName] = []\n\n this.hooks('onConnect', { ...hookPayload, documentName }, (contextAdditions: any) => {\n // merge context from all hooks\n context = { ...context, ...contextAdditions }\n })\n .then(() => {\n // Authentication is required, we’ll need to wait for the Authentication message.\n if (connection.requiresAuthentication || connectionEstablishing[documentName]) {\n return\n }\n connectionEstablishing[documentName] = true\n\n return setUpNewConnection(documentName)\n })\n .catch((error = Forbidden) => {\n // if a hook interrupts, close the websocket connection\n try {\n incoming.close(error.code ?? Forbidden.code, error.reason ?? Forbidden.reason)\n } catch (closeError) {\n // catch is needed in case invalid error code is returned by hook (that would fail sending the close message)\n console.error(closeError)\n incoming.close(Unauthorized.code, Unauthorized.reason)\n }\n })\n }\n\n handleQueueingMessage(data)\n } catch (closeError) {\n // catch is needed in case an invalid payload crashes the parsing of the Uint8Array\n console.error(closeError)\n incoming.close(Unauthorized.code, Unauthorized.reason)\n }\n\n }\n\n incoming.on('message', messageHandler)\n }\n\n /**\n * Handle update of the given document\n */\n private handleDocumentUpdate(document: Document, connection: Connection | undefined, update: Uint8Array, request?: IncomingMessage): void {\n const hookPayload = {\n instance: this,\n clientsCount: document.getConnectionsCount(),\n context: connection?.context || {},\n document,\n documentName: document.name,\n requestHeaders: request?.headers ?? {},\n requestParameters: Hocuspocus.getParameters(request),\n socketId: connection?.socketId ?? '',\n update,\n }\n\n this.hooks('onChange', hookPayload).catch(error => {\n throw error\n })\n\n // If the update was received through other ways than the\n // WebSocket connection, we don’t need to feel responsible for\n // storing the content.\n if (!connection) {\n return\n }\n\n this.debounce(`onStoreDocument-${document.name}`, () => {\n this.storeDocumentHooks(document, hookPayload)\n })\n }\n\n timers: Map = new Map()\n\n /**\n * debounce the given function, using the given identifier\n */\n debounce(id: string, func: Function, immediately = false) {\n const old = this.timers.get(id)\n const start = old?.start || Date.now()\n\n const run = () => {\n this.timers.delete(id)\n func()\n }\n\n if (old?.timeout) {\n clearTimeout(old.timeout)\n }\n\n if (immediately) {\n return run()\n }\n\n if (Date.now() - start >= this.configuration.maxDebounce) {\n return run()\n }\n\n this.timers.set(id, {\n start,\n timeout: setTimeout(run, this.configuration.debounce),\n })\n }\n\n /**\n * Create a new document by the given request\n */\n private async createDocument(documentName: string, request: Partial>, socketId: string, connection: ConnectionConfiguration, context?: any): Promise {\n if (this.documents.has(documentName)) {\n const document = this.documents.get(documentName)\n\n if (document) {\n return document\n }\n }\n\n const document = new Document(documentName, this.debugger, this.configuration.yDocOptions)\n this.documents.set(documentName, document)\n\n const hookPayload = {\n instance: this,\n context,\n connection,\n document,\n documentName,\n socketId,\n requestHeaders: request.headers,\n requestParameters: Hocuspocus.getParameters(request),\n }\n\n try {\n await this.hooks('onLoadDocument', hookPayload, (loadedDocument: Doc | undefined) => {\n // if a hook returns a Y-Doc, encode the document state as update\n // and apply it to the newly created document\n // Note: instanceof doesn't work, because Doc !== Doc for some reason I don't understand\n if (\n loadedDocument?.constructor.name === 'Document'\n || loadedDocument?.constructor.name === 'Doc'\n ) {\n applyUpdate(document, encodeStateAsUpdate(loadedDocument))\n }\n })\n } catch (e) {\n this.closeConnections(documentName)\n this.documents.delete(documentName)\n throw e\n }\n\n document.isLoading = false\n await this.hooks('afterLoadDocument', hookPayload)\n\n document.onUpdate((document: Document, connection: Connection, update: Uint8Array) => {\n this.handleDocumentUpdate(document, connection, update, connection?.request)\n })\n\n document.beforeBroadcastStateless((document: Document, stateless: string) => {\n const hookPayload: beforeBroadcastStatelessPayload = {\n document,\n documentName: document.name,\n payload: stateless,\n }\n\n this.hooks('beforeBroadcastStateless', hookPayload)\n })\n\n document.awareness.on('update', (update: AwarenessUpdate) => {\n this.hooks('onAwarenessUpdate', {\n ...hookPayload,\n ...update,\n awareness: document.awareness,\n states: awarenessStatesToArray(document.awareness.getStates()),\n })\n })\n\n return document\n }\n\n /**\n * Create a new connection by the given request and document\n */\n private createConnection(connection: WebSocket, request: IncomingMessage, document: Document, socketId: string, readOnly = false, context?: any): Connection {\n const instance = new Connection(\n connection,\n request,\n document,\n this.configuration.timeout,\n socketId,\n context,\n readOnly,\n this.debugger,\n )\n\n instance.onClose(document => {\n const hookPayload = {\n instance: this,\n clientsCount: document.getConnectionsCount(),\n context,\n document,\n socketId,\n documentName: document.name,\n requestHeaders: request.headers,\n requestParameters: Hocuspocus.getParameters(request),\n }\n\n this.hooks('onDisconnect', hookPayload).then(() => {\n // Check if there are still no connections to the document, as these hooks\n // may take some time to resolve (e.g. database queries). If a\n // new connection were to come in during that time it would rely on the\n // document in the map that we remove now.\n if (document.getConnectionsCount() > 0) {\n return\n }\n\n // If it’s the last connection, we need to make sure to store the\n // document. Use the debounce helper, to clear running timers,\n // but make it run immediately (`true`).\n // Only run this if the document has finished loading earlier (i.e. not to persist the empty\n // ydoc if the onLoadDocument hook returned an error)\n if (!document.isLoading) {\n this.debounce(`onStoreDocument-${document.name}`, () => {\n this.storeDocumentHooks(document, hookPayload)\n }, true)\n\n } else {\n // Remove document from memory immediately\n this.documents.delete(document.name)\n document.destroy()\n }\n })\n\n })\n\n instance.onStatelessCallback(payload => {\n return this.hooks('onStateless', payload)\n .catch(error => {\n if (error?.message) {\n throw error\n }\n })\n })\n\n instance.beforeHandleMessage((connection, update) => {\n const hookPayload: beforeHandleMessagePayload = {\n instance: this,\n clientsCount: document.getConnectionsCount(),\n context,\n document,\n socketId,\n connection,\n documentName: document.name,\n requestHeaders: request.headers,\n requestParameters: Hocuspocus.getParameters(request),\n update,\n }\n\n return this.hooks('beforeHandleMessage', hookPayload)\n })\n\n // If the WebSocket has already disconnected (wow, that was fast) – then\n // immediately call close to cleanup the connection and document in memory.\n if (\n connection.readyState === WsReadyStates.Closing\n || connection.readyState === WsReadyStates.Closed\n ) {\n instance.close()\n }\n\n return instance\n }\n\n storeDocumentHooks(document: Document, hookPayload: onStoreDocumentPayload) {\n this.hooks('onStoreDocument', hookPayload)\n .catch(error => {\n if (error?.message) {\n throw error\n }\n })\n .then(() => {\n this.hooks('afterStoreDocument', hookPayload).then(() => {\n // Remove document from memory.\n\n if (document.getConnectionsCount() > 0) {\n return\n }\n\n this.documents.delete(document.name)\n document.destroy()\n })\n })\n }\n\n /**\n * Run the given hook on all configured extensions.\n * Runs the given callback after each hook.\n */\n hooks(name: HookName, payload: HookPayload, callback: Function | null = null): Promise {\n const { extensions } = this.configuration\n\n // create a new `thenable` chain\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve\n let chain = Promise.resolve()\n\n extensions\n // get me all extensions which have the given hook\n .filter(extension => typeof extension[name] === 'function')\n // run through all the configured hooks\n .forEach(extension => {\n chain = chain\n .then(() => (extension[name] as any)?.(payload))\n .catch(error => {\n // make sure to log error messages\n if (error?.message) {\n console.error(`[${name}]`, error.message)\n }\n\n throw error\n })\n\n if (callback) {\n chain = chain.then((...args: any[]) => callback(...args))\n }\n })\n\n return chain\n }\n\n /**\n * Get parameters by the given request\n */\n private static getParameters(request?: Pick): URLSearchParams {\n const query = request?.url?.split('?') || []\n return new URLSearchParams(query[1] ? query[1] : '')\n }\n\n enableDebugging() {\n this.debugger.enable()\n }\n\n enableMessageLogging() {\n this.debugger.enable()\n this.debugger.verbose()\n }\n\n disableLogging() {\n this.debugger.quiet()\n }\n\n disableDebugging() {\n this.debugger.disable()\n }\n\n flushMessageLogs() {\n this.debugger.flush()\n\n return this\n }\n\n getMessageLogs() {\n return this.debugger.get()?.logs\n }\n\n async openDirectConnection(documentName: string, context?: any): Promise {\n const connectionConfig: ConnectionConfiguration = {\n isAuthenticated: true,\n readOnly: false,\n requiresAuthentication: true,\n }\n\n const document: Document = await this.createDocument(\n documentName,\n {}, // direct connection has no request params\n uuid(),\n connectionConfig,\n context,\n )\n\n return new DirectConnection(document, this, context)\n }\n}\n\nexport const Server = new Hocuspocus()\n"],"names":["create","length","object.length","object.hasProperty","map.create","string.fromCamelCase","conditions.undefinedToNull","storage.varStorage","f.isOneOf","buffer.createUint8ArrayViewFromArrayBuffer","binary.BITS7","binary.BIT8","math.floor","string.utf8TextEncoder","string.encodeUtf8","math.min","math.max","error.create","number.MAX_SAFE_INTEGER","string.utf8TextDecoder","encoding.writeVarUint","encoding.writeVarUint8Array","decoding.readVarUint8Array","map.setIfUndefined","set.create","array.from","time.getUnixTime","f.equalityDeep","encoding.createEncoder","encoding.writeVarString","encoding.toUint8Array","decoding.createDecoder","decoding.readVarUint","decoding.readVarString","uuid","SocketIncomingMessage"],"mappings":";;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AAIA;AACA;AACA;AACA;AACA;AACA,MAAM,WAAW,GAAG,CAAC,IAAI,CAAC,CAAC,WAAW,GAAE;AACxC;AACA,MAAM,aAAa,GAAG,QAAO;AAC7B;AACA;AACA;AACA;AACA;AACO,MAAM,QAAQ,GAAG,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,aAAa,EAAE,EAAE,EAA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AE,MAAE,IAAA,IAAA,EAAA,KAAA,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,IAAI,CAAA;KACjC;AAED,IAAA,MAAM,oBAAoB,CAAC,YAAoB,EAAE,OAAa,EAAA;AAC5D,QAAA,MAAM,gBAAgB,GAA4B;AAChD,YAAA,eAAe,EAAE,IAAI;AACrB,YAAA,QAAQ,EAAE,KAAK;AACf,YAAA,sBAAsB,EAAE,IAAI;SAC7B,CAAA;QAED,MAAM,QAAQ,GAAa,MAAM,IAAI,CAAC,cAAc,CAClD,YAAY,EACZ,EAAE;AACF,QAAAC,EAAI,EAAE,EACN,gBAAgB,EAChB,OAAO,CACR,CAAA;QAED,OAAO,IAAI,gBAAgB,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAA;KACrD;AACF,CAAA;AAEY,MAAA,MAAM,GAAG,IAAI,UAAU;;;;"} -\ No newline at end of file -+{"version":3,"file":"hocuspocus-server.esm.js","sources":["../../../node_modules/lib0/set.js","../../../node_modules/lib0/array.js","../../../node_modules/lib0/string.js","../../../node_modules/lib0/map.js","../../../node_modules/lib0/conditions.js","../../../node_modules/lib0/storage.js","../../../node_modules/lib0/object.js","../../../node_modules/lib0/function.js","../../../node_modules/lib0/environment.js","../../../node_modules/lib0/math.js","../../../node_modules/lib0/binary.js","../../../node_modules/lib0/number.js","../../../node_modules/lib0/encoding.js","../../../node_modules/lib0/buffer.js","../../../node_modules/lib0/error.js","../../../node_modules/lib0/decoding.js","../src/IncomingMessage.ts","../../../node_modules/lib0/time.js","../../../node_modules/lib0/observable.js","../../../node_modules/y-protocols/awareness.js","../../../node_modules/y-protocols/sync.js","../src/types.ts","../src/OutgoingMessage.ts","../src/MessageReceiver.ts","../src/Connection.ts","../src/Debugger.ts","../../../node_modules/lib0/mutex.js","../src/Document.ts","../src/util/getParameters.ts","../src/ClientConnection.ts","../src/DirectConnection.ts","../src/Hocuspocus.ts"],"sourcesContent":["/**\n * Utility module to work with sets.\n *\n * @module set\n */\n\nexport const create = () => new Set()\n\n/**\n * @template T\n * @param {Set} set\n * @return {Array}\n */\nexport const toArray = set => Array.from(set)\n\n/**\n * @template T\n * @param {Set} set\n * @return {T}\n */\nexport const first = set =>\n set.values().next().value || undefined\n\n/**\n * @template T\n * @param {Iterable} entries\n * @return {Set}\n */\nexport const from = entries => new Set(entries)\n","/**\n * Utility module to work with Arrays.\n *\n * @module array\n */\n\nimport * as set from './set.js'\n\n/**\n * Return the last element of an array. The element must exist\n *\n * @template L\n * @param {ArrayLike} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array}\n */\nexport const create = () => /** @type {Array} */ ([])\n\n/**\n * @template D\n * @param {Array} a\n * @return {Array}\n */\nexport const copy = a => /** @type {Array} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array} dest\n * @param {Array} src\n */\nexport const appendTo = (dest, src) => {\n for (let i = 0; i < src.length; i++) {\n dest.push(src[i])\n }\n}\n\n/**\n * Transforms something array-like to an actual Array.\n *\n * @function\n * @template T\n * @param {ArrayLike|Iterable} arraylike\n * @return {T}\n */\nexport const from = Array.from\n\n/**\n * True iff condition holds on every element in the Array.\n *\n * @function\n * @template ITEM\n * @template {ArrayLike} ARR\n *\n * @param {ARR} arr\n * @param {function(ITEM, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const every = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (!f(arr[i], i, arr)) {\n return false\n }\n }\n return true\n}\n\n/**\n * True iff condition holds on some element in the Array.\n *\n * @function\n * @template S\n * @template {ArrayLike} ARR\n * @param {ARR} arr\n * @param {function(S, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const some = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (f(arr[i], i, arr)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @template ELEM\n *\n * @param {ArrayLike} a\n * @param {ArrayLike} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a.length === b.length && every(a, (item, index) => item === b[index])\n\n/**\n * @template ELEM\n * @param {Array>} arr\n * @return {Array}\n */\nexport const flatten = arr => fold(arr, /** @type {Array} */ ([]), (acc, val) => acc.concat(val))\n\n/**\n * @template T\n * @param {number} len\n * @param {function(number, Array):T} f\n * @return {Array}\n */\nexport const unfold = (len, f) => {\n const array = new Array(len)\n for (let i = 0; i < len; i++) {\n array[i] = f(i, array)\n }\n return array\n}\n\n/**\n * @template T\n * @template RESULT\n * @param {Array} arr\n * @param {RESULT} seed\n * @param {function(RESULT, T, number):RESULT} folder\n */\nexport const fold = (arr, seed, folder) => arr.reduce(folder, seed)\n\nexport const isArray = Array.isArray\n\n/**\n * @template T\n * @param {Array} arr\n * @return {Array}\n */\nexport const unique = arr => from(set.from(arr))\n\n/**\n * @template T\n * @template M\n * @param {ArrayLike} arr\n * @param {function(T):M} mapper\n * @return {Array}\n */\nexport const uniqueBy = (arr, mapper) => {\n /**\n * @type {Set}\n */\n const happened = set.create()\n /**\n * @type {Array}\n */\n const result = []\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i]\n const mapped = mapper(el)\n if (!happened.has(mapped)) {\n happened.add(mapped)\n result.push(el)\n }\n }\n return result\n}\n","import * as array from './array.js'\n\n/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * The largest utf16 character.\n * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8)\n */\nexport const MAX_UTF16_CHARACTER = fromCharCode(65535)\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* c8 ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* c8 ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* c8 ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* c8 ignore start */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* c8 ignore next */\n utf8TextDecoder = null\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* c8 ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n\n/**\n * @param {string} source\n * @param {number} n\n */\nexport const repeat = (source, n) => array.unfold(n, () => source).join('')\n","/**\n * Utility module to work with key-value stores.\n *\n * @module map\n */\n\n/**\n * Creates a new Map instance.\n *\n * @function\n * @return {Map}\n *\n * @function\n */\nexport const create = () => new Map()\n\n/**\n * Copy a Map object into a fresh Map object.\n *\n * @function\n * @template X,Y\n * @param {Map} m\n * @return {Map}\n */\nexport const copy = m => {\n const r = create()\n m.forEach((v, k) => { r.set(k, v) })\n return r\n}\n\n/**\n * Get map property. Create T if property is undefined and set T on map.\n *\n * ```js\n * const listeners = map.setIfUndefined(events, 'eventName', set.create)\n * listeners.add(listener)\n * ```\n *\n * @function\n * @template V,K\n * @template {Map} MAP\n * @param {MAP} map\n * @param {K} key\n * @param {function():V} createT\n * @return {V}\n */\nexport const setIfUndefined = (map, key, createT) => {\n let set = map.get(key)\n if (set === undefined) {\n map.set(key, set = createT())\n }\n return set\n}\n\n/**\n * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function.\n *\n * @function\n * @template K\n * @template V\n * @template R\n * @param {Map} m\n * @param {function(V,K):R} f\n * @return {Array}\n */\nexport const map = (m, f) => {\n const res = []\n for (const [key, value] of m) {\n res.push(f(value, key))\n }\n return res\n}\n\n/**\n * Tests whether any key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @todo should rename to some - similarly to Array.some\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const any = (m, f) => {\n for (const [key, value] of m) {\n if (f(value, key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * Tests whether all key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const all = (m, f) => {\n for (const [key, value] of m) {\n if (!f(value, key)) {\n return false\n }\n }\n return true\n}\n","/**\n * Often used conditions.\n *\n * @module conditions\n */\n\n/**\n * @template T\n * @param {T|null|undefined} v\n * @return {T|null}\n */\n/* c8 ignore next */\nexport const undefinedToNull = v => v === undefined ? null : v\n","/* eslint-env browser */\n\n/**\n * Isomorphic variable storage.\n *\n * Uses LocalStorage in the browser and falls back to in-memory storage.\n *\n * @module storage\n */\n\n/* c8 ignore start */\nclass VarStoragePolyfill {\n constructor () {\n this.map = new Map()\n }\n\n /**\n * @param {string} key\n * @param {any} newValue\n */\n setItem (key, newValue) {\n this.map.set(key, newValue)\n }\n\n /**\n * @param {string} key\n */\n getItem (key) {\n return this.map.get(key)\n }\n}\n/* c8 ignore stop */\n\n/**\n * @type {any}\n */\nlet _localStorage = new VarStoragePolyfill()\nlet usePolyfill = true\n\n/* c8 ignore start */\ntry {\n // if the same-origin rule is violated, accessing localStorage might thrown an error\n if (typeof localStorage !== 'undefined') {\n _localStorage = localStorage\n usePolyfill = false\n }\n} catch (e) { }\n/* c8 ignore stop */\n\n/**\n * This is basically localStorage in browser, or a polyfill in nodejs\n */\n/* c8 ignore next */\nexport const varStorage = _localStorage\n\n/**\n * A polyfill for `addEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler))\n\n/**\n * A polyfill for `removeEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler))\n","/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object} obj\n */\nexport const keys = Object.keys\n\n/**\n * @template V\n * @param {{[k:string]:V}} obj\n * @param {function(V,string):any} f\n */\nexport const forEach = (obj, f) => {\n for (const key in obj) {\n f(obj[key], key)\n }\n}\n\n/**\n * @todo implement mapToArray & map\n *\n * @template R\n * @param {Object} obj\n * @param {function(any,string):R} f\n * @return {Array}\n */\nexport const map = (obj, f) => {\n const results = []\n for (const key in obj) {\n results.push(f(obj[key], key))\n }\n return results\n}\n\n/**\n * @param {Object} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n for (const key in obj) {\n if (f(obj[key], key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {Object|undefined} obj\n */\nexport const isEmpty = obj => {\n for (const _k in obj) {\n return false\n }\n return true\n}\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n for (const key in obj) {\n if (!f(obj[key], key)) {\n return false\n }\n }\n return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object} a\n * @param {Object} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val))\n","/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array} fs\n * @param {Array} args\n */\nexport const callAll = (fs, args, i = 0) => {\n try {\n for (; i < fs.length; i++) {\n fs[i](...args)\n }\n } finally {\n if (i < fs.length) {\n callAll(fs, args, i + 1)\n }\n }\n}\n\nexport const nop = () => {}\n\n/**\n * @template T\n * @param {function():T} f\n * @return {T}\n */\nexport const apply = f => f()\n\n/**\n * @template A\n *\n * @param {A} a\n * @return {A}\n */\nexport const id = a => a\n\n/**\n * @template T\n *\n * @param {T} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equalityStrict = (a, b) => a === b\n\n/**\n * @template T\n *\n * @param {Array|object} a\n * @param {Array|object} b\n * @return {boolean}\n */\nexport const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((array.isArray(a) && array.equalFlat(a, /** @type {Array} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/* c8 ignore start */\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a == null || b == null) {\n return equalityStrict(a, b)\n }\n if (a.constructor !== b.constructor) {\n return false\n }\n if (a === b) {\n return true\n }\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n break\n }\n case Map: {\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n return false\n }\n }\n break\n }\n case Object:\n if (object.length(a) !== object.length(b)) {\n return false\n }\n for (const key in a) {\n if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n return false\n }\n }\n break\n case Array:\n if (a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!equalityDeep(a[i], b[i])) {\n return false\n }\n }\n break\n default:\n return false\n }\n return true\n}\n\n/**\n * @template V\n * @template {V} OPTS\n *\n * @param {V} value\n * @param {Array} options\n */\n// @ts-ignore\nexport const isOneOf = (value, options) => options.includes(value)\n/* c8 ignore stop */\n\nexport const isArray = array.isArray\n\n/**\n * @param {any} s\n * @return {s is String}\n */\nexport const isString = (s) => s && s.constructor === String\n\n/**\n * @param {any} n\n * @return {n is Number}\n */\nexport const isNumber = n => n != null && n.constructor === Number\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {any} n\n * @param {TYPE} T\n * @return {n is InstanceType}\n */\nexport const is = (n, T) => n && n.constructor === T\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {TYPE} T\n */\nexport const isTemplate = (T) =>\n /**\n * @param {any} n\n * @return {n is InstanceType}\n **/\n n => n && n.constructor === T\n","/**\n * Isomorphic module to work access the environment (query params, env variables).\n *\n * @module map\n */\n\nimport * as map from './map.js'\nimport * as string from './string.js'\nimport * as conditions from './conditions.js'\nimport * as storage from './storage.js'\nimport * as f from './function.js'\n\n/* c8 ignore next */\n// @ts-ignore\nexport const isNode = typeof process !== 'undefined' && process.release &&\n /node|io\\.js/.test(process.release.name)\n/* c8 ignore next */\nexport const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && !isNode\n/* c8 ignore next 3 */\nexport const isMac = typeof navigator !== 'undefined'\n ? /Mac/.test(navigator.platform)\n : false\n\n/**\n * @type {Map}\n */\nlet params\nconst args = []\n\n/* c8 ignore start */\nconst computeParams = () => {\n if (params === undefined) {\n if (isNode) {\n params = map.create()\n const pargs = process.argv\n let currParamName = null\n for (let i = 0; i < pargs.length; i++) {\n const parg = pargs[i]\n if (parg[0] === '-') {\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n currParamName = parg\n } else {\n if (currParamName !== null) {\n params.set(currParamName, parg)\n currParamName = null\n } else {\n args.push(parg)\n }\n }\n }\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n // in ReactNative for example this would not be true (unless connected to the Remote Debugger)\n } else if (typeof location === 'object') {\n params = map.create(); // eslint-disable-next-line no-undef\n (location.search || '?').slice(1).split('&').forEach((kv) => {\n if (kv.length !== 0) {\n const [key, value] = kv.split('=')\n params.set(`--${string.fromCamelCase(key, '-')}`, value)\n params.set(`-${string.fromCamelCase(key, '-')}`, value)\n }\n })\n } else {\n params = map.create()\n }\n }\n return params\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next */\nexport const hasParam = (name) => computeParams().has(name)\n\n/**\n * @param {string} name\n * @param {string} defaultVal\n * @return {string}\n */\n/* c8 ignore next 2 */\nexport const getParam = (name, defaultVal) =>\n computeParams().get(name) || defaultVal\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 4 */\nexport const getVariable = (name) =>\n isNode\n ? conditions.undefinedToNull(process.env[name.toUpperCase()])\n : conditions.undefinedToNull(storage.varStorage.getItem(name))\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 2 */\nexport const getConf = (name) =>\n computeParams().get('--' + name) || getVariable(name)\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next 2 */\nexport const hasConf = (name) =>\n hasParam('--' + name) || getVariable(name) !== null\n\n/* c8 ignore next */\nexport const production = hasConf('production')\n\n/* c8 ignore next 2 */\nconst forceColor = isNode &&\n f.isOneOf(process.env.FORCE_COLOR, ['true', '1', '2'])\n\n/* c8 ignore start */\nexport const supportsColor = !hasParam('no-colors') &&\n (!isNode || process.stdout.isTTY || forceColor) && (\n !isNode || hasParam('color') || forceColor ||\n getVariable('COLORTERM') !== null ||\n (getVariable('TERM') || '').includes('color')\n)\n/* c8 ignore stop */\n","/**\n * Common Math expressions.\n *\n * @module math\n */\n\nexport const floor = Math.floor\nexport const ceil = Math.ceil\nexport const abs = Math.abs\nexport const imul = Math.imul\nexport const round = Math.round\nexport const log10 = Math.log10\nexport const log2 = Math.log2\nexport const log = Math.log\nexport const sqrt = Math.sqrt\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The sum of a and b\n */\nexport const add = (a, b) => a + b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The smaller element of a and b\n */\nexport const min = (a, b) => a < b ? a : b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The bigger element of a and b\n */\nexport const max = (a, b) => a > b ? a : b\n\nexport const isNaN = Number.isNaN\n\nexport const pow = Math.pow\n/**\n * Base 10 exponential function. Returns the value of 10 raised to the power of pow.\n *\n * @param {number} exp\n * @return {number}\n */\nexport const exp10 = exp => Math.pow(10, exp)\n\nexport const sign = Math.sign\n\n/**\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\nexport const HIGHEST_INT32 = binary.BITS31\nexport const HIGHEST_UINT32 = binary.BITS32\n\n/* c8 ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n","/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\nimport * as string from './string.js'\nimport * as array from './array.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * @param {function(Encoder):void} f\n */\nexport const encode = (f) => {\n const encoder = createEncoder()\n f(encoder)\n return toUint8Array(encoder)\n}\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Check whether encoder is empty.\n *\n * @function\n * @param {Encoder} encoder\n * @return {boolean}\n */\nexport const hasContent = encoder => encoder.cpos > 0 || encoder.bufs.length > 0\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nexport const verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer. Max encodable integer is 2^53.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num = math.floor(num / 64) // shift >>> 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n}\n\n/**\n * A cache to store strings temporarily\n */\nconst _strBuffer = new Uint8Array(30000)\nconst _maxStrBSize = _strBuffer.length / 3\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringNative = (encoder, str) => {\n if (str.length < _maxStrBSize) {\n // We can encode the string into the existing buffer\n /* c8 ignore next */\n const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0\n writeVarUint(encoder, written)\n for (let i = 0; i < written; i++) {\n write(encoder, _strBuffer[i])\n }\n } else {\n writeVarUint8Array(encoder, string.encodeUtf8(str))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringPolyfill = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\n/* c8 ignore next */\nexport const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill\n\n/**\n * Write a string terminated by a special byte sequence. This is not very performant and is\n * generally discouraged. However, the resulting byte arrays are lexiographically ordered which\n * makes this a nice feature for databases.\n *\n * The string will be encoded using utf8 and then terminated and escaped using writeTerminatingUint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const writeTerminatedString = (encoder, str) =>\n writeTerminatedUint8Array(encoder, string.encodeUtf8(str))\n\n/**\n * Write a terminating Uint8Array. Note that this is not performant and is generally\n * discouraged. There are few situations when this is needed.\n *\n * We use 0x0 as a terminating character. 0x1 serves as an escape character for 0x0 and 0x1.\n *\n * Example: [0,1,2] is encoded to [1,0,1,1,2,0]. 0x0, and 0x1 needed to be escaped using 0x1. Then\n * the result is terminated using the 0x0 character.\n *\n * This is basically how many systems implement null terminated strings. However, we use an escape\n * character 0x1 to avoid issues and potenial attacks on our database (if this is used as a key\n * encoder for NoSql databases).\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} buf The string that is to be encoded.\n */\nexport const writeTerminatedUint8Array = (encoder, buf) => {\n for (let i = 0; i < buf.length; i++) {\n const b = buf[i]\n if (b === 0 || b === 1) {\n write(encoder, 1)\n }\n write(encoder, buf[i])\n }\n write(encoder, 0)\n}\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && math.abs(data) <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (array.isArray(data)) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n","/**\n * Utility functions to work with buffers (Uint8Array).\n *\n * @module buffer\n */\n\nimport * as string from './string.js'\nimport * as env from './environment.js'\nimport * as encoding from './encoding.js'\nimport * as decoding from './decoding.js'\n\n/**\n * @param {number} len\n */\nexport const createUint8ArrayFromLen = len => new Uint8Array(len)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n * @param {number} byteOffset\n * @param {number} length\n */\nexport const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n */\nexport const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer)\n\n/* c8 ignore start */\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Browser = bytes => {\n let s = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n s += string.fromCharCode(bytes[i])\n }\n // eslint-disable-next-line no-undef\n return btoa(s)\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')\n\n/* c8 ignore start */\n/**\n * @param {string} s\n * @return {Uint8Array}\n */\nconst fromBase64Browser = s => {\n // eslint-disable-next-line no-undef\n const a = atob(s)\n const bytes = createUint8ArrayFromLen(a.length)\n for (let i = 0; i < a.length; i++) {\n bytes[i] = a.charCodeAt(i)\n }\n return bytes\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} s\n */\nconst fromBase64Node = s => {\n const buf = Buffer.from(s, 'base64')\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n}\n\n/* c8 ignore next */\nexport const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node\n\n/* c8 ignore next */\nexport const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node\n\n/**\n * Copy the content of an Uint8Array view to a new ArrayBuffer.\n *\n * @param {Uint8Array} uint8Array\n * @return {Uint8Array}\n */\nexport const copyUint8Array = uint8Array => {\n const newBuf = createUint8ArrayFromLen(uint8Array.byteLength)\n newBuf.set(uint8Array)\n return newBuf\n}\n\n/**\n * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type.\n * See encoding.writeAny for more information.\n *\n * @param {any} data\n * @return {Uint8Array}\n */\nexport const encodeAny = data => {\n const encoder = encoding.createEncoder()\n encoding.writeAny(encoder, data)\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Decode an any-encoded value.\n *\n * @param {Uint8Array} buf\n * @return {any}\n */\nexport const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf))\n","/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* c8 ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n","/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as binary from './binary.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as string from './string.js'\nimport * as error from './error.js'\nimport * as encoding from './encoding.js'\n\nconst errorUnexpectedEndOfArray = error.create('Unexpected end of array')\nconst errorIntegerOutOfRange = error.create('Integer out of Range')\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n */\nexport class Decoder {\n /**\n * @param {Uint8Array} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @param {Uint8Array} uint8Array\n * @return {Decoder}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = buffer.createUint8ArrayViewFromArrayBuffer(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let mult = 1\n const len = decoder.arr.length\n while (decoder.pos < len) {\n const r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num\n mult *= 128 // next iteration, shift 7 \"more\" to the left\n if (r < binary.BIT8) {\n return num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let mult = 64\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n const len = decoder.arr.length\n while (decoder.pos < len) {\n r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult\n mult *= 128\n if (r < binary.BIT8) {\n return sign * num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * We don't test this function anymore as we use native decoding/encoding by default now.\n * Better not modify this anymore..\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\n/* c8 ignore start */\nexport const _readVarStringPolyfill = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n/* c8 ignore stop */\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n */\nexport const _readVarStringNative = decoder =>\n /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder))\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n *\n */\n/* c8 ignore next */\nexport const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill\n\n/**\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTerminatedUint8Array = decoder => {\n const encoder = encoding.createEncoder()\n let b\n while (true) {\n b = readUint8(decoder)\n if (b === 0) {\n return encoding.toUint8Array(encoder)\n }\n if (b === 1) {\n b = readUint8(decoder)\n }\n encoding.write(encoder, b)\n }\n}\n\n/**\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const readTerminatedString = decoder => string.decodeUtf8(readTerminatedUint8Array(decoder))\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object\n const len = readVarUint(decoder)\n /**\n * @type {Object}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = math.floor(diff / 2) // shift >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n","import {\n createDecoder,\n Decoder,\n readVarUint,\n readVarUint8Array,\n readVarString,\n} from 'lib0/decoding'\nimport {\n createEncoder,\n Encoder,\n toUint8Array,\n writeVarUint,\n writeVarString,\n length,\n} from 'lib0/encoding'\nimport { MessageType } from './types.js'\n\nexport class IncomingMessage {\n /**\n * Access to the received message.\n */\n decoder: Decoder\n\n /**\n * Access to the reply.\n */\n encoder: Encoder\n\n constructor(input: any) {\n if (!(input instanceof Uint8Array)) {\n input = new Uint8Array(input)\n }\n\n this.encoder = createEncoder()\n this.decoder = createDecoder(input)\n }\n\n readVarUint8Array() {\n return readVarUint8Array(this.decoder)\n }\n\n readVarUint() {\n return readVarUint(this.decoder)\n }\n\n readVarString() {\n return readVarString(this.decoder)\n }\n\n toUint8Array() {\n return toUint8Array(this.encoder)\n }\n\n writeVarUint(type: MessageType) {\n writeVarUint(this.encoder, type)\n }\n\n writeVarString(string: string) {\n writeVarString(this.encoder, string)\n }\n\n get length(): number {\n return length(this.encoder)\n }\n}\n","/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* c8 ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n","/**\n * Observable class prototype.\n *\n * @module observable\n */\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as array from './array.js'\n\n/**\n * Handles named events.\n *\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map}\n */\n this._observers = map.create()\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, name, set.create).add(f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, _f)\n f(...args)\n }\n this.on(name, _f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @param {N} name The event name.\n * @param {Array} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // 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.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n","/**\n * @module awareness-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as time from 'lib0/time'\nimport * as math from 'lib0/math'\nimport { Observable } from 'lib0/observable'\nimport * as f from 'lib0/function'\nimport * as Y from 'yjs' // eslint-disable-line\n\nexport const outdatedTimeout = 30000\n\n/**\n * @typedef {Object} MetaClientState\n * @property {number} MetaClientState.clock\n * @property {number} MetaClientState.lastUpdated unix timestamp\n */\n\n/**\n * The Awareness class implements a simple shared state protocol that can be used for non-persistent data like awareness information\n * (cursor, username, status, ..). Each client can update its own local state and listen to state changes of\n * remote clients. Every client may set a state of a remote peer to `null` to mark the client as offline.\n *\n * Each client is identified by a unique client id (something we borrow from `doc.clientID`). A client can override\n * its own state by propagating a message with an increasing timestamp (`clock`). If such a message is received, it is\n * applied if the known state of that client is older than the new state (`clock < newClock`). If a client thinks that\n * a remote client is offline, it may propagate a message with\n * `{ clock: currentClientClock, state: null, client: remoteClient }`. If such a\n * message is received, and the known clock of that client equals the received clock, it will override the state with `null`.\n *\n * Before a client disconnects, it should propagate a `null` state with an updated clock.\n *\n * Awareness states must be updated every 30 seconds. Otherwise the Awareness instance will delete the client state.\n *\n * @extends {Observable}\n */\nexport class Awareness extends Observable {\n /**\n * @param {Y.Doc} doc\n */\n constructor (doc) {\n super()\n this.doc = doc\n /**\n * @type {number}\n */\n this.clientID = doc.clientID\n /**\n * Maps from client id to client state\n * @type {Map>}\n */\n this.states = new Map()\n /**\n * @type {Map}\n */\n this.meta = new Map()\n this._checkInterval = /** @type {any} */ (setInterval(() => {\n const now = time.getUnixTime()\n if (this.getLocalState() !== null && (outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ (this.meta.get(this.clientID)).lastUpdated)) {\n // renew local clock\n this.setLocalState(this.getLocalState())\n }\n /**\n * @type {Array}\n */\n const remove = []\n this.meta.forEach((meta, clientid) => {\n if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) {\n remove.push(clientid)\n }\n })\n if (remove.length > 0) {\n removeAwarenessStates(this, remove, 'timeout')\n }\n }, math.floor(outdatedTimeout / 10)))\n doc.on('destroy', () => {\n this.destroy()\n })\n this.setLocalState({})\n }\n\n destroy () {\n this.emit('destroy', [this])\n this.setLocalState(null)\n super.destroy()\n clearInterval(this._checkInterval)\n }\n\n /**\n * @return {Object|null}\n */\n getLocalState () {\n return this.states.get(this.clientID) || null\n }\n\n /**\n * @param {Object|null} state\n */\n setLocalState (state) {\n const clientID = this.clientID\n const currLocalMeta = this.meta.get(clientID)\n const clock = currLocalMeta === undefined ? 0 : currLocalMeta.clock + 1\n const prevState = this.states.get(clientID)\n if (state === null) {\n this.states.delete(clientID)\n } else {\n this.states.set(clientID, state)\n }\n this.meta.set(clientID, {\n clock,\n lastUpdated: time.getUnixTime()\n })\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n if (state === null) {\n removed.push(clientID)\n } else if (prevState == null) {\n if (state != null) {\n added.push(clientID)\n }\n } else {\n updated.push(clientID)\n if (!f.equalityDeep(prevState, state)) {\n filteredUpdated.push(clientID)\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n this.emit('change', [{ added, updated: filteredUpdated, removed }, 'local'])\n }\n this.emit('update', [{ added, updated, removed }, 'local'])\n }\n\n /**\n * @param {string} field\n * @param {any} value\n */\n setLocalStateField (field, value) {\n const state = this.getLocalState()\n if (state !== null) {\n this.setLocalState({\n ...state,\n [field]: value\n })\n }\n }\n\n /**\n * @return {Map>}\n */\n getStates () {\n return this.states\n }\n}\n\n/**\n * Mark (remote) clients as inactive and remove them from the list of active peers.\n * This change will be propagated to remote clients.\n *\n * @param {Awareness} awareness\n * @param {Array} clients\n * @param {any} origin\n */\nexport const removeAwarenessStates = (awareness, clients, origin) => {\n const removed = []\n for (let i = 0; i < clients.length; i++) {\n const clientID = clients[i]\n if (awareness.states.has(clientID)) {\n awareness.states.delete(clientID)\n if (clientID === awareness.clientID) {\n const curMeta = /** @type {MetaClientState} */ (awareness.meta.get(clientID))\n awareness.meta.set(clientID, {\n clock: curMeta.clock + 1,\n lastUpdated: time.getUnixTime()\n })\n }\n removed.push(clientID)\n }\n }\n if (removed.length > 0) {\n awareness.emit('change', [{ added: [], updated: [], removed }, origin])\n awareness.emit('update', [{ added: [], updated: [], removed }, origin])\n }\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Array} clients\n * @return {Uint8Array}\n */\nexport const encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {\n const len = clients.length\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = clients[i]\n const state = states.get(clientID) || null\n const clock = /** @type {MetaClientState} */ (awareness.meta.get(clientID)).clock\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(state))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Modify the content of an awareness update before re-encoding it to an awareness update.\n *\n * This might be useful when you have a central server that wants to ensure that clients\n * cant hijack somebody elses identity.\n *\n * @param {Uint8Array} update\n * @param {function(any):any} modify\n * @return {Uint8Array}\n */\nexport const modifyAwarenessUpdate = (update, modify) => {\n const decoder = decoding.createDecoder(update)\n const encoder = encoding.createEncoder()\n const len = decoding.readVarUint(decoder)\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n const clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const modifiedState = modify(state)\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(modifiedState))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Uint8Array} update\n * @param {any} origin This will be added to the emitted change event\n */\nexport const applyAwarenessUpdate = (awareness, update, origin) => {\n const decoder = decoding.createDecoder(update)\n const timestamp = time.getUnixTime()\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n const len = decoding.readVarUint(decoder)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n let clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const clientMeta = awareness.meta.get(clientID)\n const prevState = awareness.states.get(clientID)\n const currClock = clientMeta === undefined ? 0 : clientMeta.clock\n if (currClock < clock || (currClock === clock && state === null && awareness.states.has(clientID))) {\n if (state === null) {\n // never let a remote client remove this local state\n if (clientID === awareness.clientID && awareness.getLocalState() != null) {\n // remote client removed the local state. Do not remote state. Broadcast a message indicating\n // that this client still exists by increasing the clock\n clock++\n } else {\n awareness.states.delete(clientID)\n }\n } else {\n awareness.states.set(clientID, state)\n }\n awareness.meta.set(clientID, {\n clock,\n lastUpdated: timestamp\n })\n if (clientMeta === undefined && state !== null) {\n added.push(clientID)\n } else if (clientMeta !== undefined && state === null) {\n removed.push(clientID)\n } else if (state !== null) {\n if (!f.equalityDeep(state, prevState)) {\n filteredUpdated.push(clientID)\n }\n updated.push(clientID)\n }\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n awareness.emit('change', [{\n added, updated: filteredUpdated, removed\n }, origin])\n }\n if (added.length > 0 || updated.length > 0 || removed.length > 0) {\n awareness.emit('update', [{\n added, updated, removed\n }, origin])\n }\n}\n","/**\n * @module sync-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as Y from 'yjs'\n\n/**\n * @typedef {Map} StateMap\n */\n\n/**\n * Core Yjs defines two message types:\n * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.\n * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it\n * received all information from the remote client.\n *\n * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection\n * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both\n * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.\n *\n * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.\n * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies\n * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the\n * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can\n * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them.\n * Therefore it is necesarry that the client initiates the sync.\n *\n * Construction of a message:\n * [messageType : varUint, message definition..]\n *\n * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!\n *\n * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)\n */\n\nexport const messageYjsSyncStep1 = 0\nexport const messageYjsSyncStep2 = 1\nexport const messageYjsUpdate = 2\n\n/**\n * Create a sync step 1 message based on the state of the current shared document.\n *\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n */\nexport const writeSyncStep1 = (encoder, doc) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep1)\n const sv = Y.encodeStateVector(doc)\n encoding.writeVarUint8Array(encoder, sv)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n * @param {Uint8Array} [encodedStateVector]\n */\nexport const writeSyncStep2 = (encoder, doc, encodedStateVector) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep2)\n encoding.writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector))\n}\n\n/**\n * Read SyncStep1 message and reply with SyncStep2.\n *\n * @param {decoding.Decoder} decoder The reply to the received message\n * @param {encoding.Encoder} encoder The received message\n * @param {Y.Doc} doc\n */\nexport const readSyncStep1 = (decoder, encoder, doc) =>\n writeSyncStep2(encoder, doc, decoding.readVarUint8Array(decoder))\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin) => {\n try {\n Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n } catch (error) {\n // This catches errors that are thrown by event handlers\n console.error('Caught error while handling a Yjs update', error)\n }\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Uint8Array} update\n */\nexport const writeUpdate = (encoder, update) => {\n encoding.writeVarUint(encoder, messageYjsUpdate)\n encoding.writeVarUint8Array(encoder, update)\n}\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readUpdate = readSyncStep2\n\n/**\n * @param {decoding.Decoder} decoder A message received from another client\n * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => {\n const messageType = decoding.readVarUint(decoder)\n switch (messageType) {\n case messageYjsSyncStep1:\n readSyncStep1(decoder, encoder, doc)\n break\n case messageYjsSyncStep2:\n readSyncStep2(decoder, doc, transactionOrigin)\n break\n case messageYjsUpdate:\n readUpdate(decoder, doc, transactionOrigin)\n break\n default:\n throw new Error('Unknown message type')\n }\n return messageType\n}\n","import {\n IncomingHttpHeaders, IncomingMessage, ServerResponse,\n} from 'http'\nimport { URLSearchParams } from 'url'\nimport { Awareness } from 'y-protocols/awareness'\nimport Connection from './Connection.js'\nimport Document from './Document.js'\nimport { Hocuspocus } from './Hocuspocus.js'\n\nexport enum MessageType {\n Unknown = -1,\n Sync = 0,\n Awareness = 1,\n Auth = 2,\n QueryAwareness = 3,\n SyncReply = 4, // same as Sync, but won't trigger another 'SyncStep1'\n Stateless = 5,\n BroadcastStateless = 6,\n CLOSE = 7,\n SyncStatus = 8, // TODO: should this be 8?\n}\n\nexport interface AwarenessUpdate {\n added: Array,\n updated: Array,\n removed: Array,\n}\n\nexport interface ConnectionConfiguration {\n readOnly: boolean\n requiresAuthentication: boolean\n isAuthenticated: boolean\n}\n\nexport interface Extension {\n priority?: number,\n onConfigure?(data: onConfigurePayload): Promise,\n onListen?(data: onListenPayload): Promise,\n onUpgrade?(data: onUpgradePayload): Promise,\n onConnect?(data: onConnectPayload): Promise,\n connected?(data: connectedPayload): Promise,\n onAuthenticate?(data: onAuthenticatePayload): Promise,\n onLoadDocument?(data: onLoadDocumentPayload): Promise,\n afterLoadDocument?(data: onLoadDocumentPayload): Promise,\n beforeHandleMessage?(data: beforeHandleMessagePayload): Promise,\n beforeBroadcastStateless?(data: beforeBroadcastStatelessPayload): Promise,\n onStateless?(payload: onStatelessPayload): Promise;\n onChange?(data: onChangePayload): Promise,\n onStoreDocument?(data: onStoreDocumentPayload): Promise,\n afterStoreDocument?(data: afterStoreDocumentPayload): Promise,\n onAwarenessUpdate?(data: onAwarenessUpdatePayload): Promise,\n onRequest?(data: onRequestPayload): Promise,\n onDisconnect?(data: onDisconnectPayload): Promise\n onDestroy?(data: onDestroyPayload): Promise,\n}\n\nexport type HookName =\n 'onConfigure' |\n 'onListen' |\n 'onUpgrade' |\n 'onConnect' |\n 'connected' |\n 'onAuthenticate' |\n 'onLoadDocument' |\n 'afterLoadDocument' |\n 'beforeHandleMessage' |\n 'beforeBroadcastStateless' |\n 'onStateless' |\n 'onChange' |\n 'onStoreDocument' |\n 'afterStoreDocument' |\n 'onAwarenessUpdate' |\n 'onRequest' |\n 'onDisconnect' |\n 'onDestroy'\n\nexport type HookPayload =\n onConfigurePayload |\n onListenPayload |\n onUpgradePayload |\n onConnectPayload |\n connectedPayload |\n onAuthenticatePayload |\n onLoadDocumentPayload |\n onStatelessPayload |\n beforeHandleMessagePayload |\n beforeBroadcastStatelessPayload |\n onChangePayload |\n onStoreDocumentPayload |\n afterStoreDocumentPayload |\n onAwarenessUpdatePayload |\n onRequestPayload |\n onDisconnectPayload |\n onDestroyPayload\n\nexport interface Configuration extends Extension {\n /**\n * A name for the instance, used for logging.\n */\n name: string | null,\n /**\n * A list of hocuspocus extenions.\n */\n extensions: Array,\n /**\n * The port which the server listens on.\n */\n port?: number,\n /**\n * The address which the server listens on.\n */\n address?: string,\n /**\n * Defines in which interval the server sends a ping, and closes the connection when no pong is sent back.\n */\n timeout: number,\n /**\n * Debounces the call of the `onStoreDocument` hook for the given amount of time in ms.\n * Otherwise every single update would be persisted.\n */\n debounce: number,\n /**\n * Makes sure to call `onStoreDocument` at least in the given amount of time (ms).\n */\n maxDebounce: number\n /**\n * By default, the servers show a start screen. If passed false, the server will start quietly.\n */\n quiet: boolean,\n\n /**\n * options to pass to the ydoc document\n */\n yDocOptions: {\n gc: boolean, // enable or disable garbage collection (see https://github.com/yjs/yjs/blob/main/INTERNALS.md#deletions)\n gcFilter: () => boolean, // will be called before garbage collecting ; return false to keep it\n },\n /**\n * Function which returns the (customized) document name based on the request\n */\n getDocumentName?(data: getDocumentNamePayload): string | Promise,\n}\n\nexport interface getDocumentNamePayload {\n documentName: string,\n request: IncomingMessage,\n requestParameters: URLSearchParams,\n}\n\nexport interface onStatelessPayload {\n connection: Connection,\n documentName: string,\n document: Document,\n payload: string,\n}\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface onAuthenticatePayload {\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n token: string,\n connection: ConnectionConfiguration\n}\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface onConnectPayload {\n documentName: string,\n instance: Hocuspocus,\n request: IncomingMessage,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration\n}\n\n// @todo Change 'connection' to 'connectionConfig', and 'connectionInstance' to 'connection' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface connectedPayload {\n context: any,\n documentName: string,\n instance: Hocuspocus,\n request: IncomingMessage,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration,\n connectionInstance: Connection\n}\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface onLoadDocumentPayload {\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration\n}\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface afterLoadDocumentPayload {\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration\n}\n\nexport interface onChangePayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n update: Uint8Array,\n socketId: string,\n}\n\nexport interface beforeHandleMessagePayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n update: Uint8Array,\n socketId: string,\n connection: Connection\n}\n\nexport interface beforeBroadcastStatelessPayload {\n document: Document,\n documentName: string,\n payload: string,\n}\n\nexport interface onStoreDocumentPayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n}\n\nexport interface afterStoreDocumentPayload extends onStoreDocumentPayload {}\n\nexport interface onAwarenessUpdatePayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n update: Uint8Array,\n socketId: string,\n added: number[],\n updated: number[],\n removed: number[],\n awareness: Awareness,\n states: StatesArray,\n}\n\nexport type StatesArray = { clientId: number, [key: string | number]: any }[]\n\n// @todo Change 'connection' to 'connectionConfig' in next major release\n// see https://github.com/ueberdosis/hocuspocus/pull/607#issuecomment-1553559805\nexport interface fetchPayload {\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n connection: ConnectionConfiguration\n}\n\nexport interface storePayload extends onStoreDocumentPayload {\n state: Buffer,\n}\n\nexport interface onDisconnectPayload {\n clientsCount: number,\n context: any,\n document: Document,\n documentName: string,\n instance: Hocuspocus,\n requestHeaders: IncomingHttpHeaders,\n requestParameters: URLSearchParams,\n socketId: string,\n}\n\nexport interface onRequestPayload {\n request: IncomingMessage,\n response: ServerResponse,\n instance: Hocuspocus,\n}\n\nexport interface onUpgradePayload {\n request: IncomingMessage,\n socket: any,\n head: any,\n instance: Hocuspocus,\n}\n\nexport interface onListenPayload {\n instance: Hocuspocus,\n configuration: Configuration,\n port: number,\n}\n\nexport interface onDestroyPayload {\n instance: Hocuspocus,\n}\n\nexport interface onConfigurePayload {\n instance: Hocuspocus,\n configuration: Configuration,\n version: string,\n}\n","import {\n createEncoder,\n Encoder,\n toUint8Array,\n writeVarString,\n writeVarUint,\n writeVarUint8Array,\n} from 'lib0/encoding'\nimport { Awareness, encodeAwarenessUpdate } from 'y-protocols/awareness'\nimport { writeSyncStep1, writeUpdate } from 'y-protocols/sync'\n\nimport { writeAuthenticated, writePermissionDenied } from '@hocuspocus/common'\nimport Document from './Document.js'\nimport { MessageType } from './types.js'\n\nexport class OutgoingMessage {\n\n encoder: Encoder\n\n type?: number\n\n category?: string\n\n constructor(documentName: string) {\n this.encoder = createEncoder()\n\n writeVarString(this.encoder, documentName)\n }\n\n createSyncMessage(): OutgoingMessage {\n this.type = MessageType.Sync\n\n writeVarUint(this.encoder, MessageType.Sync)\n\n return this\n }\n\n createSyncReplyMessage(): OutgoingMessage {\n this.type = MessageType.SyncReply\n\n writeVarUint(this.encoder, MessageType.SyncReply)\n\n return this\n }\n\n createAwarenessUpdateMessage(awareness: Awareness, changedClients?: Array): OutgoingMessage {\n this.type = MessageType.Awareness\n this.category = 'Update'\n\n const message = encodeAwarenessUpdate(\n awareness,\n changedClients || Array.from(awareness.getStates().keys()),\n )\n\n writeVarUint(this.encoder, MessageType.Awareness)\n writeVarUint8Array(this.encoder, message)\n\n return this\n }\n\n writeQueryAwareness(): OutgoingMessage {\n this.type = MessageType.QueryAwareness\n this.category = 'Update'\n\n writeVarUint(this.encoder, MessageType.QueryAwareness)\n\n return this\n }\n\n writeAuthenticated(readonly: boolean): OutgoingMessage {\n this.type = MessageType.Auth\n this.category = 'Authenticated'\n\n writeVarUint(this.encoder, MessageType.Auth)\n writeAuthenticated(this.encoder, readonly ? 'readonly' : 'read-write')\n\n return this\n }\n\n writePermissionDenied(reason: string): OutgoingMessage {\n this.type = MessageType.Auth\n this.category = 'PermissionDenied'\n\n writeVarUint(this.encoder, MessageType.Auth)\n writePermissionDenied(this.encoder, reason)\n\n return this\n }\n\n writeFirstSyncStepFor(document: Document): OutgoingMessage {\n this.category = 'SyncStep1'\n\n writeSyncStep1(this.encoder, document)\n\n return this\n }\n\n writeUpdate(update: Uint8Array): OutgoingMessage {\n this.category = 'Update'\n\n writeUpdate(this.encoder, update)\n\n return this\n }\n\n writeStateless(payload: string): OutgoingMessage {\n this.category = 'Stateless'\n\n writeVarUint(this.encoder, MessageType.Stateless)\n writeVarString(this.encoder, payload)\n\n return this\n }\n\n writeBroadcastStateless(payload: string): OutgoingMessage {\n this.category = 'Stateless'\n\n writeVarUint(this.encoder, MessageType.BroadcastStateless)\n writeVarString(this.encoder, payload)\n\n return this\n }\n\n // TODO: should this be write* or create* as method name?\n writeSyncStatus(updateSaved: boolean): OutgoingMessage {\n this.category = 'SyncStatus'\n\n writeVarUint(this.encoder, MessageType.SyncStatus)\n writeVarUint(this.encoder, updateSaved ? 1 : 0)\n\n return this\n }\n\n toUint8Array(): Uint8Array {\n return toUint8Array(this.encoder)\n }\n\n}\n","import * as decoding from 'lib0/decoding'\nimport { readVarString } from 'lib0/decoding'\nimport { applyAwarenessUpdate } from 'y-protocols/awareness'\nimport {\n messageYjsSyncStep1,\n messageYjsSyncStep2,\n messageYjsUpdate,\n readSyncStep1,\n readSyncStep2,\n readUpdate,\n} from 'y-protocols/sync'\nimport * as Y from 'yjs'\nimport Connection from './Connection.js'\nimport { Debugger } from './Debugger.js'\nimport Document from './Document.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { MessageType } from './types.js'\n\nexport class MessageReceiver {\n\n message: IncomingMessage\n\n logger: Debugger\n\n constructor(message: IncomingMessage, logger: Debugger) {\n this.message = message\n this.logger = logger\n }\n\n public apply(document: Document, connection?: Connection, reply?: (message: Uint8Array) => void) {\n const { message } = this\n const type = message.readVarUint()\n const emptyMessageLength = message.length\n\n switch (type) {\n case MessageType.Sync:\n case MessageType.SyncReply: {\n message.writeVarUint(MessageType.Sync)\n this.readSyncMessage(message, document, connection, reply, type !== MessageType.SyncReply)\n\n if (message.length > emptyMessageLength + 1) {\n if (reply) {\n reply(message.toUint8Array())\n } else if (connection) {\n // TODO: We should log this, shouldn’t we?\n // this.logger.log({\n // direction: 'out',\n // type: MessageType.Awareness,\n // category: 'Update',\n // })\n connection.send(message.toUint8Array())\n }\n }\n\n break\n }\n case MessageType.Awareness: {\n this.logger.log({\n direction: 'in',\n type: MessageType.Awareness,\n category: 'Update',\n })\n\n applyAwarenessUpdate(document.awareness, message.readVarUint8Array(), connection)\n\n break\n }\n case MessageType.QueryAwareness: {\n\n this.applyQueryAwarenessMessage(document, reply)\n\n break\n }\n case MessageType.Stateless: {\n connection?.callbacks.statelessCallback({\n connection,\n documentName: document.name,\n document,\n payload: readVarString(message.decoder),\n })\n\n break\n }\n case MessageType.BroadcastStateless: {\n const msg = message.readVarString()\n document.getConnections().forEach(connection => {\n connection.sendStateless(msg)\n })\n break\n }\n\n case MessageType.CLOSE: {\n connection?.close({\n code: 1000,\n reason: 'provider_initiated',\n })\n break\n }\n default:\n console.error(`Unable to handle message of type ${type}: no handler defined!`)\n // Do nothing\n }\n }\n\n readSyncMessage(message: IncomingMessage, document: Document, connection?: Connection, reply?: (message: Uint8Array) => void, requestFirstSync = true) {\n const type = message.readVarUint()\n\n switch (type) {\n case messageYjsSyncStep1: {\n this.logger.log({\n direction: 'in',\n type: MessageType.Sync,\n category: 'SyncStep1',\n })\n\n readSyncStep1(message.decoder, message.encoder, document)\n\n // When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1.\n this.logger.log({\n direction: 'out',\n type: MessageType.Sync,\n category: 'SyncStep2',\n })\n\n if (reply && requestFirstSync) {\n const syncMessage = (new OutgoingMessage(document.name)\n .createSyncReplyMessage()\n .writeFirstSyncStepFor(document))\n\n this.logger.log({\n direction: 'out',\n type: MessageType.Sync,\n category: 'SyncStep1',\n })\n\n reply(syncMessage.toUint8Array())\n } else if (connection) {\n const syncMessage = (new OutgoingMessage(document.name)\n .createSyncMessage()\n .writeFirstSyncStepFor(document))\n\n this.logger.log({\n direction: 'out',\n type: MessageType.Sync,\n category: 'SyncStep1',\n })\n\n connection.send(syncMessage.toUint8Array())\n }\n break\n }\n case messageYjsSyncStep2:\n this.logger.log({\n direction: 'in',\n type: MessageType.Sync,\n category: 'SyncStep2',\n })\n\n if (connection?.readOnly) {\n // We're in read-only mode, so we can't apply the update.\n // Let's use snapshotContainsUpdate to see if the update actually contains changes.\n // If not, we can still ack the update\n const snapshot = Y.snapshot(document)\n const update = decoding.readVarUint8Array(message.decoder)\n if (Y.snapshotContainsUpdate(snapshot, update)) {\n // no new changes in update\n const ackMessage = new OutgoingMessage(document.name)\n .writeSyncStatus(true)\n\n connection.send(ackMessage.toUint8Array())\n } else {\n // new changes in update that we can't apply, because readOnly\n const ackMessage = new OutgoingMessage(document.name)\n .writeSyncStatus(false)\n\n connection.send(ackMessage.toUint8Array())\n }\n break\n }\n\n readSyncStep2(message.decoder, document, connection)\n\n if (connection) {\n // TODO: how should this work if connection is not set? should we use reply?\n // reply is used by redis, but I'm unsure how that code path works\n connection.send(new OutgoingMessage(document.name)\n .writeSyncStatus(true).toUint8Array())\n }\n break\n case messageYjsUpdate:\n this.logger.log({\n direction: 'in',\n type: MessageType.Sync,\n category: 'Update',\n })\n\n if (connection?.readOnly) {\n connection.send(new OutgoingMessage(document.name)\n .writeSyncStatus(false).toUint8Array())\n break\n }\n\n readUpdate(message.decoder, document, connection)\n if (connection) {\n // TODO: how should this work if connection is not set? should we use reply?\n // reply is used by redis, but I'm unsure how that code path works\n connection.send(new OutgoingMessage(document.name)\n .writeSyncStatus(true).toUint8Array())\n }\n break\n default:\n throw new Error(`Received a message with an unknown type: ${type}`)\n }\n\n return type\n }\n\n applyQueryAwarenessMessage(document: Document, reply?: (message: Uint8Array) => void) {\n const message = new OutgoingMessage(document.name)\n .createAwarenessUpdateMessage(document.awareness)\n\n if (reply) {\n reply(message.toUint8Array())\n }\n\n // TODO: We should add support for WebSocket connections, too, right?\n // this.logger.log({\n // direction: 'out',\n // type: MessageType.Sync,\n // category: 'SyncStep1',\n // })\n\n // connection.send(syncMessage.toUint8Array())\n }\n}\n","import { IncomingMessage as HTTPIncomingMessage } from 'http'\nimport AsyncLock from 'async-lock'\nimport WebSocket from 'ws'\nimport {\n CloseEvent, ConnectionTimeout, Forbidden, WsReadyStates,\n} from '@hocuspocus/common'\nimport Document from './Document.js'\nimport { IncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { MessageReceiver } from './MessageReceiver.js'\nimport { Debugger } from './Debugger.js'\nimport { onStatelessPayload } from './types.js'\n\nexport class Connection {\n\n webSocket: WebSocket\n\n context: any\n\n document: Document\n\n pingInterval: NodeJS.Timeout\n\n pongReceived = true\n\n request: HTTPIncomingMessage\n\n timeout: number\n\n callbacks: any = {\n onClose: [(document: Document, event?: CloseEvent) => null],\n beforeHandleMessage: (connection: Connection, update: Uint8Array) => Promise,\n statelessCallback: () => Promise,\n }\n\n socketId: string\n\n lock: AsyncLock\n\n readOnly: Boolean\n\n logger: Debugger\n\n /**\n * Constructor.\n */\n constructor(\n connection: WebSocket,\n request: HTTPIncomingMessage,\n document: Document,\n timeout: number,\n socketId: string,\n context: any,\n readOnly = false,\n logger: Debugger,\n ) {\n this.webSocket = connection\n this.context = context\n this.document = document\n this.request = request\n this.timeout = timeout\n this.socketId = socketId\n this.readOnly = readOnly\n this.logger = logger\n\n this.lock = new AsyncLock()\n\n this.webSocket.binaryType = 'arraybuffer'\n this.document.addConnection(this)\n\n this.pingInterval = setInterval(this.check.bind(this), this.timeout)\n\n this.webSocket.on('close', this.boundClose)\n this.webSocket.on('message', this.boundHandleMessage)\n this.webSocket.on('pong', this.boundHandlePong)\n\n this.sendCurrentAwareness()\n }\n\n boundClose = this.close.bind(this)\n\n boundHandleMessage = this.handleMessage.bind(this)\n\n boundHandlePong = this.handlePong.bind(this)\n\n handlePong() {\n this.pongReceived = true\n }\n\n /**\n * Set a callback that will be triggered when the connection is closed\n */\n onClose(callback: (document: Document, event?: CloseEvent) => void): Connection {\n this.callbacks.onClose.push(callback)\n\n return this\n }\n\n /**\n * Set a callback that will be triggered when an stateless message is received\n */\n onStatelessCallback(callback: (payload: onStatelessPayload) => Promise): Connection {\n this.callbacks.statelessCallback = callback\n\n return this\n }\n\n /**\n * Set a callback that will be triggered before an message is handled\n */\n beforeHandleMessage(callback: (connection: Connection, update: Uint8Array) => Promise): Connection {\n this.callbacks.beforeHandleMessage = callback\n\n return this\n }\n\n /**\n * Send the given message\n */\n send(message: any): void {\n if (\n this.webSocket.readyState === WsReadyStates.Closing\n || this.webSocket.readyState === WsReadyStates.Closed\n ) {\n this.close()\n }\n\n try {\n this.webSocket.send(message, (error: any) => {\n if (error != null) this.close()\n })\n } catch (exception) {\n this.close()\n }\n }\n\n /**\n * Send a stateless message with payload\n */\n public sendStateless(payload: string): void {\n const message = new OutgoingMessage(this.document.name)\n .writeStateless(payload)\n\n this.logger.log({\n direction: 'out',\n type: message.type,\n category: message.category,\n })\n\n this.send(\n message.toUint8Array(),\n )\n }\n\n /**\n * Graceful wrapper around the WebSocket close method.\n */\n close(event?: CloseEvent): void {\n this.lock.acquire('close', (done: Function) => {\n if (this.pingInterval) {\n clearInterval(this.pingInterval)\n }\n\n if (this.document.hasConnection(this)) {\n this.document.removeConnection(this)\n clearInterval(this.pingInterval)\n\n this.webSocket.removeListener('close', this.boundClose)\n this.webSocket.removeListener('message', this.boundHandleMessage)\n this.webSocket.removeListener('pong', this.boundHandlePong)\n\n this.callbacks.onClose.forEach((callback: (arg0: Document, arg1?: CloseEvent) => any) => callback(this.document, event))\n }\n\n done()\n })\n }\n\n /**\n * Check if pong was received and close the connection otherwise\n * @private\n */\n private check(): void {\n if (!this.pongReceived) {\n return this.close(ConnectionTimeout)\n }\n\n if (this.document.hasConnection(this)) {\n this.pongReceived = false\n\n try {\n this.webSocket.ping()\n } catch (error) {\n this.close(ConnectionTimeout)\n }\n }\n }\n\n /**\n * Send the current document awareness to the client, if any\n * @private\n */\n private sendCurrentAwareness(): void {\n if (!this.document.hasAwarenessStates()) {\n return\n }\n\n const awarenessMessage = new OutgoingMessage(this.document.name)\n .createAwarenessUpdateMessage(this.document.awareness)\n\n this.logger.log({\n direction: 'out',\n type: awarenessMessage.type,\n category: awarenessMessage.category,\n })\n\n this.send(awarenessMessage.toUint8Array())\n }\n\n /**\n * Handle an incoming message\n * @private\n */\n private handleMessage(data: Uint8Array): void {\n const message = new IncomingMessage(data)\n const documentName = message.readVarString()\n\n if (documentName !== this.document.name) return\n\n message.writeVarString(documentName)\n\n this.callbacks.beforeHandleMessage(this, data)\n .then(() => {\n new MessageReceiver(\n message,\n this.logger,\n ).apply(this.document, this)\n })\n .catch((e: any) => {\n console.log('closing connection because of exception', e)\n this.close({\n code: 'code' in e ? e.code : Forbidden.code,\n reason: 'reason' in e ? e.reason : Forbidden.reason,\n })\n })\n }\n\n}\n\nexport default Connection\n","// import * as time from 'lib0/time'\nimport { MessageType } from './types.js'\n\nexport class Debugger {\n logs: any[] = []\n\n listen = false\n\n output = false\n\n enable() {\n this.flush()\n\n this.listen = true\n }\n\n disable() {\n this.listen = false\n }\n\n verbose() {\n this.output = true\n }\n\n quiet() {\n this.output = false\n }\n\n log(message: any) {\n if (!this.listen) {\n return this\n }\n\n const item = {\n ...message,\n type: MessageType[message.type],\n // time: time.getUnixTime(),\n }\n\n this.logs.push(item)\n\n if (this.output) {\n console.log('[DEBUGGER]', item.direction === 'in' ? 'IN –>' : 'OUT <–', `${item.type}/${item.category}`)\n }\n\n return this\n }\n\n flush() {\n this.logs = []\n\n return this\n }\n\n get() {\n return {\n logs: this.logs,\n }\n }\n}\n","/**\n * Mutual exclude for JavaScript.\n *\n * @module mutex\n */\n\n/**\n * @callback mutex\n * @param {function():void} cb Only executed when this mutex is not in the current stack\n * @param {function():void} [elseCb] Executed when this mutex is in the current stack\n */\n\n/**\n * Creates a mutual exclude function with the following property:\n *\n * ```js\n * const mutex = createMutex()\n * mutex(() => {\n * // This function is immediately executed\n * mutex(() => {\n * // This function is not executed, as the mutex is already active.\n * })\n * })\n * ```\n *\n * @return {mutex} A mutual exclude function\n * @public\n */\nexport const createMutex = () => {\n let token = true\n return (f, g) => {\n if (token) {\n token = false\n try {\n f()\n } finally {\n token = true\n }\n } else if (g !== undefined) {\n g()\n }\n }\n}\n","import WebSocket from 'ws'\nimport { Awareness, removeAwarenessStates, applyAwarenessUpdate } from 'y-protocols/awareness'\nimport { applyUpdate, Doc, encodeStateAsUpdate } from 'yjs'\nimport { mutex, createMutex } from 'lib0/mutex.js'\nimport { AwarenessUpdate } from './types.js'\nimport Connection from './Connection.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport { Debugger } from './Debugger.js'\n\nexport class Document extends Doc {\n\n awareness: Awareness\n\n callbacks = {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n onUpdate: (document: Document, connection: Connection, update: Uint8Array) => {},\n beforeBroadcastStateless: (document: Document, stateless: string) => {},\n }\n\n connections: Map,\n connection: Connection\n }> = new Map()\n\n // The number of direct (non-websocket) connections to this document\n directConnectionsCount = 0\n\n name: string\n\n mux: mutex\n\n logger: Debugger\n\n isLoading: boolean\n\n /**\n * Constructor.\n */\n constructor(name: string, logger: Debugger, yDocOptions: {}) {\n super(yDocOptions)\n\n this.name = name\n this.mux = createMutex()\n\n this.awareness = new Awareness(this)\n this.awareness.setLocalState(null)\n\n this.awareness.on('update', this.handleAwarenessUpdate.bind(this))\n this.on('update', this.handleUpdate.bind(this))\n\n this.logger = logger\n this.isLoading = true\n }\n\n /**\n * Check if the Document is empty\n */\n isEmpty(fieldName: string): boolean {\n // eslint-disable-next-line no-underscore-dangle\n return !this.get(fieldName)._start\n }\n\n /**\n * Merge the given document(s) into this one\n */\n merge(documents: Doc|Array): Document {\n (Array.isArray(documents) ? documents : [documents]).forEach(document => {\n applyUpdate(this, encodeStateAsUpdate(document))\n })\n\n return this\n }\n\n /**\n * Set a callback that will be triggered when the document is updated\n */\n onUpdate(callback: (document: Document, connection: Connection, update: Uint8Array) => void): Document {\n this.callbacks.onUpdate = callback\n\n return this\n }\n\n /**\n * Set a callback that will be triggered before a stateless message is broadcasted\n */\n beforeBroadcastStateless(callback: (document: Document, stateless: string) => void): Document {\n this.callbacks.beforeBroadcastStateless = callback\n\n return this\n }\n\n /**\n * Register a connection and a set of clients on this document keyed by the\n * underlying websocket connection\n */\n addConnection(connection: Connection): Document {\n this.connections.set(connection.webSocket, {\n clients: new Set(),\n connection,\n })\n\n return this\n }\n\n /**\n * Is the given connection registered on this document\n */\n hasConnection(connection: Connection): boolean {\n return this.connections.has(connection.webSocket)\n }\n\n /**\n * Remove the given connection from this document\n */\n removeConnection(connection: Connection): Document {\n removeAwarenessStates(\n this.awareness,\n Array.from(this.getClients(connection.webSocket)),\n null,\n )\n\n this.connections.delete(connection.webSocket)\n\n return this\n }\n\n addDirectConnection(): Document {\n this.directConnectionsCount += 1\n\n return this\n }\n\n removeDirectConnection(): Document {\n if (this.directConnectionsCount > 0) {\n this.directConnectionsCount -= 1\n }\n\n return this\n }\n\n /**\n * Get the number of active connections for this document\n */\n getConnectionsCount(): number {\n return this.connections.size + this.directConnectionsCount\n }\n\n /**\n * Get an array of registered connections\n */\n getConnections(): Array {\n return Array.from(this.connections.values()).map(data => data.connection)\n }\n\n /**\n * Get the client ids for the given connection instance\n */\n getClients(connectionInstance: WebSocket): Set {\n const connection = this.connections.get(connectionInstance)\n\n return connection?.clients === undefined ? new Set() : connection.clients\n }\n\n /**\n * Has the document awareness states\n */\n hasAwarenessStates(): boolean {\n return this.awareness.getStates().size > 0\n }\n\n /**\n * Apply the given awareness update\n */\n applyAwarenessUpdate(connection: Connection, update: Uint8Array): Document {\n applyAwarenessUpdate(\n this.awareness,\n update,\n connection.webSocket,\n )\n\n return this\n }\n\n /**\n * Handle an awareness update and sync changes to clients\n * @private\n */\n private handleAwarenessUpdate(\n { added, updated, removed }: AwarenessUpdate,\n connectionInstance: WebSocket,\n ): Document {\n const changedClients = added.concat(updated, removed)\n\n if (connectionInstance !== null) {\n const connection = this.connections.get(connectionInstance)\n\n if (connection) {\n added.forEach((clientId: any) => connection.clients.add(clientId))\n removed.forEach((clientId: any) => connection.clients.delete(clientId))\n }\n }\n\n this.getConnections().forEach(connection => {\n const awarenessMessage = new OutgoingMessage(this.name)\n .createAwarenessUpdateMessage(this.awareness, changedClients)\n\n this.logger.log({\n direction: 'out',\n type: awarenessMessage.type,\n category: awarenessMessage.category,\n })\n\n connection.send(\n awarenessMessage.toUint8Array(),\n )\n })\n\n return this\n }\n\n /**\n * Handle an updated document and sync changes to clients\n */\n private handleUpdate(update: Uint8Array, connection: Connection): Document {\n this.callbacks.onUpdate(this, connection, update)\n\n const message = new OutgoingMessage(this.name)\n .createSyncMessage()\n .writeUpdate(update)\n\n this.getConnections().forEach(connection => {\n this.logger.log({\n direction: 'out',\n type: message.type,\n category: message.category,\n })\n\n connection.send(\n message.toUint8Array(),\n )\n })\n\n return this\n }\n\n /**\n * Broadcast stateless message to all connections\n */\n public broadcastStateless(payload: string): void {\n this.callbacks.beforeBroadcastStateless(this, payload)\n\n this.getConnections().forEach(connection => {\n connection.sendStateless(payload)\n })\n }\n}\n\nexport default Document\n","import { IncomingMessage } from 'http'\nimport { URLSearchParams } from 'url'\n\n/**\n * Get parameters by the given request\n */\nexport function getParameters(request?: Pick): URLSearchParams {\n const query = request?.url?.split('?') || []\n return new URLSearchParams(query[1] ? query[1] : '')\n}\n","import { IncomingHttpHeaders, IncomingMessage } from 'http'\nimport {\n Forbidden, Unauthorized, WsReadyStates,\n} from '@hocuspocus/common'\nimport * as decoding from 'lib0/decoding'\nimport { v4 as uuid } from 'uuid'\nimport WebSocket from 'ws'\n\nimport Connection from './Connection.js'\nimport { Debugger } from './Debugger.js'\nimport Document from './Document.js'\nimport { Hocuspocus } from './Hocuspocus.js'\nimport { IncomingMessage as SocketIncomingMessage } from './IncomingMessage.js'\nimport { OutgoingMessage } from './OutgoingMessage.js'\nimport {\n ConnectionConfiguration,\n MessageType,\n beforeHandleMessagePayload,\n onDisconnectPayload,\n} from './types.js'\nimport { getParameters } from './util/getParameters.js'\n\n/**\n * The `ClientConnection` class is responsible for handling an incoming WebSocket\n *\n * TODO-refactor:\n * - use event handlers instead of calling hooks directly, hooks should probably be called from Hocuspocus.ts\n */\nexport class ClientConnection {\n // this map indicates whether a `Connection` instance has already taken over for incoming message for the key (i.e. documentName)\n private readonly documentConnections: Record = {}\n\n // While the connection will be establishing messages will\n // be queued and handled later.\n private readonly incomingMessageQueue: Record = {}\n\n // While the connection is establishing, kee\n private readonly documentConnectionsEstablished = new Set()\n\n // hooks payload by Document\n private readonly hookPayloads: Record = {}\n\n private readonly callbacks = {\n onClose: [(document: Document, payload: onDisconnectPayload) => {}],\n }\n\n private readonly closeIdleConnectionTimeout: NodeJS.Timeout\n\n // Every new connection gets a unique identifier.\n private readonly socketId = uuid()\n\n /**\n * The `ClientConnection` class receives incoming WebSocket connections,\n * runs all hooks:\n *\n * - onConnect for all connections\n * - onAuthenticate only if required\n *\n * … and if nothings fails it’ll fully establish the connection and\n * load the Document then.\n */\n constructor(\n private readonly websocket: WebSocket,\n private readonly request: IncomingMessage,\n private readonly documentProvider: {\n createDocument: Hocuspocus['createDocument'],\n },\n // TODO: change to events\n private readonly hooks: Hocuspocus['hooks'],\n private readonly debuggerTool: Debugger,\n private readonly opts: {\n requiresAuthentication: boolean,\n timeout: number,\n },\n ) {\n // Make sure to close an idle connection after a while.\n this.closeIdleConnectionTimeout = setTimeout(() => {\n websocket.close(Unauthorized.code, Unauthorized.reason)\n }, opts.timeout)\n\n websocket.on('message', this.messageHandler)\n }\n\n /**\n * Set a callback that will be triggered when the connection is closed\n */\n public onClose(callback: (document: Document, payload: onDisconnectPayload) => void): ClientConnection {\n this.callbacks.onClose.push(callback)\n\n return this\n }\n\n /**\n * Create a new connection by the given request and document\n */\n private createConnection(connection: WebSocket, document: Document): Connection {\n const hookPayload = this.hookPayloads[document.name]\n const instance = new Connection(\n connection,\n hookPayload.request,\n document,\n this.opts.timeout,\n hookPayload.socketId,\n hookPayload.context,\n hookPayload.connection.readOnly,\n this.debuggerTool,\n )\n\n instance.onClose(async (document, event) => {\n const disconnectHookPayload: onDisconnectPayload = {\n instance: this.documentProvider as Hocuspocus, // TODO, this will be removed when we use events instead of hooks for this class\n clientsCount: document.getConnectionsCount(),\n context: hookPayload.context,\n document,\n socketId: hookPayload.socketId,\n documentName: document.name,\n requestHeaders: hookPayload.request.headers,\n requestParameters: getParameters(hookPayload.request),\n }\n\n await this.hooks('onDisconnect', hookPayload)\n this.callbacks.onClose.forEach((callback => callback(document, disconnectHookPayload)))\n })\n\n instance.onStatelessCallback(async payload => {\n try {\n return await this.hooks('onStateless', payload)\n } catch (error: any) {\n // TODO: weird pattern, what's the use of this?\n if (error?.message) {\n throw error\n }\n }\n })\n\n instance.beforeHandleMessage((connection, update) => {\n const beforeHandleMessagePayload: beforeHandleMessagePayload = {\n instance: this.documentProvider as Hocuspocus, // TODO, this will be removed when we use events instead of hooks for this class\n clientsCount: document.getConnectionsCount(),\n context: hookPayload.context,\n document,\n socketId: hookPayload.socketId,\n connection,\n documentName: document.name,\n requestHeaders: hookPayload.request.headers,\n requestParameters: getParameters(hookPayload.request),\n update,\n }\n\n return this.hooks('beforeHandleMessage', beforeHandleMessagePayload)\n })\n\n // If the WebSocket has already disconnected (wow, that was fast) – then\n // immediately call close to cleanup the connection and document in memory.\n if (\n connection.readyState === WsReadyStates.Closing\n || connection.readyState === WsReadyStates.Closed\n ) {\n instance.close()\n }\n\n return instance\n }\n\n // Once all hooks are run, we’ll fully establish the connection:\n private setUpNewConnection = async (documentName: string) => {\n // Not an idle connection anymore, no need to close it then.\n clearTimeout(this.closeIdleConnectionTimeout)\n\n const hookPayload = this.hookPayloads[documentName]\n // If no hook interrupts, create a document and connection\n const document = await this.documentProvider.createDocument(documentName, hookPayload.request, hookPayload.socketId, hookPayload.connection, hookPayload.context)\n const instance = this.createConnection(this.websocket, document)\n\n instance.onClose((document, event) => {\n delete this.hookPayloads[documentName]\n delete this.documentConnections[documentName]\n delete this.incomingMessageQueue[documentName]\n this.documentConnectionsEstablished.delete(documentName)\n\n if (Object.keys(this.documentConnections).length === 0) {\n instance.webSocket.close(event?.code, event?.reason) // TODO: Move this to Hocuspocus connection handler\n }\n })\n\n this.documentConnections[documentName] = true\n\n // There’s no need to queue messages anymore.\n // Let’s work through queued messages.\n this.incomingMessageQueue[documentName].forEach(input => {\n this.websocket.emit('message', input)\n })\n\n this.hooks('connected', {\n ...hookPayload,\n documentName,\n context: hookPayload.context,\n connectionInstance: instance,\n })\n }\n\n // This listener handles authentication messages and queues everything else.\n private handleQueueingMessage = async (data: Uint8Array) => {\n try {\n const tmpMsg = new SocketIncomingMessage(data)\n\n const documentName = decoding.readVarString(tmpMsg.decoder)\n const type = decoding.readVarUint(tmpMsg.decoder)\n\n if (!(type === MessageType.Auth && !this.documentConnectionsEstablished.has(documentName))) {\n this.incomingMessageQueue[documentName].push(data)\n return\n }\n\n // Okay, we’ve got the authentication message we’re waiting for:\n this.documentConnectionsEstablished.add(documentName)\n\n // The 2nd integer contains the submessage type\n // which will always be authentication when sent from client -> server\n decoding.readVarUint(tmpMsg.decoder)\n const token = decoding.readVarString(tmpMsg.decoder)\n\n this.debuggerTool.log({\n direction: 'in',\n type,\n category: 'Token',\n })\n\n try {\n const hookPayload = this.hookPayloads[documentName]\n await this.hooks('onAuthenticate', {\n token,\n ...hookPayload,\n documentName,\n }, (contextAdditions: any) => {\n // Hooks are allowed to give us even more context and we’ll merge everything together.\n // We’ll pass the context to other hooks then.\n hookPayload.context = { ...hookPayload.context, ...contextAdditions }\n })\n // All `onAuthenticate` hooks passed.\n hookPayload.connection.isAuthenticated = true\n\n // Let the client know that authentication was successful.\n const message = new OutgoingMessage(documentName).writeAuthenticated(hookPayload.connection.readOnly)\n\n this.debuggerTool.log({\n direction: 'out',\n type: message.type,\n category: message.category,\n })\n\n this.websocket.send(message.toUint8Array())\n\n // Time to actually establish the connection.\n await this.setUpNewConnection(documentName)\n } catch (err: any) {\n const error = err || Forbidden\n const message = new OutgoingMessage(documentName).writePermissionDenied(error.reason ?? 'permission-denied')\n\n this.debuggerTool.log({\n direction: 'out',\n type: message.type,\n category: message.category,\n })\n\n // Ensure that the permission denied message is sent before the\n // connection is closed\n this.websocket.send(message.toUint8Array(), () => {\n if (Object.keys(this.documentConnections).length === 0) {\n try {\n this.websocket.close(error.code ?? Forbidden.code, error.reason ?? Forbidden.reason)\n } catch (closeError) {\n // catch is needed in case invalid error code is returned by hook (that would fail sending the close message)\n console.error(closeError)\n this.websocket.close(Forbidden.code, Forbidden.reason)\n }\n }\n })\n }\n\n // Catch errors due to failed decoding of data\n } catch (error) {\n console.error(error)\n this.websocket.close(Unauthorized.code, Unauthorized.reason)\n }\n }\n\n private messageHandler = async (data: Uint8Array) => {\n try {\n const tmpMsg = new SocketIncomingMessage(data)\n\n const documentName = decoding.readVarString(tmpMsg.decoder)\n\n if (this.documentConnections[documentName] === true) {\n // we already have a `Connection` set up for this document\n return\n }\n\n const isFirst = this.incomingMessageQueue[documentName] === undefined\n if (isFirst) {\n this.incomingMessageQueue[documentName] = []\n if (this.hookPayloads[documentName]) {\n throw new Error('first message, but hookPayloads exists')\n }\n\n const hookPayload = {\n instance: this.documentProvider as Hocuspocus,\n request: this.request,\n connection: {\n readOnly: false,\n requiresAuthentication: this.opts.requiresAuthentication,\n isAuthenticated: false,\n },\n requestHeaders: this.request.headers,\n requestParameters: getParameters(this.request),\n socketId: this.socketId,\n context: {},\n }\n\n this.hookPayloads[documentName] = hookPayload\n }\n this.handleQueueingMessage(data)\n\n if (isFirst) {\n const hookPayload = this.hookPayloads[documentName]\n // if this is the first message, trigger onConnect & check if we can start the connection (only if no auth is required)\n try {\n await this.hooks('onConnect', { ...hookPayload, documentName }, (contextAdditions: any) => {\n // merge context from all hooks\n hookPayload.context = { ...hookPayload.context, ...contextAdditions }\n })\n\n if (hookPayload.connection.requiresAuthentication || this.documentConnectionsEstablished.has(documentName)) {\n // Authentication is required, we’ll need to wait for the Authentication message.\n return\n }\n this.documentConnectionsEstablished.add(documentName)\n\n await this.setUpNewConnection(documentName)\n } catch (err: any) {\n // if a hook interrupts, close the websocket connection\n const error = err || Forbidden\n try {\n this.websocket.close(error.code ?? Forbidden.code, error.reason ?? Forbidden.reason)\n } catch (closeError) {\n // catch is needed in case invalid error code is returned by hook (that would fail sending the close message)\n console.error(closeError)\n this.websocket.close(Unauthorized.code, Unauthorized.reason)\n }\n }\n }\n } catch (closeError) {\n // catch is needed in case an invalid payload crashes the parsing of the Uint8Array\n console.error(closeError)\n this.websocket.close(Unauthorized.code, Unauthorized.reason)\n }\n }\n}\n","import { URLSearchParams } from 'url'\nimport Document from './Document.js'\nimport type { Hocuspocus } from './Hocuspocus.js'\n\nexport class DirectConnection {\n document: Document | null = null\n\n instance!: Hocuspocus\n\n context: any\n\n /**\n * Constructor.\n */\n constructor(\n document: Document,\n instance: Hocuspocus,\n context?: any,\n ) {\n this.document = document\n this.instance = instance\n this.context = context\n\n this.document.addDirectConnection()\n }\n\n async transact(transaction: (document: Document) => void) {\n if (!this.document) {\n throw new Error('direct connection closed')\n }\n\n transaction(this.document)\n\n this.instance.storeDocumentHooks(this.document, {\n clientsCount: this.document.getConnectionsCount(),\n context: this.context,\n document: this.document,\n documentName: this.document.name,\n instance: this.instance,\n requestHeaders: {},\n requestParameters: new URLSearchParams(),\n socketId: 'server',\n })\n }\n\n disconnect() {\n this.document?.removeDirectConnection()\n this.document = null\n }\n}\n","import { Server as HTTPServer, IncomingMessage, createServer } from 'http'\nimport { ListenOptions } from 'net'\nimport {\n ResetConnection, awarenessStatesToArray,\n} from '@hocuspocus/common'\nimport kleur from 'kleur'\nimport { v4 as uuid } from 'uuid'\nimport WebSocket, { AddressInfo, WebSocketServer } from 'ws'\nimport { Doc, applyUpdate, encodeStateAsUpdate } from 'yjs'\nimport meta from '../package.json' assert { type: 'json' }\nimport { ClientConnection } from './ClientConnection'\n// TODO: would be nice to only have a dependency on ClientConnection, and not on Connection\nimport Connection from './Connection.js'\nimport { Debugger } from './Debugger.js'\nimport { DirectConnection } from './DirectConnection.js'\nimport Document from './Document.js'\nimport {\n AwarenessUpdate,\n Configuration,\n ConnectionConfiguration,\n HookName,\n HookPayload,\n beforeBroadcastStatelessPayload,\n onChangePayload,\n onDisconnectPayload,\n onListenPayload,\n onStoreDocumentPayload,\n} from './types.js'\nimport { getParameters } from './util/getParameters'\n\nexport const defaultConfiguration = {\n name: null,\n port: 80,\n address: '0.0.0.0',\n timeout: 30000,\n debounce: 2000,\n maxDebounce: 10000,\n quiet: false,\n yDocOptions: {\n gc: true,\n gcFilter: () => true,\n },\n}\n\n/**\n * Hocuspocus Server\n */\nexport class Hocuspocus {\n configuration: Configuration = {\n ...defaultConfiguration,\n extensions: [],\n onConfigure: () => new Promise(r => r(null)),\n onListen: () => new Promise(r => r(null)),\n onUpgrade: () => new Promise(r => r(null)),\n onConnect: () => new Promise(r => r(null)),\n connected: () => new Promise(r => r(null)),\n beforeHandleMessage: () => new Promise(r => r(null)),\n beforeBroadcastStateless: () => new Promise(r => r(null)),\n onStateless: () => new Promise(r => r(null)),\n onChange: () => new Promise(r => r(null)),\n onLoadDocument: () => new Promise(r => r(null)),\n onStoreDocument: () => new Promise(r => r(null)),\n afterStoreDocument: () => new Promise(r => r(null)),\n onAwarenessUpdate: () => new Promise(r => r(null)),\n onRequest: () => new Promise(r => r(null)),\n onDisconnect: () => new Promise(r => r(null)),\n onDestroy: () => new Promise(r => r(null)),\n }\n\n documents: Map = new Map()\n\n httpServer?: HTTPServer\n\n webSocketServer?: WebSocketServer\n\n debugger = new Debugger()\n\n constructor(configuration?: Partial) {\n if (configuration) {\n this.configure(configuration)\n }\n }\n\n /**\n * Configure the server\n */\n configure(configuration: Partial): Hocuspocus {\n this.configuration = {\n ...this.configuration,\n ...configuration,\n }\n\n this.configuration.extensions.sort((a, b) => {\n const one = typeof a.priority === 'undefined' ? 100 : a.priority\n const two = typeof b.priority === 'undefined' ? 100 : b.priority\n\n if (one > two) {\n return -1\n }\n\n if (one < two) {\n return 1\n }\n\n return 0\n })\n\n this.configuration.extensions.push({\n onConfigure: this.configuration.onConfigure,\n onListen: this.configuration.onListen,\n onUpgrade: this.configuration.onUpgrade,\n onConnect: this.configuration.onConnect,\n connected: this.configuration.connected,\n onAuthenticate: this.configuration.onAuthenticate,\n onLoadDocument: this.configuration.onLoadDocument,\n beforeHandleMessage: this.configuration.beforeHandleMessage,\n beforeBroadcastStateless: this.configuration.beforeBroadcastStateless,\n onStateless: this.configuration.onStateless,\n onChange: this.configuration.onChange,\n onStoreDocument: this.configuration.onStoreDocument,\n afterStoreDocument: this.configuration.afterStoreDocument,\n onAwarenessUpdate: this.configuration.onAwarenessUpdate,\n onRequest: this.configuration.onRequest,\n onDisconnect: this.configuration.onDisconnect,\n onDestroy: this.configuration.onDestroy,\n })\n\n this.hooks('onConfigure', {\n configuration: this.configuration,\n version: meta.version,\n instance: this,\n })\n\n return this\n }\n\n get requiresAuthentication(): boolean {\n return !!this.configuration.extensions.find(extension => {\n return extension.onAuthenticate !== undefined\n })\n }\n\n /**\n * Start the server\n */\n async listen(\n portOrCallback: number | ((data: onListenPayload) => Promise) | null = null,\n callback: any = null,\n ): Promise {\n if (typeof portOrCallback === 'number') {\n this.configuration.port = portOrCallback\n }\n\n if (typeof portOrCallback === 'function') {\n this.configuration.extensions.push({\n onListen: portOrCallback,\n })\n }\n\n if (typeof callback === 'function') {\n this.configuration.extensions.push({\n onListen: callback,\n })\n }\n\n const webSocketServer = new WebSocketServer({ noServer: true })\n\n webSocketServer.on('connection', async (incoming: WebSocket, request: IncomingMessage) => {\n\n incoming.on('error', error => {\n /**\n * Handle a ws instance error, which is required to prevent\n * the server from crashing when one happens\n * See https://github.com/websockets/ws/issues/1777#issuecomment-660803472\n * @private\n */\n this.debugger.log('Error emitted from webSocket instance:')\n this.debugger.log(error)\n })\n\n this.handleConnection(incoming, request)\n })\n\n const server = createServer(async (request, response) => {\n try {\n await this.hooks('onRequest', { request, response, instance: this })\n\n // default response if all prior hooks don't interfere\n response.writeHead(200, { 'Content-Type': 'text/plain' })\n response.end('OK')\n } catch (error) {\n // if a hook rejects and the error is empty, do nothing\n // this is only meant to prevent later hooks and the\n // default handler to do something. if a error is present\n // just rethrow it\n if (error) {\n throw error\n }\n }\n })\n\n server.on('upgrade', async (request, socket, head) => {\n try {\n await this.hooks('onUpgrade', {\n request,\n socket,\n head,\n instance: this,\n })\n\n // let the default websocket server handle the connection if\n // prior hooks don't interfere\n webSocketServer.handleUpgrade(request, socket, head, ws => {\n webSocketServer.emit('connection', ws, request)\n })\n } catch (error) {\n // if a hook rejects and the error is empty, do nothing\n // this is only meant to prevent later hooks and the\n // default handler to do something. if a error is present\n // just rethrow it\n\n // TODO: why?\n if (error) {\n throw error\n }\n }\n })\n\n this.httpServer = server\n this.webSocketServer = webSocketServer\n\n return new Promise((resolve: Function, reject: Function) => {\n server.listen({\n port: this.configuration.port,\n host: this.configuration.address,\n } as ListenOptions, async () => {\n if (!this.configuration.quiet && process.env.NODE_ENV !== 'testing') {\n this.showStartScreen()\n }\n\n const onListenPayload = {\n instance: this,\n configuration: this.configuration,\n port: this.address.port,\n }\n\n try {\n await this.hooks('onListen', onListenPayload)\n resolve(this)\n } catch (e) {\n reject(e)\n }\n })\n })\n }\n\n get address(): AddressInfo {\n return (this.httpServer?.address() || {\n port: this.configuration.port,\n address: this.configuration.address,\n family: 'IPv4',\n }) as AddressInfo\n }\n\n get URL(): string {\n return `${this.configuration.address}:${this.address.port}`\n }\n\n get webSocketURL(): string {\n return `ws://${this.URL}`\n }\n\n get httpURL(): string {\n return `http://${this.URL}`\n }\n\n private showStartScreen() {\n const name = this.configuration.name ? ` (${this.configuration.name})` : ''\n\n console.log()\n console.log(` ${kleur.cyan(`Hocuspocus v${meta.version}${name}`)}${kleur.green(' running at:')}`)\n console.log()\n console.log(` > HTTP: ${kleur.cyan(`${this.httpURL}`)}`)\n console.log(` > WebSocket: ${this.webSocketURL}`)\n\n const extensions = this.configuration?.extensions.map(extension => {\n return extension.constructor?.name\n })\n .filter(name => name)\n .filter(name => name !== 'Object')\n\n if (!extensions.length) {\n return\n }\n\n console.log()\n console.log(' Extensions:')\n\n extensions\n .forEach(name => {\n console.log(` - ${name}`)\n })\n\n console.log()\n console.log(` ${kleur.green('Ready.')}`)\n console.log()\n }\n\n /**\n * Get the total number of active documents\n */\n getDocumentsCount(): number {\n return this.documents.size\n }\n\n /**\n * Get the total number of active connections\n */\n getConnectionsCount(): number {\n return Array.from(this.documents.values()).reduce((acc, document) => {\n acc += document.getConnectionsCount()\n return acc\n }, 0)\n }\n\n /**\n * Force close one or more connections\n */\n closeConnections(documentName?: string) {\n // Iterate through all connections for all documents\n // and invoke their close method, which is a graceful\n // disconnect wrapper around the underlying websocket.close\n this.documents.forEach((document: Document) => {\n // If a documentName was specified, bail if it doesnt match\n if (documentName && document.name !== documentName) {\n return\n }\n\n document.connections.forEach(({ connection }) => {\n connection.close(ResetConnection)\n })\n })\n }\n\n /**\n * Destroy the server\n */\n async destroy(): Promise {\n this.httpServer?.close()\n\n try {\n this.webSocketServer?.close()\n this.webSocketServer?.clients.forEach(client => {\n client.terminate()\n })\n } catch (error) {\n console.error(error)\n //\n }\n\n this.debugger.flush()\n\n await this.hooks('onDestroy', { instance: this })\n }\n\n /**\n * The `handleConnection` method receives incoming WebSocket connections,\n * runs all hooks:\n *\n * - onConnect for all connections\n * - onAuthenticate only if required\n *\n * … and if nothings fails it’ll fully establish the connection and\n * load the Document then.\n */\n handleConnection(incoming: WebSocket, request: IncomingMessage): void {\n const clientConnection = new ClientConnection(incoming, request, this, this.hooks.bind(this), this.debugger, {\n requiresAuthentication: this.requiresAuthentication,\n timeout: this.configuration.timeout,\n })\n clientConnection.onClose((document: Document, hookPayload: onDisconnectPayload) => {\n // Check if there are still no connections to the document, as these hooks\n // may take some time to resolve (e.g. database queries). If a\n // new connection were to come in during that time it would rely on the\n // document in the map that we remove now.\n if (document.getConnectionsCount() > 0) {\n return\n }\n\n // If it’s the last connection, we need to make sure to store the\n // document. Use the debounce helper, to clear running timers,\n // but make it run immediately (`true`).\n // Only run this if the document has finished loading earlier (i.e. not to persist the empty\n // ydoc if the onLoadDocument hook returned an error)\n if (!document.isLoading) {\n this.debounce(`onStoreDocument-${document.name}`, () => {\n this.storeDocumentHooks(document, hookPayload)\n }, true)\n } else {\n // Remove document from memory immediately\n this.documents.delete(document.name)\n document.destroy()\n }\n })\n }\n\n /**\n * Handle update of the given document\n */\n private handleDocumentUpdate(document: Document, connection: Connection | undefined, update: Uint8Array, request?: IncomingMessage): void {\n const hookPayload: onChangePayload | onStoreDocumentPayload = {\n instance: this,\n clientsCount: document.getConnectionsCount(),\n context: connection?.context || {},\n document,\n documentName: document.name,\n requestHeaders: request?.headers ?? {},\n requestParameters: getParameters(request),\n socketId: connection?.socketId ?? '',\n update,\n }\n\n this.hooks('onChange', hookPayload).catch(error => {\n // TODO: what's the intention of this catch -> throw?\n throw error\n })\n\n // If the update was received through other ways than the\n // WebSocket connection, we don’t need to feel responsible for\n // storing the content.\n if (!connection) {\n return\n }\n\n this.debounce(`onStoreDocument-${document.name}`, () => {\n this.storeDocumentHooks(document, hookPayload)\n })\n }\n\n timers: Map = new Map()\n\n /**\n * debounce the given function, using the given identifier\n */\n debounce(id: string, func: Function, immediately = false) {\n const old = this.timers.get(id)\n const start = old?.start || Date.now()\n\n const run = () => {\n this.timers.delete(id)\n func()\n }\n\n if (old?.timeout) {\n clearTimeout(old.timeout)\n }\n\n if (immediately) {\n return run()\n }\n\n if (Date.now() - start >= this.configuration.maxDebounce) {\n return run()\n }\n\n this.timers.set(id, {\n start,\n timeout: setTimeout(run, this.configuration.debounce),\n })\n }\n\n /**\n * Create a new document by the given request\n */\n public async createDocument(documentName: string, request: Partial>, socketId: string, connection: ConnectionConfiguration, context?: any): Promise {\n if (this.documents.has(documentName)) {\n const document = this.documents.get(documentName)\n\n if (document) {\n return document\n }\n }\n\n const document = new Document(documentName, this.debugger, this.configuration.yDocOptions)\n this.documents.set(documentName, document)\n\n const hookPayload = {\n instance: this,\n context,\n connection,\n document,\n documentName,\n socketId,\n requestHeaders: request.headers,\n requestParameters: getParameters(request),\n }\n\n try {\n await this.hooks('onLoadDocument', hookPayload, (loadedDocument: Doc | undefined) => {\n // if a hook returns a Y-Doc, encode the document state as update\n // and apply it to the newly created document\n // Note: instanceof doesn't work, because Doc !== Doc for some reason I don't understand\n if (\n loadedDocument?.constructor.name === 'Document'\n || loadedDocument?.constructor.name === 'Doc'\n ) {\n applyUpdate(document, encodeStateAsUpdate(loadedDocument))\n }\n })\n } catch (e) {\n this.closeConnections(documentName)\n this.documents.delete(documentName)\n throw e\n }\n\n document.isLoading = false\n await this.hooks('afterLoadDocument', hookPayload)\n\n document.onUpdate((document: Document, connection: Connection, update: Uint8Array) => {\n this.handleDocumentUpdate(document, connection, update, connection?.request)\n })\n\n document.beforeBroadcastStateless((document: Document, stateless: string) => {\n const hookPayload: beforeBroadcastStatelessPayload = {\n document,\n documentName: document.name,\n payload: stateless,\n }\n\n this.hooks('beforeBroadcastStateless', hookPayload)\n })\n\n document.awareness.on('update', (update: AwarenessUpdate) => {\n this.hooks('onAwarenessUpdate', {\n ...hookPayload,\n ...update,\n awareness: document.awareness,\n states: awarenessStatesToArray(document.awareness.getStates()),\n })\n })\n\n return document\n }\n\n storeDocumentHooks(document: Document, hookPayload: onStoreDocumentPayload) {\n this.hooks('onStoreDocument', hookPayload)\n .catch(error => {\n if (error?.message) {\n throw error\n }\n })\n .then(() => {\n this.hooks('afterStoreDocument', hookPayload).then(() => {\n // Remove document from memory.\n\n if (document.getConnectionsCount() > 0) {\n return\n }\n\n this.documents.delete(document.name)\n document.destroy()\n })\n })\n }\n\n /**\n * Run the given hook on all configured extensions.\n * Runs the given callback after each hook.\n */\n hooks(name: HookName, payload: HookPayload, callback: Function | null = null): Promise {\n const { extensions } = this.configuration\n\n // create a new `thenable` chain\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve\n let chain = Promise.resolve()\n\n extensions\n // get me all extensions which have the given hook\n .filter(extension => typeof extension[name] === 'function')\n // run through all the configured hooks\n .forEach(extension => {\n chain = chain\n .then(() => (extension[name] as any)?.(payload))\n .catch(error => {\n // make sure to log error messages\n if (error?.message) {\n console.error(`[${name}]`, error.message)\n }\n\n throw error\n })\n\n if (callback) {\n chain = chain.then((...args: any[]) => callback(...args))\n }\n })\n\n return chain\n }\n\n enableDebugging() {\n this.debugger.enable()\n }\n\n enableMessageLogging() {\n this.debugger.enable()\n this.debugger.verbose()\n }\n\n disableLogging() {\n this.debugger.quiet()\n }\n\n disableDebugging() {\n this.debugger.disable()\n }\n\n flushMessageLogs() {\n this.debugger.flush()\n\n return this\n }\n\n getMessageLogs() {\n return this.debugger.get()?.logs\n }\n\n async openDirectConnection(documentName: string, context?: any): Promise {\n const connectionConfig: ConnectionConfiguration = {\n isAuthenticated: true,\n readOnly: false,\n requiresAuthentication: true,\n }\n\n const document: Document = await this.createDocument(\n documentName,\n {}, // direct connection has no request params\n uuid(),\n connectionConfig,\n context,\n )\n\n return new DirectConnection(document, this, context)\n }\n}\n\nexport const Server = new Hocuspocus()\n"],"names":["create","length","object.length","object.hasProperty","map.create","string.fromCamelCase","conditions.undefinedToNull","storage.varStorage","f.isOneOf","buffer.createUint8ArrayViewFromArrayBuffer","binary.BITS7","binary.BIT8","math.floor","string.utf8TextEncoder","string.encodeUtf8","math.min","math.max","error.create","number.MAX_SAFE_INTEGER","string.utf8TextDecoder","map.setIfUndefined","set.create","array.from","time.getUnixTime","f.equalityDeep","encoding.createEncoder","encoding.writeVarUint","encoding.writeVarString","encoding.toUint8Array","decoding.createDecoder","decoding.readVarUint","decoding.readVarString","encoding.writeVarUint8Array","decoding.readVarUint8Array","uuid","SocketIncomingMessage"],"mappings":";;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMA,QAAM,GAAG,MAAM,IAAI,GAAG;;ACNnC;AACA;AACA;AACA;AACA;AAsCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,IAAI,GAAG,KAAK,CAAC;;AClC1B;AACA;AACA;AACA;AACA,MAAM,WAAW,GAAG,CAAC,IAAI,CAAC,CAAC,WAAW,GAAE;AACxC;AACA,MAAM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AED,eAAe,GAAA;AACb,QAAA,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAA;KACvB;IAED,oBAAoB,GAAA;AAClB,QAAA,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAA;AACtB,QAAA,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAA;KACxB;IAED,cAAc,GAAA;AACZ,QAAA,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAA;KACtB;IAED,gBAAgB,GAAA;AACd,QAAA,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAA;KACxB;IAED,gBAAgB,GAAA;AACd,QAAA,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAA;AAErB,QAAA,OAAO,IAAI,CAAA;KACZ;IAED,cAAc,GAAA;;QACZ,OAAO,CAAA,EAAA,GAAA,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,MAAE,IAAA,IAAA,EAAA,KAAA,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,IAAI,CAAA;KACjC;AAED,IAAA,MAAM,oBAAoB,CAAC,YAAoB,EAAE,OAAa,EAAA;AAC5D,QAAA,MAAM,gBAAgB,GAA4B;AAChD,YAAA,eAAe,EAAE,IAAI;AACrB,YAAA,QAAQ,EAAE,KAAK;AACf,YAAA,sBAAsB,EAAE,IAAI;SAC7B,CAAA;QAED,MAAM,QAAQ,GAAa,MAAM,IAAI,CAAC,cAAc,CAClD,YAAY,EACZ,EAAE;AACF,QAAAG,EAAI,EAAE,EACN,gBAAgB,EAChB,OAAO,CACR,CAAA;QAED,OAAO,IAAI,gBAAgB,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAA;KACrD;AACF,CAAA;AAEY,MAAA,MAAM,GAAG,IAAI,UAAU;;;;"} -\ No newline at end of file -diff --git a/node_modules/@hocuspocus/server/dist/packages/provider/src/HocuspocusProvider.d.ts b/node_modules/@hocuspocus/server/dist/packages/provider/src/HocuspocusProvider.d.ts -index dffe09b..2168445 100644 ---- a/node_modules/@hocuspocus/server/dist/packages/provider/src/HocuspocusProvider.d.ts -+++ b/node_modules/@hocuspocus/server/dist/packages/provider/src/HocuspocusProvider.d.ts -@@ -1,10 +1,10 @@ --import * as Y from 'yjs'; --import { Awareness } from 'y-protocols/awareness'; - import * as mutex from 'lib0/mutex'; - import type { CloseEvent, Event, MessageEvent } from 'ws'; -+import { Awareness } from 'y-protocols/awareness'; -+import * as Y from 'yjs'; - import EventEmitter from './EventEmitter.js'; --import { ConstructableOutgoingMessage, onAuthenticationFailedParameters, onCloseParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onStatelessParameters, onStatusParameters, onSyncedParameters, WebSocketStatus, onAwarenessChangeParameters, onAwarenessUpdateParameters } from './types.js'; - import { CompleteHocuspocusProviderWebsocketConfiguration, HocuspocusProviderWebsocket } from './HocuspocusProviderWebsocket.js'; -+import { ConstructableOutgoingMessage, WebSocketStatus, onAuthenticationFailedParameters, onAwarenessChangeParameters, onAwarenessUpdateParameters, onCloseParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onStatelessParameters, onStatusParameters, onSyncedParameters } from './types.js'; - export type HocuspocusProviderConfiguration = Required> & Partial & (Required> | Required>); - export interface CompleteHocuspocusProviderConfiguration { - /** -@@ -77,7 +77,8 @@ export declare class HocuspocusProvider extends EventEmitter { - get document(): Y.Doc; - get awareness(): Awareness; - get hasUnsyncedChanges(): boolean; -- updateUnsyncedChanges(unsyncedChanges?: number): void; -+ incrementUnsyncedChanges(): void; -+ decrementUnsyncedChanges(): void; - forceSync(): void; - boundBeforeUnload: () => void; - beforeUnload(): void; -diff --git a/node_modules/@hocuspocus/server/dist/packages/provider/src/HocuspocusProviderWebsocket.d.ts b/node_modules/@hocuspocus/server/dist/packages/provider/src/HocuspocusProviderWebsocket.d.ts -index a3abfae..866ab85 100644 ---- a/node_modules/@hocuspocus/server/dist/packages/provider/src/HocuspocusProviderWebsocket.d.ts -+++ b/node_modules/@hocuspocus/server/dist/packages/provider/src/HocuspocusProviderWebsocket.d.ts -@@ -2,8 +2,8 @@ import * as mutex from 'lib0/mutex'; - import type { MessageEvent } from 'ws'; - import { Event } from 'ws'; - import EventEmitter from './EventEmitter.js'; --import { onCloseParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onStatusParameters, WebSocketStatus, onAwarenessChangeParameters, onAwarenessUpdateParameters } from './types.js'; - import { HocuspocusProvider } from './HocuspocusProvider.js'; -+import { WebSocketStatus, onAwarenessChangeParameters, onAwarenessUpdateParameters, onCloseParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onStatusParameters } from './types.js'; - export type HocuspocusProviderWebsocketConfiguration = Required> & Partial; - export interface CompleteHocuspocusProviderWebsocketConfiguration { - /** -@@ -76,6 +76,7 @@ export interface CompleteHocuspocusProviderWebsocketConfiguration { - quiet: boolean; - } - export declare class HocuspocusProviderWebsocket extends EventEmitter { -+ private messageQueue; - configuration: CompleteHocuspocusProviderWebsocketConfiguration; - subscribedToBroadcastChannel: boolean; - webSocket: WebSocket | null; -diff --git a/node_modules/@hocuspocus/server/dist/packages/provider/src/MessageReceiver.d.ts b/node_modules/@hocuspocus/server/dist/packages/provider/src/MessageReceiver.d.ts -index 8e5d55c..4d41340 100644 ---- a/node_modules/@hocuspocus/server/dist/packages/provider/src/MessageReceiver.d.ts -+++ b/node_modules/@hocuspocus/server/dist/packages/provider/src/MessageReceiver.d.ts -@@ -5,8 +5,9 @@ export declare class MessageReceiver { - broadcasted: boolean; - constructor(message: IncomingMessage); - setBroadcasted(value: boolean): this; -- apply(provider: HocuspocusProvider, emitSynced?: boolean): void; -+ apply(provider: HocuspocusProvider, emitSynced: boolean): void; - private applySyncMessage; -+ applySyncStatusMessage(provider: HocuspocusProvider, applied: boolean): void; - private applyAwarenessMessage; - private applyAuthMessage; - private applyQueryAwarenessMessage; -diff --git a/node_modules/@hocuspocus/server/dist/packages/provider/src/types.d.ts b/node_modules/@hocuspocus/server/dist/packages/provider/src/types.d.ts -index 1a67c25..fd3379e 100644 ---- a/node_modules/@hocuspocus/server/dist/packages/provider/src/types.d.ts -+++ b/node_modules/@hocuspocus/server/dist/packages/provider/src/types.d.ts -@@ -1,22 +1,23 @@ -+import { Encoder } from 'lib0/encoding'; -+import type { CloseEvent, Event, MessageEvent } from 'ws'; - import { Awareness } from 'y-protocols/awareness'; - import * as Y from 'yjs'; --import { Encoder } from 'lib0/encoding'; --import type { Event, CloseEvent, MessageEvent } from 'ws'; -+import { IncomingMessage } from './IncomingMessage.js'; -+import { OutgoingMessage } from './OutgoingMessage.js'; - import { AuthenticationMessage } from './OutgoingMessages/AuthenticationMessage.js'; - import { AwarenessMessage } from './OutgoingMessages/AwarenessMessage.js'; - import { QueryAwarenessMessage } from './OutgoingMessages/QueryAwarenessMessage.js'; - import { SyncStepOneMessage } from './OutgoingMessages/SyncStepOneMessage.js'; - import { SyncStepTwoMessage } from './OutgoingMessages/SyncStepTwoMessage.js'; - import { UpdateMessage } from './OutgoingMessages/UpdateMessage.js'; --import { IncomingMessage } from './IncomingMessage.js'; --import { OutgoingMessage } from './OutgoingMessage.js'; - export declare enum MessageType { - Sync = 0, - Awareness = 1, - Auth = 2, - QueryAwareness = 3, - Stateless = 5, -- CLOSE = 7 -+ CLOSE = 7, -+ SyncStatus = 8 - } - export declare enum WebSocketStatus { - Connecting = "connecting", -diff --git a/node_modules/@hocuspocus/server/dist/packages/server/src/ClientConnection.d.ts b/node_modules/@hocuspocus/server/dist/packages/server/src/ClientConnection.d.ts -new file mode 100644 -index 0000000..894206f ---- /dev/null -+++ b/node_modules/@hocuspocus/server/dist/packages/server/src/ClientConnection.d.ts -@@ -0,0 +1,55 @@ -+/// -+import { IncomingMessage } from 'http'; -+import WebSocket from 'ws'; -+import { Debugger } from './Debugger.js'; -+import Document from './Document.js'; -+import { Hocuspocus } from './Hocuspocus.js'; -+import { onDisconnectPayload } from './types.js'; -+/** -+ * The `ClientConnection` class is responsible for handling an incoming WebSocket -+ * -+ * TODO-refactor: -+ * - use event handlers instead of calling hooks directly, hooks should probably be called from Hocuspocus.ts -+ */ -+export declare class ClientConnection { -+ private readonly websocket; -+ private readonly request; -+ private readonly documentProvider; -+ private readonly hooks; -+ private readonly debuggerTool; -+ private readonly opts; -+ private readonly documentConnections; -+ private readonly incomingMessageQueue; -+ private readonly documentConnectionsEstablished; -+ private readonly hookPayloads; -+ private readonly callbacks; -+ private readonly closeIdleConnectionTimeout; -+ private readonly socketId; -+ /** -+ * The `ClientConnection` class receives incoming WebSocket connections, -+ * runs all hooks: -+ * -+ * - onConnect for all connections -+ * - onAuthenticate only if required -+ * -+ * … and if nothings fails it’ll fully establish the connection and -+ * load the Document then. -+ */ -+ constructor(websocket: WebSocket, request: IncomingMessage, documentProvider: { -+ createDocument: Hocuspocus['createDocument']; -+ }, hooks: Hocuspocus['hooks'], debuggerTool: Debugger, opts: { -+ requiresAuthentication: boolean; -+ timeout: number; -+ }); -+ /** -+ * Set a callback that will be triggered when the connection is closed -+ */ -+ onClose(callback: (document: Document, payload: onDisconnectPayload) => void): ClientConnection; -+ /** -+ * Create a new connection by the given request and document -+ */ -+ private createConnection; -+ private setUpNewConnection; -+ private handleQueueingMessage; -+ private messageHandler; -+} -diff --git a/node_modules/@hocuspocus/server/dist/packages/server/src/Hocuspocus.d.ts b/node_modules/@hocuspocus/server/dist/packages/server/src/Hocuspocus.d.ts -index 2709615..90d46c5 100644 ---- a/node_modules/@hocuspocus/server/dist/packages/server/src/Hocuspocus.d.ts -+++ b/node_modules/@hocuspocus/server/dist/packages/server/src/Hocuspocus.d.ts -@@ -1,11 +1,11 @@ - /// - /// --import { IncomingMessage, Server as HTTPServer } from 'http'; -+import { Server as HTTPServer, IncomingMessage } from 'http'; - import WebSocket, { AddressInfo, WebSocketServer } from 'ws'; --import { Configuration, HookName, HookPayload, onListenPayload, onStoreDocumentPayload } from './types.js'; --import Document from './Document.js'; - import { Debugger } from './Debugger.js'; - import { DirectConnection } from './DirectConnection.js'; -+import Document from './Document.js'; -+import { Configuration, ConnectionConfiguration, HookName, HookPayload, onListenPayload, onStoreDocumentPayload } from './types.js'; - export declare const defaultConfiguration: { - name: null; - port: number; -@@ -69,7 +69,7 @@ export declare class Hocuspocus { - * … and if nothings fails it’ll fully establish the connection and - * load the Document then. - */ -- handleConnection(incoming: WebSocket, request: IncomingMessage, context?: any): void; -+ handleConnection(incoming: WebSocket, request: IncomingMessage): void; - /** - * Handle update of the given document - */ -@@ -85,21 +85,13 @@ export declare class Hocuspocus { - /** - * Create a new document by the given request - */ -- private createDocument; -- /** -- * Create a new connection by the given request and document -- */ -- private createConnection; -+ createDocument(documentName: string, request: Partial>, socketId: string, connection: ConnectionConfiguration, context?: any): Promise; - storeDocumentHooks(document: Document, hookPayload: onStoreDocumentPayload): void; - /** - * Run the given hook on all configured extensions. - * Runs the given callback after each hook. - */ - hooks(name: HookName, payload: HookPayload, callback?: Function | null): Promise; -- /** -- * Get parameters by the given request -- */ -- private static getParameters; - enableDebugging(): void; - enableMessageLogging(): void; - disableLogging(): void; -diff --git a/node_modules/@hocuspocus/server/dist/packages/server/src/MessageReceiver.d.ts b/node_modules/@hocuspocus/server/dist/packages/server/src/MessageReceiver.d.ts -index 8a0a68a..7c12f51 100644 ---- a/node_modules/@hocuspocus/server/dist/packages/server/src/MessageReceiver.d.ts -+++ b/node_modules/@hocuspocus/server/dist/packages/server/src/MessageReceiver.d.ts -@@ -1,7 +1,7 @@ - import Connection from './Connection.js'; --import { IncomingMessage } from './IncomingMessage.js'; - import { Debugger } from './Debugger.js'; - import Document from './Document.js'; -+import { IncomingMessage } from './IncomingMessage.js'; - export declare class MessageReceiver { - message: IncomingMessage; - logger: Debugger; -diff --git a/node_modules/@hocuspocus/server/dist/packages/server/src/OutgoingMessage.d.ts b/node_modules/@hocuspocus/server/dist/packages/server/src/OutgoingMessage.d.ts -index dbd17e3..8cb4f13 100644 ---- a/node_modules/@hocuspocus/server/dist/packages/server/src/OutgoingMessage.d.ts -+++ b/node_modules/@hocuspocus/server/dist/packages/server/src/OutgoingMessage.d.ts -@@ -16,5 +16,6 @@ export declare class OutgoingMessage { - writeUpdate(update: Uint8Array): OutgoingMessage; - writeStateless(payload: string): OutgoingMessage; - writeBroadcastStateless(payload: string): OutgoingMessage; -+ writeSyncStatus(updateSaved: boolean): OutgoingMessage; - toUint8Array(): Uint8Array; - } -diff --git a/node_modules/@hocuspocus/server/dist/packages/server/src/types.d.ts b/node_modules/@hocuspocus/server/dist/packages/server/src/types.d.ts -index 30e719d..d905fc0 100644 ---- a/node_modules/@hocuspocus/server/dist/packages/server/src/types.d.ts -+++ b/node_modules/@hocuspocus/server/dist/packages/server/src/types.d.ts -@@ -4,9 +4,9 @@ - import { IncomingHttpHeaders, IncomingMessage, ServerResponse } from 'http'; - import { URLSearchParams } from 'url'; - import { Awareness } from 'y-protocols/awareness'; -+import Connection from './Connection.js'; - import Document from './Document.js'; - import { Hocuspocus } from './Hocuspocus.js'; --import Connection from './Connection.js'; - export declare enum MessageType { - Unknown = -1, - Sync = 0, -@@ -16,7 +16,8 @@ export declare enum MessageType { - SyncReply = 4, - Stateless = 5, - BroadcastStateless = 6, -- CLOSE = 7 -+ CLOSE = 7, -+ SyncStatus = 8 - } - export interface AwarenessUpdate { - added: Array; -diff --git a/node_modules/@hocuspocus/server/dist/packages/server/src/util/getParameters.d.ts b/node_modules/@hocuspocus/server/dist/packages/server/src/util/getParameters.d.ts -new file mode 100644 -index 0000000..9e5f4cf ---- /dev/null -+++ b/node_modules/@hocuspocus/server/dist/packages/server/src/util/getParameters.d.ts -@@ -0,0 +1,8 @@ -+/// -+/// -+import { IncomingMessage } from 'http'; -+import { URLSearchParams } from 'url'; -+/** -+ * Get parameters by the given request -+ */ -+export declare function getParameters(request?: Pick): URLSearchParams; -diff --git a/node_modules/@hocuspocus/server/dist/tests/provider/hasUnsyncedChanges.d.ts b/node_modules/@hocuspocus/server/dist/tests/provider/hasUnsyncedChanges.d.ts -new file mode 100644 -index 0000000..cb0ff5c ---- /dev/null -+++ b/node_modules/@hocuspocus/server/dist/tests/provider/hasUnsyncedChanges.d.ts -@@ -0,0 +1 @@ -+export {}; -diff --git a/node_modules/@hocuspocus/server/src/ClientConnection.ts b/node_modules/@hocuspocus/server/src/ClientConnection.ts -new file mode 100644 -index 0000000..7e65716 ---- /dev/null -+++ b/node_modules/@hocuspocus/server/src/ClientConnection.ts -@@ -0,0 +1,366 @@ -+import { IncomingHttpHeaders, IncomingMessage } from 'http' -+import { -+ Forbidden, Unauthorized, WsReadyStates, -+} from '@hocuspocus/common' -+import * as decoding from 'lib0/decoding' -+import { v4 as uuid } from 'uuid' -+import WebSocket from 'ws' -+ -+import Connection from './Connection.js' -+import { Debugger } from './Debugger.js' -+import Document from './Document.js' -+import { Hocuspocus } from './Hocuspocus.js' -+import { IncomingMessage as SocketIncomingMessage } from './IncomingMessage.js' -+import { OutgoingMessage } from './OutgoingMessage.js' -+import { -+ ConnectionConfiguration, -+ MessageType, -+ beforeHandleMessagePayload, -+ onDisconnectPayload, -+} from './types.js' -+import { getParameters } from './util/getParameters.js' -+ -+/** -+ * The `ClientConnection` class is responsible for handling an incoming WebSocket -+ * -+ * TODO-refactor: -+ * - use event handlers instead of calling hooks directly, hooks should probably be called from Hocuspocus.ts -+ */ -+export class ClientConnection { -+ // this map indicates whether a `Connection` instance has already taken over for incoming message for the key (i.e. documentName) -+ private readonly documentConnections: Record = {} -+ -+ // While the connection will be establishing messages will -+ // be queued and handled later. -+ private readonly incomingMessageQueue: Record = {} -+ -+ // While the connection is establishing, kee -+ private readonly documentConnectionsEstablished = new Set() -+ -+ // hooks payload by Document -+ private readonly hookPayloads: Record = {} -+ -+ private readonly callbacks = { -+ onClose: [(document: Document, payload: onDisconnectPayload) => {}], -+ } -+ -+ private readonly closeIdleConnectionTimeout: NodeJS.Timeout -+ -+ // Every new connection gets a unique identifier. -+ private readonly socketId = uuid() -+ -+ /** -+ * The `ClientConnection` class receives incoming WebSocket connections, -+ * runs all hooks: -+ * -+ * - onConnect for all connections -+ * - onAuthenticate only if required -+ * -+ * … and if nothings fails it’ll fully establish the connection and -+ * load the Document then. -+ */ -+ constructor( -+ private readonly websocket: WebSocket, -+ private readonly request: IncomingMessage, -+ private readonly documentProvider: { -+ createDocument: Hocuspocus['createDocument'], -+ }, -+ // TODO: change to events -+ private readonly hooks: Hocuspocus['hooks'], -+ private readonly debuggerTool: Debugger, -+ private readonly opts: { -+ requiresAuthentication: boolean, -+ timeout: number, -+ }, -+ ) { -+ // Make sure to close an idle connection after a while. -+ this.closeIdleConnectionTimeout = setTimeout(() => { -+ websocket.close(Unauthorized.code, Unauthorized.reason) -+ }, opts.timeout) -+ -+ websocket.on('message', this.messageHandler) -+ } -+ -+ /** -+ * Set a callback that will be triggered when the connection is closed -+ */ -+ public onClose(callback: (document: Document, payload: onDisconnectPayload) => void): ClientConnection { -+ this.callbacks.onClose.push(callback) -+ -+ return this -+ } -+ -+ /** -+ * Create a new connection by the given request and document -+ */ -+ private createConnection(connection: WebSocket, document: Document): Connection { -+ const hookPayload = this.hookPayloads[document.name] -+ const instance = new Connection( -+ connection, -+ hookPayload.request, -+ document, -+ this.opts.timeout, -+ hookPayload.socketId, -+ hookPayload.context, -+ hookPayload.connection.readOnly, -+ this.debuggerTool, -+ ) -+ -+ instance.onClose(async (document, event) => { -+ const disconnectHookPayload: onDisconnectPayload = { -+ instance: this.documentProvider as Hocuspocus, // TODO, this will be removed when we use events instead of hooks for this class -+ clientsCount: document.getConnectionsCount(), -+ context: hookPayload.context, -+ document, -+ socketId: hookPayload.socketId, -+ documentName: document.name, -+ requestHeaders: hookPayload.request.headers, -+ requestParameters: getParameters(hookPayload.request), -+ } -+ -+ await this.hooks('onDisconnect', hookPayload) -+ this.callbacks.onClose.forEach((callback => callback(document, disconnectHookPayload))) -+ }) -+ -+ instance.onStatelessCallback(async payload => { -+ try { -+ return await this.hooks('onStateless', payload) -+ } catch (error: any) { -+ // TODO: weird pattern, what's the use of this? -+ if (error?.message) { -+ throw error -+ } -+ } -+ }) -+ -+ instance.beforeHandleMessage((connection, update) => { -+ const beforeHandleMessagePayload: beforeHandleMessagePayload = { -+ instance: this.documentProvider as Hocuspocus, // TODO, this will be removed when we use events instead of hooks for this class -+ clientsCount: document.getConnectionsCount(), -+ context: hookPayload.context, -+ document, -+ socketId: hookPayload.socketId, -+ connection, -+ documentName: document.name, -+ requestHeaders: hookPayload.request.headers, -+ requestParameters: getParameters(hookPayload.request), -+ update, -+ } -+ -+ return this.hooks('beforeHandleMessage', beforeHandleMessagePayload) -+ }) -+ -+ // If the WebSocket has already disconnected (wow, that was fast) – then -+ // immediately call close to cleanup the connection and document in memory. -+ if ( -+ connection.readyState === WsReadyStates.Closing -+ || connection.readyState === WsReadyStates.Closed -+ ) { -+ instance.close() -+ } -+ -+ return instance -+ } -+ -+ // Once all hooks are run, we’ll fully establish the connection: -+ private setUpNewConnection = async (documentName: string) => { -+ // Not an idle connection anymore, no need to close it then. -+ clearTimeout(this.closeIdleConnectionTimeout) -+ -+ const hookPayload = this.hookPayloads[documentName] -+ // If no hook interrupts, create a document and connection -+ const document = await this.documentProvider.createDocument(documentName, hookPayload.request, hookPayload.socketId, hookPayload.connection, hookPayload.context) -+ const instance = this.createConnection(this.websocket, document) -+ -+ instance.onClose((document, event) => { -+ delete this.hookPayloads[documentName] -+ delete this.documentConnections[documentName] -+ delete this.incomingMessageQueue[documentName] -+ this.documentConnectionsEstablished.delete(documentName) -+ -+ if (Object.keys(this.documentConnections).length === 0) { -+ instance.webSocket.close(event?.code, event?.reason) // TODO: Move this to Hocuspocus connection handler -+ } -+ }) -+ -+ this.documentConnections[documentName] = true -+ -+ // There’s no need to queue messages anymore. -+ // Let’s work through queued messages. -+ this.incomingMessageQueue[documentName].forEach(input => { -+ this.websocket.emit('message', input) -+ }) -+ -+ this.hooks('connected', { -+ ...hookPayload, -+ documentName, -+ context: hookPayload.context, -+ connectionInstance: instance, -+ }) -+ } -+ -+ // This listener handles authentication messages and queues everything else. -+ private handleQueueingMessage = async (data: Uint8Array) => { -+ try { -+ const tmpMsg = new SocketIncomingMessage(data) -+ -+ const documentName = decoding.readVarString(tmpMsg.decoder) -+ const type = decoding.readVarUint(tmpMsg.decoder) -+ -+ if (!(type === MessageType.Auth && !this.documentConnectionsEstablished.has(documentName))) { -+ this.incomingMessageQueue[documentName].push(data) -+ return -+ } -+ -+ // Okay, we’ve got the authentication message we’re waiting for: -+ this.documentConnectionsEstablished.add(documentName) -+ -+ // The 2nd integer contains the submessage type -+ // which will always be authentication when sent from client -> server -+ decoding.readVarUint(tmpMsg.decoder) -+ const token = decoding.readVarString(tmpMsg.decoder) -+ -+ this.debuggerTool.log({ -+ direction: 'in', -+ type, -+ category: 'Token', -+ }) -+ -+ try { -+ const hookPayload = this.hookPayloads[documentName] -+ await this.hooks('onAuthenticate', { -+ token, -+ ...hookPayload, -+ documentName, -+ }, (contextAdditions: any) => { -+ // Hooks are allowed to give us even more context and we’ll merge everything together. -+ // We’ll pass the context to other hooks then. -+ hookPayload.context = { ...hookPayload.context, ...contextAdditions } -+ }) -+ // All `onAuthenticate` hooks passed. -+ hookPayload.connection.isAuthenticated = true -+ -+ // Let the client know that authentication was successful. -+ const message = new OutgoingMessage(documentName).writeAuthenticated(hookPayload.connection.readOnly) -+ -+ this.debuggerTool.log({ -+ direction: 'out', -+ type: message.type, -+ category: message.category, -+ }) -+ -+ this.websocket.send(message.toUint8Array()) -+ -+ // Time to actually establish the connection. -+ await this.setUpNewConnection(documentName) -+ } catch (err: any) { -+ const error = err || Forbidden -+ const message = new OutgoingMessage(documentName).writePermissionDenied(error.reason ?? 'permission-denied') -+ -+ this.debuggerTool.log({ -+ direction: 'out', -+ type: message.type, -+ category: message.category, -+ }) -+ -+ // Ensure that the permission denied message is sent before the -+ // connection is closed -+ this.websocket.send(message.toUint8Array(), () => { -+ if (Object.keys(this.documentConnections).length === 0) { -+ try { -+ this.websocket.close(error.code ?? Forbidden.code, error.reason ?? Forbidden.reason) -+ } catch (closeError) { -+ // catch is needed in case invalid error code is returned by hook (that would fail sending the close message) -+ console.error(closeError) -+ this.websocket.close(Forbidden.code, Forbidden.reason) -+ } -+ } -+ }) -+ } -+ -+ // Catch errors due to failed decoding of data -+ } catch (error) { -+ console.error(error) -+ this.websocket.close(Unauthorized.code, Unauthorized.reason) -+ } -+ } -+ -+ private messageHandler = async (data: Uint8Array) => { -+ try { -+ const tmpMsg = new SocketIncomingMessage(data) -+ -+ const documentName = decoding.readVarString(tmpMsg.decoder) -+ -+ if (this.documentConnections[documentName] === true) { -+ // we already have a `Connection` set up for this document -+ return -+ } -+ -+ const isFirst = this.incomingMessageQueue[documentName] === undefined -+ if (isFirst) { -+ this.incomingMessageQueue[documentName] = [] -+ if (this.hookPayloads[documentName]) { -+ throw new Error('first message, but hookPayloads exists') -+ } -+ -+ const hookPayload = { -+ instance: this.documentProvider as Hocuspocus, -+ request: this.request, -+ connection: { -+ readOnly: false, -+ requiresAuthentication: this.opts.requiresAuthentication, -+ isAuthenticated: false, -+ }, -+ requestHeaders: this.request.headers, -+ requestParameters: getParameters(this.request), -+ socketId: this.socketId, -+ context: {}, -+ } -+ -+ this.hookPayloads[documentName] = hookPayload -+ } -+ this.handleQueueingMessage(data) -+ -+ if (isFirst) { -+ const hookPayload = this.hookPayloads[documentName] -+ // if this is the first message, trigger onConnect & check if we can start the connection (only if no auth is required) -+ try { -+ await this.hooks('onConnect', { ...hookPayload, documentName }, (contextAdditions: any) => { -+ // merge context from all hooks -+ hookPayload.context = { ...hookPayload.context, ...contextAdditions } -+ }) -+ -+ if (hookPayload.connection.requiresAuthentication || this.documentConnectionsEstablished.has(documentName)) { -+ // Authentication is required, we’ll need to wait for the Authentication message. -+ return -+ } -+ this.documentConnectionsEstablished.add(documentName) -+ -+ await this.setUpNewConnection(documentName) -+ } catch (err: any) { -+ // if a hook interrupts, close the websocket connection -+ const error = err || Forbidden -+ try { -+ this.websocket.close(error.code ?? Forbidden.code, error.reason ?? Forbidden.reason) -+ } catch (closeError) { -+ // catch is needed in case invalid error code is returned by hook (that would fail sending the close message) -+ console.error(closeError) -+ this.websocket.close(Unauthorized.code, Unauthorized.reason) -+ } -+ } -+ } -+ } catch (closeError) { -+ // catch is needed in case an invalid payload crashes the parsing of the Uint8Array -+ console.error(closeError) -+ this.websocket.close(Unauthorized.code, Unauthorized.reason) -+ } -+ } -+} -diff --git a/node_modules/@hocuspocus/server/src/Hocuspocus.ts b/node_modules/@hocuspocus/server/src/Hocuspocus.ts -index 56f3e3d..b746ca2 100644 ---- a/node_modules/@hocuspocus/server/src/Hocuspocus.ts -+++ b/node_modules/@hocuspocus/server/src/Hocuspocus.ts -@@ -1,37 +1,32 @@ --import { createServer, IncomingMessage, Server as HTTPServer } from 'http' --import { URLSearchParams } from 'url' -+import { Server as HTTPServer, IncomingMessage, createServer } from 'http' - import { ListenOptions } from 'net' --import * as decoding from 'lib0/decoding' --import WebSocket, { AddressInfo, WebSocketServer } from 'ws' --import { Doc, encodeStateAsUpdate, applyUpdate } from 'yjs' --import { v4 as uuid } from 'uuid' --import kleur from 'kleur' - import { -- ResetConnection, -- Unauthorized, -- Forbidden, -- awarenessStatesToArray, -- WsReadyStates, -+ ResetConnection, awarenessStatesToArray, - } from '@hocuspocus/common' --import meta from '../package.json' assert {type: 'json'} --import { IncomingMessage as SocketIncomingMessage } from './IncomingMessage.js' -+import kleur from 'kleur' -+import { v4 as uuid } from 'uuid' -+import WebSocket, { AddressInfo, WebSocketServer } from 'ws' -+import { Doc, applyUpdate, encodeStateAsUpdate } from 'yjs' -+import meta from '../package.json' assert { type: 'json' } -+import { ClientConnection } from './ClientConnection' -+// TODO: would be nice to only have a dependency on ClientConnection, and not on Connection -+import Connection from './Connection.js' -+import { Debugger } from './Debugger.js' -+import { DirectConnection } from './DirectConnection.js' -+import Document from './Document.js' - import { -- MessageType, -+ AwarenessUpdate, - Configuration, - ConnectionConfiguration, - HookName, -- AwarenessUpdate, - HookPayload, -- beforeHandleMessagePayload, - beforeBroadcastStatelessPayload, -+ onChangePayload, -+ onDisconnectPayload, - onListenPayload, - onStoreDocumentPayload, - } from './types.js' --import Document from './Document.js' --import Connection from './Connection.js' --import { OutgoingMessage } from './OutgoingMessage.js' --import { Debugger } from './Debugger.js' --import { DirectConnection } from './DirectConnection.js' -+import { getParameters } from './util/getParameters' - - export const defaultConfiguration = { - name: null, -@@ -186,47 +181,49 @@ export class Hocuspocus { - this.handleConnection(incoming, request) - }) - -- const server = createServer((request, response) => { -- this.hooks('onRequest', { request, response, instance: this }) -- .then(() => { -- // default response if all prior hooks don't interfere -- response.writeHead(200, { 'Content-Type': 'text/plain' }) -- response.end('OK') -- }) -- .catch(error => { -- // if a hook rejects and the error is empty, do nothing -- // this is only meant to prevent later hooks and the -- // default handler to do something. if a error is present -- // just rethrow it -- if (error) { -- throw error -- } -- }) -+ const server = createServer(async (request, response) => { -+ try { -+ await this.hooks('onRequest', { request, response, instance: this }) -+ -+ // default response if all prior hooks don't interfere -+ response.writeHead(200, { 'Content-Type': 'text/plain' }) -+ response.end('OK') -+ } catch (error) { -+ // if a hook rejects and the error is empty, do nothing -+ // this is only meant to prevent later hooks and the -+ // default handler to do something. if a error is present -+ // just rethrow it -+ if (error) { -+ throw error -+ } -+ } - }) - -- server.on('upgrade', (request, socket, head) => { -- this.hooks('onUpgrade', { -- request, -- socket, -- head, -- instance: this, -- }) -- .then(() => { -- // let the default websocket server handle the connection if -- // prior hooks don't interfere -- webSocketServer.handleUpgrade(request, socket, head, ws => { -- webSocketServer.emit('connection', ws, request) -- }) -+ server.on('upgrade', async (request, socket, head) => { -+ try { -+ await this.hooks('onUpgrade', { -+ request, -+ socket, -+ head, -+ instance: this, - }) -- .catch(error => { -- // if a hook rejects and the error is empty, do nothing -- // this is only meant to prevent later hooks and the -- // default handler to do something. if a error is present -- // just rethrow it -- if (error) { -- throw error -- } -+ -+ // let the default websocket server handle the connection if -+ // prior hooks don't interfere -+ webSocketServer.handleUpgrade(request, socket, head, ws => { -+ webSocketServer.emit('connection', ws, request) - }) -+ } catch (error) { -+ // if a hook rejects and the error is empty, do nothing -+ // this is only meant to prevent later hooks and the -+ // default handler to do something. if a error is present -+ // just rethrow it -+ -+ // TODO: why? -+ if (error) { -+ throw error -+ } -+ } - }) - - this.httpServer = server -@@ -236,7 +233,7 @@ export class Hocuspocus { - server.listen({ - port: this.configuration.port, - host: this.configuration.address, -- } as ListenOptions, () => { -+ } as ListenOptions, async () => { - if (!this.configuration.quiet && process.env.NODE_ENV !== 'testing') { - this.showStartScreen() - } -@@ -247,9 +244,12 @@ export class Hocuspocus { - port: this.address.port, - } - -- this.hooks('onListen', onListenPayload) -- .then(() => resolve(this)) -- .catch(error => reject(error)) -+ try { -+ await this.hooks('onListen', onListenPayload) -+ resolve(this) -+ } catch (e) { -+ reject(e) -+ } - }) - }) - } -@@ -373,233 +373,55 @@ export class Hocuspocus { - * … and if nothings fails it’ll fully establish the connection and - * load the Document then. - */ -- handleConnection(incoming: WebSocket, request: IncomingMessage, context: any = null): void { -- // Make sure to close an idle connection after a while. -- const closeIdleConnection = setTimeout(() => { -- incoming.close(Unauthorized.code, Unauthorized.reason) -- }, this.configuration.timeout) -- -- // Every new connection gets a unique identifier. -- const socketId = uuid() -- -- // To override settings for specific connections, we’ll -- // keep track of a few things in the `ConnectionConfiguration`. -- const connection: ConnectionConfiguration = { -- readOnly: false, -+ handleConnection(incoming: WebSocket, request: IncomingMessage): void { -+ const clientConnection = new ClientConnection(incoming, request, this, this.hooks.bind(this), this.debugger, { - requiresAuthentication: this.requiresAuthentication, -- isAuthenticated: false, -- } -- -- // The `onConnect` and `onAuthenticate` hooks need some context -- // to decide who’s connecting, so let’s put it together: -- const hookPayload = { -- instance: this, -- request, -- requestHeaders: request.headers, -- requestParameters: Hocuspocus.getParameters(request), -- socketId, -- connection, -- } -- -- // this map indicates whether a `Connection` instance has already taken over for incoming message for the key (i.e. documentName) -- const documentConnections: Record = {} -- -- // While the connection will be establishing messages will -- // be queued and handled later. -- const incomingMessageQueue: Record = {} -- -- // While the connection is establishing -- const connectionEstablishing: Record = {} -- -- // Once all hooks are run, we’ll fully establish the connection: -- const setUpNewConnection = async (documentName: string) => { -- // Not an idle connection anymore, no need to close it then. -- clearTimeout(closeIdleConnection) -- -- // If no hook interrupts, create a document and connection -- const document = await this.createDocument(documentName, request, socketId, connection, context) -- const instance = this.createConnection(incoming, request, document, socketId, connection.readOnly, context) -- -- instance.onClose((document, event) => { -- delete documentConnections[documentName] -- delete incomingMessageQueue[documentName] -- delete connectionEstablishing[documentName] -- -- if (Object.keys(documentConnections).length === 0) { -- instance.webSocket.close(event?.code, event?.reason) // TODO: Move this to Hocuspocus connection handler -- } -- }) -- -- documentConnections[documentName] = true -- -- // There’s no need to queue messages anymore. -- // Let’s work through queued messages. -- incomingMessageQueue[documentName].forEach(input => { -- incoming.emit('message', input) -- }) -- -- this.hooks('connected', { -- ...hookPayload, -- documentName, -- context, -- connectionInstance: instance, -- }) -- } -- -- // This listener handles authentication messages and queues everything else. -- const handleQueueingMessage = (data: Uint8Array) => { -- try { -- const tmpMsg = new SocketIncomingMessage(data) -- -- const documentName = decoding.readVarString(tmpMsg.decoder) -- const type = decoding.readVarUint(tmpMsg.decoder) -- -- // Okay, we’ve got the authentication message we’re waiting for: -- if (type === MessageType.Auth && !connectionEstablishing[documentName]) { -- connectionEstablishing[documentName] = true -- -- // The 2nd integer contains the submessage type -- // which will always be authentication when sent from client -> server -- decoding.readVarUint(tmpMsg.decoder) -- const token = decoding.readVarString(tmpMsg.decoder) -- -- this.debugger.log({ -- direction: 'in', -- type, -- category: 'Token', -- }) -- -- this.hooks('onAuthenticate', { -- token, -- ...hookPayload, -- documentName, -- }, (contextAdditions: any) => { -- // Hooks are allowed to give us even more context and we’ll merge everything together. -- // We’ll pass the context to other hooks then. -- context = { ...context, ...contextAdditions } -- }) -- .then(() => { -- // All `onAuthenticate` hooks passed. -- connection.isAuthenticated = true -- -- // Let the client know that authentication was successful. -- const message = new OutgoingMessage(documentName).writeAuthenticated(connection.readOnly) -- -- this.debugger.log({ -- direction: 'out', -- type: message.type, -- category: message.category, -- }) -- -- incoming.send(message.toUint8Array()) -- }) -- .then(() => { -- // Time to actually establish the connection. -- return setUpNewConnection(documentName) -- }) -- .catch((error = Forbidden) => { -- const message = new OutgoingMessage(documentName).writePermissionDenied(error.reason ?? 'permission-denied') -- -- this.debugger.log({ -- direction: 'out', -- type: message.type, -- category: message.category, -- }) -- -- // Ensure that the permission denied message is sent before the -- // connection is closed -- incoming.send(message.toUint8Array(), () => { -- if (Object.keys(documentConnections).length === 0) { -- try { -- incoming.close(error.code ?? Forbidden.code, error.reason ?? Forbidden.reason) -- } catch (closeError) { -- // catch is needed in case invalid error code is returned by hook (that would fail sending the close message) -- console.error(closeError) -- incoming.close(Forbidden.code, Forbidden.reason) -- } -- } -- }) -- }) -- } else { -- incomingMessageQueue[documentName].push(data) -- } -- -- // Catch errors due to failed decoding of data -- } catch (error) { -- console.error(error) -- incoming.close(Unauthorized.code, Unauthorized.reason) -+ timeout: this.configuration.timeout, -+ }) -+ clientConnection.onClose((document: Document, hookPayload: onDisconnectPayload) => { -+ // Check if there are still no connections to the document, as these hooks -+ // may take some time to resolve (e.g. database queries). If a -+ // new connection were to come in during that time it would rely on the -+ // document in the map that we remove now. -+ if (document.getConnectionsCount() > 0) { -+ return - } -- } -- -- const messageHandler = (data: Uint8Array) => { -- try { -- const tmpMsg = new SocketIncomingMessage(data) -- -- const documentName = decoding.readVarString(tmpMsg.decoder) -- -- if (documentConnections[documentName] === true) { -- // we already have a `Connection` set up for this document -- return -- } -- -- // if this is the first message, trigger onConnect & check if we can start the connection (only if no auth is required) -- if (incomingMessageQueue[documentName] === undefined) { -- incomingMessageQueue[documentName] = [] - -- this.hooks('onConnect', { ...hookPayload, documentName }, (contextAdditions: any) => { -- // merge context from all hooks -- context = { ...context, ...contextAdditions } -- }) -- .then(() => { -- // Authentication is required, we’ll need to wait for the Authentication message. -- if (connection.requiresAuthentication || connectionEstablishing[documentName]) { -- return -- } -- connectionEstablishing[documentName] = true -- -- return setUpNewConnection(documentName) -- }) -- .catch((error = Forbidden) => { -- // if a hook interrupts, close the websocket connection -- try { -- incoming.close(error.code ?? Forbidden.code, error.reason ?? Forbidden.reason) -- } catch (closeError) { -- // catch is needed in case invalid error code is returned by hook (that would fail sending the close message) -- console.error(closeError) -- incoming.close(Unauthorized.code, Unauthorized.reason) -- } -- }) -- } -- -- handleQueueingMessage(data) -- } catch (closeError) { -- // catch is needed in case an invalid payload crashes the parsing of the Uint8Array -- console.error(closeError) -- incoming.close(Unauthorized.code, Unauthorized.reason) -+ // If it’s the last connection, we need to make sure to store the -+ // document. Use the debounce helper, to clear running timers, -+ // but make it run immediately (`true`). -+ // Only run this if the document has finished loading earlier (i.e. not to persist the empty -+ // ydoc if the onLoadDocument hook returned an error) -+ if (!document.isLoading) { -+ this.debounce(`onStoreDocument-${document.name}`, () => { -+ this.storeDocumentHooks(document, hookPayload) -+ }, true) -+ } else { -+ // Remove document from memory immediately -+ this.documents.delete(document.name) -+ document.destroy() - } -- -- } -- -- incoming.on('message', messageHandler) -+ }) - } - - /** - * Handle update of the given document - */ - private handleDocumentUpdate(document: Document, connection: Connection | undefined, update: Uint8Array, request?: IncomingMessage): void { -- const hookPayload = { -+ const hookPayload: onChangePayload | onStoreDocumentPayload = { - instance: this, - clientsCount: document.getConnectionsCount(), - context: connection?.context || {}, - document, - documentName: document.name, - requestHeaders: request?.headers ?? {}, -- requestParameters: Hocuspocus.getParameters(request), -+ requestParameters: getParameters(request), - socketId: connection?.socketId ?? '', - update, - } - - this.hooks('onChange', hookPayload).catch(error => { -+ // TODO: what's the intention of this catch -> throw? - throw error - }) - -@@ -653,7 +475,7 @@ export class Hocuspocus { - /** - * Create a new document by the given request - */ -- private async createDocument(documentName: string, request: Partial>, socketId: string, connection: ConnectionConfiguration, context?: any): Promise { -+ public async createDocument(documentName: string, request: Partial>, socketId: string, connection: ConnectionConfiguration, context?: any): Promise { - if (this.documents.has(documentName)) { - const document = this.documents.get(documentName) - -@@ -673,7 +495,7 @@ export class Hocuspocus { - documentName, - socketId, - requestHeaders: request.headers, -- requestParameters: Hocuspocus.getParameters(request), -+ requestParameters: getParameters(request), - } - - try { -@@ -723,99 +545,6 @@ export class Hocuspocus { - return document - } - -- /** -- * Create a new connection by the given request and document -- */ -- private createConnection(connection: WebSocket, request: IncomingMessage, document: Document, socketId: string, readOnly = false, context?: any): Connection { -- const instance = new Connection( -- connection, -- request, -- document, -- this.configuration.timeout, -- socketId, -- context, -- readOnly, -- this.debugger, -- ) -- -- instance.onClose(document => { -- const hookPayload = { -- instance: this, -- clientsCount: document.getConnectionsCount(), -- context, -- document, -- socketId, -- documentName: document.name, -- requestHeaders: request.headers, -- requestParameters: Hocuspocus.getParameters(request), -- } -- -- this.hooks('onDisconnect', hookPayload).then(() => { -- // Check if there are still no connections to the document, as these hooks -- // may take some time to resolve (e.g. database queries). If a -- // new connection were to come in during that time it would rely on the -- // document in the map that we remove now. -- if (document.getConnectionsCount() > 0) { -- return -- } -- -- // If it’s the last connection, we need to make sure to store the -- // document. Use the debounce helper, to clear running timers, -- // but make it run immediately (`true`). -- // Only run this if the document has finished loading earlier (i.e. not to persist the empty -- // ydoc if the onLoadDocument hook returned an error) -- if (!document.isLoading) { -- this.debounce(`onStoreDocument-${document.name}`, () => { -- this.storeDocumentHooks(document, hookPayload) -- }, true) -- -- } else { -- // Remove document from memory immediately -- this.documents.delete(document.name) -- document.destroy() -- } -- }) -- -- }) -- -- instance.onStatelessCallback(payload => { -- return this.hooks('onStateless', payload) -- .catch(error => { -- if (error?.message) { -- throw error -- } -- }) -- }) -- -- instance.beforeHandleMessage((connection, update) => { -- const hookPayload: beforeHandleMessagePayload = { -- instance: this, -- clientsCount: document.getConnectionsCount(), -- context, -- document, -- socketId, -- connection, -- documentName: document.name, -- requestHeaders: request.headers, -- requestParameters: Hocuspocus.getParameters(request), -- update, -- } -- -- return this.hooks('beforeHandleMessage', hookPayload) -- }) -- -- // If the WebSocket has already disconnected (wow, that was fast) – then -- // immediately call close to cleanup the connection and document in memory. -- if ( -- connection.readyState === WsReadyStates.Closing -- || connection.readyState === WsReadyStates.Closed -- ) { -- instance.close() -- } -- -- return instance -- } -- - storeDocumentHooks(document: Document, hookPayload: onStoreDocumentPayload) { - this.hooks('onStoreDocument', hookPayload) - .catch(error => { -@@ -872,14 +601,6 @@ export class Hocuspocus { - return chain - } - -- /** -- * Get parameters by the given request -- */ -- private static getParameters(request?: Pick): URLSearchParams { -- const query = request?.url?.split('?') || [] -- return new URLSearchParams(query[1] ? query[1] : '') -- } -- - enableDebugging() { - this.debugger.enable() - } -diff --git a/node_modules/@hocuspocus/server/src/MessageReceiver.ts b/node_modules/@hocuspocus/server/src/MessageReceiver.ts -index 3590f92..d090ae1 100644 ---- a/node_modules/@hocuspocus/server/src/MessageReceiver.ts -+++ b/node_modules/@hocuspocus/server/src/MessageReceiver.ts -@@ -1,3 +1,6 @@ -+import * as decoding from 'lib0/decoding' -+import { readVarString } from 'lib0/decoding' -+import { applyAwarenessUpdate } from 'y-protocols/awareness' - import { - messageYjsSyncStep1, - messageYjsSyncStep2, -@@ -6,14 +9,13 @@ import { - readSyncStep2, - readUpdate, - } from 'y-protocols/sync' --import { applyAwarenessUpdate } from 'y-protocols/awareness' --import { readVarString } from 'lib0/decoding' --import { MessageType } from './types.js' -+import * as Y from 'yjs' - import Connection from './Connection.js' --import { IncomingMessage } from './IncomingMessage.js' --import { OutgoingMessage } from './OutgoingMessage.js' - import { Debugger } from './Debugger.js' - import Document from './Document.js' -+import { IncomingMessage } from './IncomingMessage.js' -+import { OutgoingMessage } from './OutgoingMessage.js' -+import { MessageType } from './types.js' - - export class MessageReceiver { - -@@ -156,10 +158,35 @@ export class MessageReceiver { - }) - - if (connection?.readOnly) { -+ // We're in read-only mode, so we can't apply the update. -+ // Let's use snapshotContainsUpdate to see if the update actually contains changes. -+ // If not, we can still ack the update -+ const snapshot = Y.snapshot(document) -+ const update = decoding.readVarUint8Array(message.decoder) -+ if (Y.snapshotContainsUpdate(snapshot, update)) { -+ // no new changes in update -+ const ackMessage = new OutgoingMessage(document.name) -+ .writeSyncStatus(true) -+ -+ connection.send(ackMessage.toUint8Array()) -+ } else { -+ // new changes in update that we can't apply, because readOnly -+ const ackMessage = new OutgoingMessage(document.name) -+ .writeSyncStatus(false) -+ -+ connection.send(ackMessage.toUint8Array()) -+ } - break - } - - readSyncStep2(message.decoder, document, connection) -+ -+ if (connection) { -+ // TODO: how should this work if connection is not set? should we use reply? -+ // reply is used by redis, but I'm unsure how that code path works -+ connection.send(new OutgoingMessage(document.name) -+ .writeSyncStatus(true).toUint8Array()) -+ } - break - case messageYjsUpdate: - this.logger.log({ -@@ -169,10 +196,18 @@ export class MessageReceiver { - }) - - if (connection?.readOnly) { -+ connection.send(new OutgoingMessage(document.name) -+ .writeSyncStatus(false).toUint8Array()) - break - } - - readUpdate(message.decoder, document, connection) -+ if (connection) { -+ // TODO: how should this work if connection is not set? should we use reply? -+ // reply is used by redis, but I'm unsure how that code path works -+ connection.send(new OutgoingMessage(document.name) -+ .writeSyncStatus(true).toUint8Array()) -+ } - break - default: - throw new Error(`Received a message with an unknown type: ${type}`) -diff --git a/node_modules/@hocuspocus/server/src/OutgoingMessage.ts b/node_modules/@hocuspocus/server/src/OutgoingMessage.ts -index 17db7cf..650b9a4 100644 ---- a/node_modules/@hocuspocus/server/src/OutgoingMessage.ts -+++ b/node_modules/@hocuspocus/server/src/OutgoingMessage.ts -@@ -6,12 +6,12 @@ import { - writeVarUint, - writeVarUint8Array, - } from 'lib0/encoding' --import { writeSyncStep1, writeUpdate } from 'y-protocols/sync' - import { Awareness, encodeAwarenessUpdate } from 'y-protocols/awareness' -+import { writeSyncStep1, writeUpdate } from 'y-protocols/sync' - - import { writeAuthenticated, writePermissionDenied } from '@hocuspocus/common' --import { MessageType } from './types.js' - import Document from './Document.js' -+import { MessageType } from './types.js' - - export class OutgoingMessage { - -@@ -121,6 +121,16 @@ export class OutgoingMessage { - return this - } - -+ // TODO: should this be write* or create* as method name? -+ writeSyncStatus(updateSaved: boolean): OutgoingMessage { -+ this.category = 'SyncStatus' -+ -+ writeVarUint(this.encoder, MessageType.SyncStatus) -+ writeVarUint(this.encoder, updateSaved ? 1 : 0) -+ -+ return this -+ } -+ - toUint8Array(): Uint8Array { - return toUint8Array(this.encoder) - } -diff --git a/node_modules/@hocuspocus/server/src/types.ts b/node_modules/@hocuspocus/server/src/types.ts -index d5fff8e..924ea18 100644 ---- a/node_modules/@hocuspocus/server/src/types.ts -+++ b/node_modules/@hocuspocus/server/src/types.ts -@@ -3,9 +3,9 @@ import { - } from 'http' - import { URLSearchParams } from 'url' - import { Awareness } from 'y-protocols/awareness' -+import Connection from './Connection.js' - import Document from './Document.js' - import { Hocuspocus } from './Hocuspocus.js' --import Connection from './Connection.js' - - export enum MessageType { - Unknown = -1, -@@ -16,8 +16,8 @@ export enum MessageType { - SyncReply = 4, // same as Sync, but won't trigger another 'SyncStep1' - Stateless = 5, - BroadcastStateless = 6, -- - CLOSE = 7, -+ SyncStatus = 8, // TODO: should this be 8? - } - - export interface AwarenessUpdate { -diff --git a/node_modules/@hocuspocus/server/src/util/getParameters.ts b/node_modules/@hocuspocus/server/src/util/getParameters.ts -new file mode 100644 -index 0000000..7eb556b ---- /dev/null -+++ b/node_modules/@hocuspocus/server/src/util/getParameters.ts -@@ -0,0 +1,10 @@ -+import { IncomingMessage } from 'http' -+import { URLSearchParams } from 'url' -+ -+/** -+ * Get parameters by the given request -+ */ -+export function getParameters(request?: Pick): URLSearchParams { -+ const query = request?.url?.split('?') || [] -+ return new URLSearchParams(query[1] ? query[1] : '') -+}