@hocuspocus/provider 4.0.0-rc.0 → 4.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"hocuspocus-provider.cjs","names":["isNaN","binary.BITS31","binary.BITS32","math.floor","create","isArray","binary.BITS7","binary.BIT8","math.floor","string.encodeUtf8","string.utf8TextEncoder","math.min","math.max","create","error.create","binary.BITS7","binary.BIT8","number.MAX_SAFE_INTEGER","binary.BITS6","binary.BIT7","string.utf8TextDecoder","map.create","set.create","array.from","equalityTrait.EqualityTraitSymbol","object.size","object.hasProperty","array.isArray","time.getUnixTime","math.floor","f.equalityDeep","encoding.createEncoder","encoding.toUint8Array","decoding.createDecoder","decoding.readVarUint","decoding.readVarString","time.getUnixTime","encoding.createEncoder","encoding.toUint8Array","WsReadyStates","Y","decoding.readVarUint8Array","decoding.readVarUint","awarenessProtocol.encodeAwarenessUpdate","Y"],"sources":["../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/math.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/binary.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/number.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/set.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/array.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/string.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/encoding.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/error.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/decoding.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/time.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/map.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/observable.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/trait/equality.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/object.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/function.js","../../../node_modules/.pnpm/y-protocols@1.0.7_yjs@13.6.29/node_modules/y-protocols/awareness.js","../src/EventEmitter.ts","../src/IncomingMessage.ts","../src/types.ts","../src/OutgoingMessage.ts","../src/OutgoingMessages/CloseMessage.ts","../src/HocuspocusProviderWebsocket.ts","../../../node_modules/.pnpm/y-protocols@1.0.7_yjs@13.6.29/node_modules/y-protocols/sync.js","../src/MessageReceiver.ts","../src/MessageSender.ts","../src/version.ts","../src/OutgoingMessages/AuthenticationMessage.ts","../src/OutgoingMessages/AwarenessMessage.ts","../src/OutgoingMessages/StatelessMessage.ts","../src/OutgoingMessages/SyncStepOneMessage.ts","../src/OutgoingMessages/UpdateMessage.ts","../src/HocuspocusProvider.ts"],"sourcesContent":["/**\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 * Check whether n is negative, while considering the -0 edge case. While `-0 < 0` is false, this\n * function returns true for -0,-1,,.. and returns false for 0,1,2,...\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also distinguishes 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/**\n * Count the number of \"1\" bits in an unsigned 32bit number.\n *\n * Super fun bitcount algorithm by Brian Kernighan.\n *\n * @param {number} n\n */\nexport const countBits = n => {\n n &= binary.BITS32\n let count = 0\n while (n) {\n n &= (n - 1)\n count++\n }\n return count\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<T>} set\n * @return {Array<T>}\n */\nexport const toArray = set => Array.from(set)\n\n/**\n * @template T\n * @param {Set<T>} set\n * @return {T|undefined}\n */\nexport const first = set => set.values().next().value\n\n/**\n * @template T\n * @param {Iterable<T>} entries\n * @return {Set<T>}\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<L>} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array<C>}\n */\nexport const create = () => /** @type {Array<C>} */ ([])\n\n/**\n * @template D\n * @param {Array<D>} a\n * @return {Array<D>}\n */\nexport const copy = a => /** @type {Array<D>} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array<M>} dest\n * @param {Array<M>} 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<T>|Iterable<T>} 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 {ArrayLike<any>} ARR\n *\n * @param {ARR} arr\n * @param {ARR extends ArrayLike<infer S> ? ((value:S, index:number, arr:ARR) => boolean) : any} 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 {ArrayLike<any>} ARR\n *\n * @param {ARR} arr\n * @param {ARR extends ArrayLike<infer S> ? ((value:S, index:number, arr:ARR) => boolean) : never} 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<ELEM>} a\n * @param {ArrayLike<ELEM>} 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<Array<ELEM>>} arr\n * @return {Array<ELEM>}\n */\nexport const flatten = arr => fold(arr, /** @type {Array<ELEM>} */ ([]), (acc, val) => acc.concat(val))\n\n/**\n * @template T\n * @param {number} len\n * @param {function(number, Array<T>):T} f\n * @return {Array<T>}\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<T>} 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<T>} arr\n * @return {Array<T>}\n */\nexport const unique = arr => from(set.from(arr))\n\n/**\n * @template T\n * @template M\n * @param {ArrayLike<T>} arr\n * @param {function(T):M} mapper\n * @return {Array<T>}\n */\nexport const uniqueBy = (arr, mapper) => {\n /**\n * @type {Set<M>}\n */\n const happened = set.create()\n /**\n * @type {Array<T>}\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/**\n * @template {ArrayLike<any>} ARR\n * @template {function(ARR extends ArrayLike<infer T> ? T : never, number, ARR):any} MAPPER\n * @param {ARR} arr\n * @param {MAPPER} mapper\n * @return {Array<MAPPER extends function(...any): infer M ? M : never>}\n */\nexport const map = (arr, mapper) => {\n /**\n * @type {Array<any>}\n */\n const res = Array(arr.length)\n for (let i = 0; i < arr.length; i++) {\n res[i] = mapper(/** @type {any} */ (arr[i]), i, /** @type {any} */ (arr))\n }\n return /** @type {any} */ (res)\n}\n\n/**\n * This function bubble-sorts a single item to the correct position. The sort happens in-place and\n * might be useful to ensure that a single item is at the correct position in an otherwise sorted\n * array.\n *\n * @example\n * const arr = [3, 2, 5]\n * arr.sort((a, b) => a - b)\n * arr // => [2, 3, 5]\n * arr.splice(1, 0, 7)\n * array.bubbleSortItem(arr, 1, (a, b) => a - b)\n * arr // => [2, 3, 5, 7]\n *\n * @template T\n * @param {Array<T>} arr\n * @param {number} i\n * @param {(a:T,b:T) => number} compareFn\n */\nexport const bubblesortItem = (arr, i, compareFn) => {\n const n = arr[i]\n let j = i\n // try to sort to the right\n while (j + 1 < arr.length && compareFn(n, arr[j + 1]) > 0) {\n arr[j] = arr[j + 1]\n arr[++j] = n\n }\n if (i === j && j > 0) { // no change yet\n // sort to the left\n while (j > 0 && compareFn(arr[j - 1], n) > 0) {\n arr[j] = arr[j - 1]\n arr[--j] = n\n }\n }\n return j\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<ArrayBuffer>}\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<ArrayBuffer>}\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/**\n * Escape HTML characters &,<,>,',\" to their respective HTML entities &amp;,&lt;,&gt;,&#39;,&quot;\n *\n * @param {string} str\n */\nexport const escapeHTML = str =>\n str.replace(/[&<>'\"]/g, r => /** @type {string} */ ({\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n \"'\": '&#39;',\n '\"': '&quot;'\n }[r]))\n\n/**\n * Reverse of `escapeHTML`\n *\n * @param {string} str\n */\nexport const unescapeHTML = str =>\n str.replace(/&amp;|&lt;|&gt;|&#39;|&quot;/g, r => /** @type {string} */ ({\n '&amp;': '&',\n '&lt;': '<',\n '&gt;': '>',\n '&#39;': \"'\",\n '&quot;': '\"'\n }[r]))\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 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<Uint8Array>}\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<ArrayBuffer>} 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(new Uint8Array(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(new Uint8Array(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 * @typedef {Array<AnyEncodable>} AnyEncodableArray\n */\n\n/**\n * @typedef {undefined|null|number|bigint|boolean|string|{[k:string]:AnyEncodable}|AnyEncodableArray|Uint8Array} AnyEncodable\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<string,any> | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array<any> | 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 {AnyEncodable} 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 /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\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 /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\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 /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\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<string>}\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/**\n * @param {boolean} property\n * @return {asserts property is true}\n */\nexport const assert = property => { if (!property) throw create('Assert failed') }\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 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 * @template {ArrayBufferLike} [Buf=ArrayBufferLike]\n */\nexport class Decoder {\n /**\n * @param {Uint8Array<Buf>} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array<Buf>}\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 * @template {ArrayBufferLike} Buf\n * @param {Uint8Array<Buf>} uint8Array\n * @return {Decoder<Buf>}\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 * @template {ArrayBufferLike} Buf\n * @param {Decoder<Buf>} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array<Buf>}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = new Uint8Array(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 * @template {ArrayBufferLike} Buf\n * @param {Decoder<Buf>} decoder\n * @return {Uint8Array<Buf>}\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<function(Decoder):any>}\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<string,any>\n const len = readVarUint(decoder)\n /**\n * @type {Object<string,any>}\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<any>\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 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 * Utility module to work with key-value stores.\n *\n * @module map\n */\n\n/**\n * @template K\n * @template V\n * @typedef {Map<K,V>} GlobalMap\n */\n\n/**\n * Creates a new Map instance.\n *\n * @function\n * @return {Map<any, any>}\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 K,V\n * @param {Map<K,V>} m\n * @return {Map<K,V>}\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 {Map<any, any>} MAP\n * @template {MAP extends Map<any,infer V> ? function():V : unknown} CF\n * @param {MAP} map\n * @param {MAP extends Map<infer K,any> ? K : unknown} key\n * @param {CF} createT\n * @return {ReturnType<CF>}\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<K,V>} m\n * @param {function(V,K):R} f\n * @return {Array<R>}\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<K,V>} 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<K,V>} 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 * 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 * @experimental\n *\n * This is basically a (better typed) duplicate of Observable, which will replace Observable in the\n * next release.\n *\n * @template {{[key in keyof EVENTS]: function(...any):void}} EVENTS\n */\nexport class ObservableV2 {\n constructor () {\n /**\n * Some desc.\n * @type {Map<string, Set<any>>}\n */\n this._observers = map.create()\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, /** @type {string} */ (name), set.create).add(f)\n return f\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, /** @type {any} */ (_f))\n f(...args)\n }\n this.on(name, /** @type {any} */ (_f))\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} 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 * @template {keyof EVENTS & string} NAME\n * @param {NAME} name The event name.\n * @param {Parameters<EVENTS[NAME]>} 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/* c8 ignore start */\n/**\n * Handles named events.\n *\n * @deprecated\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map<N, any>}\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<any>} 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/* c8 ignore end */\n","export const EqualityTraitSymbol = Symbol('Equality')\n\n/**\n * @typedef {{ [EqualityTraitSymbol]:(other:EqualityTrait)=>boolean }} EqualityTrait\n */\n\n/**\n *\n * Utility function to compare any two objects.\n *\n * Note that it is expected that the first parameter is more specific than the latter one.\n *\n * @example js\n * class X { [traits.EqualityTraitSymbol] (other) { return other === this } }\n * class X2 { [traits.EqualityTraitSymbol] (other) { return other === this }, x2 () { return 2 } }\n * // this is fine\n * traits.equals(new X2(), new X())\n * // this is not, because the left type is less specific than the right one\n * traits.equals(new X(), new X2())\n *\n * @template {EqualityTrait} T\n * @param {NoInfer<T>} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equals = (a, b) => a === b || !!a?.[EqualityTraitSymbol]?.(b) || false\n","import * as equalityTrait from './trait/equality.js'\n\n/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object<string,any>} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * @param {any} o\n * @return {o is { [k:string]:any }}\n */\nexport const isObject = o => typeof o === 'object'\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object<string,any>} obj\n */\nexport const keys = Object.keys\n\n/**\n * @template V\n * @param {{[key:string]: V}} obj\n * @return {Array<V>}\n */\nexport const values = Object.values\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<string,any>} obj\n * @param {function(any,string):R} f\n * @return {Array<R>}\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 * @deprecated use object.size instead\n * @param {Object<string,any>} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object<string,any>} obj\n * @return {number}\n */\nexport const size = obj => keys(obj).length\n\n/**\n * @template {{ [key:string|number|symbol]: any }} T\n * @param {T} obj\n * @param {(v:T[keyof T],k:keyof T)=>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|null|undefined} obj\n */\nexport const isEmpty = obj => {\n // eslint-disable-next-line no-unreachable-loop\n for (const _k in obj) {\n return false\n }\n return true\n}\n\n/**\n * @template {{ [key:string|number|symbol]: any }} T\n * @param {T} obj\n * @param {(v:T[keyof T],k:keyof T)=>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|number|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object<string,any>} a\n * @param {Object<string,any>} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (size(a) === size(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && equalityTrait.equals(b[key], val)))\n\n/**\n * Make an object immutable. This hurts performance and is usually not needed if you perform good\n * coding practices.\n */\nexport const freeze = Object.freeze\n\n/**\n * Make an object and all its children immutable.\n * This *really* hurts performance and is usually not needed if you perform good coding practices.\n *\n * @template {any} T\n * @param {T} o\n * @return {Readonly<T>}\n */\nexport const deepFreeze = (o) => {\n for (const key in o) {\n const c = o[key]\n if (typeof c === 'object' || typeof c === 'function') {\n deepFreeze(o[key])\n }\n }\n return freeze(o)\n}\n\n/**\n * Get object property. Create T if property is undefined and set T on object.\n *\n * @function\n * @template {object} KV\n * @template {keyof KV} [K=keyof KV]\n * @param {KV} o\n * @param {K} key\n * @param {() => KV[K]} createT\n * @return {KV[K]}\n */\nexport const setIfUndefined = (o, key, createT) => hasProperty(o, key) ? o[key] : (o[key] = createT())\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'\nimport * as equalityTrait from './trait/equality.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array<function>} fs\n * @param {Array<any>} 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<T>|object} a\n * @param {Array<T>|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<T>} */ (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 === b) {\n return true\n }\n if (a == null || b == null || (a.constructor !== b.constructor && (a.constructor || Object) !== (b.constructor || Object))) {\n return false\n }\n if (a[equalityTrait.EqualityTraitSymbol] != null) {\n return a[equalityTrait.EqualityTraitSymbol](b)\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 undefined:\n case Object:\n if (object.size(a) !== object.size(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<OPTS>} 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<TYPE>}\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<TYPE>}\n **/\n n => n && n.constructor === T\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<string>}\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<number, Object<string, any>>}\n */\n this.states = new Map()\n /**\n * @type {Map<number, MetaClientState>}\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<number>}\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<string,any>|null}\n */\n getLocalState () {\n return this.states.get(this.clientID) || null\n }\n\n /**\n * @param {Object<string,any>|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<number,Object<string,any>>}\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<number>} 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<number>} 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\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic callbacks: { [key: string]: Function[] } = {};\n\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic on(event: string, fn: Function): this {\n\t\tif (!this.callbacks[event]) {\n\t\t\tthis.callbacks[event] = [];\n\t\t}\n\n\t\tthis.callbacks[event].push(fn);\n\n\t\treturn this;\n\t}\n\n\tprotected emit(event: string, ...args: any): this {\n\t\tconst callbacks = this.callbacks[event];\n\n\t\tif (callbacks) {\n\t\t\tcallbacks.forEach((callback) => callback.apply(this, args));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic off(event: string, fn?: Function): this {\n\t\tconst callbacks = this.callbacks[event];\n\n\t\tif (callbacks) {\n\t\t\tif (fn) {\n\t\t\t\tthis.callbacks[event] = callbacks.filter((callback) => callback !== fn);\n\t\t\t} else {\n\t\t\t\tdelete this.callbacks[event];\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tremoveAllListeners(): void {\n\t\tthis.callbacks = {};\n\t}\n}\n","import type { Decoder } from \"lib0/decoding\";\nimport {\n\tcreateDecoder,\n\tpeekVarString,\n\treadVarUint,\n\treadVarUint8Array,\n\treadVarString,\n} from \"lib0/decoding\";\nimport type { Encoder } from \"lib0/encoding\";\nimport {\n\tcreateEncoder,\n\twriteVarUint,\n\twriteVarUint8Array,\n\twriteVarString,\n\tlength,\n} from \"lib0/encoding\";\nimport type { MessageType } from \"./types.ts\";\n\nexport class IncomingMessage {\n\tdata: any;\n\n\tencoder: Encoder;\n\n\tdecoder: Decoder;\n\n\tconstructor(data: any) {\n\t\tthis.data = data;\n\t\tthis.encoder = createEncoder();\n\t\tthis.decoder = createDecoder(new Uint8Array(this.data));\n\t}\n\n\tpeekVarString(): string {\n\t\treturn peekVarString(this.decoder);\n\t}\n\n\treadVarUint(): MessageType {\n\t\treturn readVarUint(this.decoder);\n\t}\n\n\treadVarString(): string {\n\t\treturn readVarString(this.decoder);\n\t}\n\n\treadVarUint8Array() {\n\t\treturn readVarUint8Array(this.decoder);\n\t}\n\n\twriteVarUint(type: MessageType) {\n\t\treturn writeVarUint(this.encoder, type);\n\t}\n\n\twriteVarString(string: string) {\n\t\treturn writeVarString(this.encoder, string);\n\t}\n\n\twriteVarUint8Array(data: Uint8Array) {\n\t\treturn writeVarUint8Array(this.encoder, data);\n\t}\n\n\tlength() {\n\t\treturn length(this.encoder);\n\t}\n}\n","import type { Encoder } from \"lib0/encoding\";\nimport type { Awareness } from \"y-protocols/awareness\";\nimport type * as Y from \"yjs\";\nimport type { CloseEvent } from \"@hocuspocus/common\";\nimport type { IncomingMessage } from \"./IncomingMessage.ts\";\nimport type { OutgoingMessage } from \"./OutgoingMessage.ts\";\nimport type { AuthenticationMessage } from \"./OutgoingMessages/AuthenticationMessage.ts\";\nimport type { AwarenessMessage } from \"./OutgoingMessages/AwarenessMessage.ts\";\nimport type { QueryAwarenessMessage } from \"./OutgoingMessages/QueryAwarenessMessage.ts\";\nimport type { SyncStepOneMessage } from \"./OutgoingMessages/SyncStepOneMessage.ts\";\nimport type { SyncStepTwoMessage } from \"./OutgoingMessages/SyncStepTwoMessage.ts\";\nimport type { UpdateMessage } from \"./OutgoingMessages/UpdateMessage.ts\";\n\nexport enum MessageType {\n\tSync = 0,\n\tAwareness = 1,\n\tAuth = 2,\n\tQueryAwareness = 3,\n\tStateless = 5,\n\tCLOSE = 7,\n\tSyncStatus = 8,\n\tPing = 9,\n\tPong = 10,\n}\n\nexport enum WebSocketStatus {\n\tConnecting = \"connecting\",\n\tConnected = \"connected\",\n\tDisconnected = \"disconnected\",\n}\n\nexport type AuthorizedScope = \"read-write\" | \"readonly\";\n\nexport interface OutgoingMessageInterface {\n\tencoder: Encoder;\n\ttype?: MessageType;\n}\n\nexport interface OutgoingMessageArguments {\n\tdocumentName: string;\n\ttoken: string;\n\tdocument: Y.Doc;\n\tawareness: Awareness;\n\tclients: number[];\n\tstates: Map<number, { [key: string]: any }>;\n\tupdate: any;\n\tpayload: string;\n\tencoder: Encoder;\n}\n\nexport interface Constructable<T> {\n\tnew (...args: any): T;\n}\n\nexport type ConstructableOutgoingMessage =\n\t| Constructable<AuthenticationMessage>\n\t| Constructable<AwarenessMessage>\n\t| Constructable<QueryAwarenessMessage>\n\t| Constructable<SyncStepOneMessage>\n\t| Constructable<SyncStepTwoMessage>\n\t| Constructable<UpdateMessage>;\n\nexport type onAuthenticationFailedParameters = {\n\treason: string;\n};\n\nexport type onAuthenticatedParameters = {\n\tscope: AuthorizedScope;\n};\n\nexport type onOpenParameters = {\n\tevent: Event;\n};\n\nexport type onMessageParameters = {\n\tevent: MessageEvent;\n\tmessage: IncomingMessage;\n};\n\nexport type onOutgoingMessageParameters = {\n\tmessage: OutgoingMessage;\n};\n\nexport type onStatusParameters = {\n\tstatus: WebSocketStatus;\n};\n\nexport type onSyncedParameters = {\n\tstate: boolean;\n};\n\nexport type onUnsyncedChangesParameters = {\n\tnumber: number;\n};\n\nexport type onDisconnectParameters = {\n\tevent: CloseEvent;\n};\n\nexport type onCloseParameters = {\n\tevent: CloseEvent;\n};\n\nexport type onAwarenessUpdateParameters = {\n\tstates: StatesArray;\n};\n\nexport type onAwarenessChangeParameters = {\n\tstates: StatesArray;\n};\n\nexport type onStatelessParameters = {\n\tpayload: string;\n};\n\nexport type StatesArray = { clientId: number; [key: string | number]: any }[];\n","import type { Encoder } from \"lib0/encoding\";\nimport { createEncoder, toUint8Array } from \"lib0/encoding\";\nimport type {\n\tMessageType,\n\tOutgoingMessageArguments,\n\tOutgoingMessageInterface,\n} from \"./types.ts\";\n\nexport class OutgoingMessage implements OutgoingMessageInterface {\n\tencoder: Encoder;\n\n\ttype?: MessageType;\n\n\tconstructor() {\n\t\tthis.encoder = createEncoder();\n\t}\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\treturn args.encoder;\n\t}\n\n\ttoUint8Array() {\n\t\treturn toUint8Array(this.encoder);\n\t}\n}\n","import * as encoding from \"lib0/encoding\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class CloseMessage extends OutgoingMessage {\n\ttype = MessageType.CLOSE;\n\n\tdescription = \"Ask the server to close the connection\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tencoding.writeVarString(this.encoder, args.documentName!);\n\t\tencoding.writeVarUint(this.encoder, this.type);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { WsReadyStates } from \"@hocuspocus/common\";\nimport { retry } from \"@lifeomic/attempt\";\nimport * as encoding from \"lib0/encoding\";\nimport * as time from \"lib0/time\";\nimport EventEmitter from \"./EventEmitter.ts\";\nimport type { HocuspocusProvider } from \"./HocuspocusProvider.ts\";\nimport { IncomingMessage } from \"./IncomingMessage.ts\";\nimport { CloseMessage } from \"./OutgoingMessages/CloseMessage.ts\";\nimport {\n\tMessageType,\n\tWebSocketStatus,\n\ttype onAwarenessChangeParameters,\n\ttype onAwarenessUpdateParameters,\n\ttype onCloseParameters,\n\ttype onDisconnectParameters,\n\ttype onMessageParameters,\n\ttype onOpenParameters,\n\ttype onOutgoingMessageParameters,\n\ttype onStatusParameters,\n} from \"./types.ts\";\n\nexport type HocuspocusWebSocket = WebSocket & { identifier: string };\nexport type HocusPocusWebSocket = HocuspocusWebSocket;\n\nexport type HocuspocusProviderWebsocketConfiguration = Required<\n\tPick<CompleteHocuspocusProviderWebsocketConfiguration, \"url\">\n> &\n\tPartial<CompleteHocuspocusProviderWebsocketConfiguration>;\n\nexport interface CompleteHocuspocusProviderWebsocketConfiguration {\n\t/**\n\t * Whether to connect automatically when creating the provider instance. Default=true\n\t */\n\tautoConnect: boolean;\n\n\t/**\n\t * URL of your @hocuspocus/server instance\n\t */\n\turl: string;\n\n\t/**\n\t * By default, trailing slashes are removed from the URL. Set this to true\n\t * to preserve trailing slashes if your server configuration requires them.\n\t */\n\tpreserveTrailingSlash: boolean;\n\n\t/**\n\t * An optional WebSocket polyfill, for example for Node.js\n\t */\n\tWebSocketPolyfill: any;\n\n\t/**\n\t * Disconnect when no message is received for the defined amount of milliseconds.\n\t */\n\tmessageReconnectTimeout: number;\n\t/**\n\t * The delay between each attempt in milliseconds. You can provide a factor to have the delay grow exponentially.\n\t */\n\tdelay: number;\n\t/**\n\t * The initialDelay 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\t */\n\tinitialDelay: number;\n\t/**\n\t * The factor option is used to grow the delay exponentially.\n\t */\n\tfactor: number;\n\t/**\n\t * The maximum number of attempts or 0 if there is no limit on number of attempts.\n\t */\n\tmaxAttempts: number;\n\t/**\n\t * minDelay is used to set a lower bound of delay when jitter is enabled. This property has no effect if jitter is disabled.\n\t */\n\tminDelay: number;\n\t/**\n\t * 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\t */\n\tmaxDelay: number;\n\t/**\n\t * 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\t */\n\tjitter: boolean;\n\t/**\n\t * 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\t */\n\ttimeout: number;\n\thandleTimeout: (() => Promise<unknown>) | null;\n\tonOpen: (data: onOpenParameters) => void;\n\tonConnect: () => void;\n\tonMessage: (data: onMessageParameters) => void;\n\tonOutgoingMessage: (data: onOutgoingMessageParameters) => void;\n\tonStatus: (data: onStatusParameters) => void;\n\tonDisconnect: (data: onDisconnectParameters) => void;\n\tonClose: (data: onCloseParameters) => void;\n\tonDestroy: () => void;\n\tonAwarenessUpdate: (data: onAwarenessUpdateParameters) => void;\n\tonAwarenessChange: (data: onAwarenessChangeParameters) => void;\n\n\t/**\n\t * Map of attached providers keyed by documentName.\n\t */\n\tproviderMap: Map<string, HocuspocusProvider>;\n}\n\nexport class HocuspocusProviderWebsocket extends EventEmitter {\n\tprivate messageQueue: any[] = [];\n\n\tpublic configuration: CompleteHocuspocusProviderWebsocketConfiguration = {\n\t\turl: \"\",\n\t\tautoConnect: true,\n\t\tpreserveTrailingSlash: false,\n\t\t// @ts-ignore\n\t\tdocument: undefined,\n\t\tWebSocketPolyfill: undefined,\n\t\t// TODO: this should depend on awareness.outdatedTime\n\t\tmessageReconnectTimeout: 30000,\n\t\t// 1 second\n\t\tdelay: 1000,\n\t\t// instant\n\t\tinitialDelay: 0,\n\t\t// double the delay each time\n\t\tfactor: 2,\n\t\t// unlimited retries\n\t\tmaxAttempts: 0,\n\t\t// wait at least 1 second\n\t\tminDelay: 1000,\n\t\t// at least every 30 seconds\n\t\tmaxDelay: 30000,\n\t\t// randomize\n\t\tjitter: true,\n\t\t// retry forever\n\t\ttimeout: 0,\n\t\tonOpen: () => null,\n\t\tonConnect: () => null,\n\t\tonMessage: () => null,\n\t\tonOutgoingMessage: () => null,\n\t\tonStatus: () => null,\n\t\tonDisconnect: () => null,\n\t\tonClose: () => null,\n\t\tonDestroy: () => null,\n\t\tonAwarenessUpdate: () => null,\n\t\tonAwarenessChange: () => null,\n\t\thandleTimeout: null,\n\t\tproviderMap: new Map(),\n\t};\n\n\twebSocket: HocusPocusWebSocket | null = null;\n\n\twebSocketHandlers: { [key: string]: any } = {};\n\n\tshouldConnect = true;\n\n\tstatus = WebSocketStatus.Disconnected;\n\n\tlastMessageReceived = 0;\n\n\tidentifier = 0;\n\n\tintervals: any = {\n\t\tconnectionChecker: null,\n\t};\n\n\tconnectionAttempt: {\n\t\tresolve: (value?: any) => void;\n\t\treject: (reason?: any) => void;\n\t} | null = null;\n\n\tconstructor(configuration: HocuspocusProviderWebsocketConfiguration) {\n\t\tsuper();\n\t\tthis.setConfiguration(configuration);\n\n\t\tthis.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill\n\t\t\t? configuration.WebSocketPolyfill\n\t\t\t: WebSocket;\n\n\t\tthis.on(\"open\", this.configuration.onOpen);\n\t\tthis.on(\"open\", this.onOpen.bind(this));\n\t\tthis.on(\"connect\", this.configuration.onConnect);\n\t\tthis.on(\"message\", this.configuration.onMessage);\n\t\tthis.on(\"outgoingMessage\", this.configuration.onOutgoingMessage);\n\t\tthis.on(\"status\", this.configuration.onStatus);\n\t\tthis.on(\"disconnect\", this.configuration.onDisconnect);\n\t\tthis.on(\"close\", this.configuration.onClose);\n\t\tthis.on(\"destroy\", this.configuration.onDestroy);\n\t\tthis.on(\"awarenessUpdate\", this.configuration.onAwarenessUpdate);\n\t\tthis.on(\"awarenessChange\", this.configuration.onAwarenessChange);\n\n\t\tthis.on(\"close\", this.onClose.bind(this));\n\t\tthis.on(\"message\", this.onMessage.bind(this));\n\n\t\tthis.intervals.connectionChecker = setInterval(\n\t\t\tthis.checkConnection.bind(this),\n\t\t\tthis.configuration.messageReconnectTimeout / 10,\n\t\t);\n\n\t\tif (this.shouldConnect) {\n\t\t\tthis.connect();\n\t\t}\n\t}\n\n\treceivedOnOpenPayload?: Event | undefined = undefined;\n\n\tasync onOpen(event: Event) {\n\t\tthis.status = WebSocketStatus.Connected;\n\t\tthis.emit(\"status\", { status: WebSocketStatus.Connected });\n\n\t\tthis.cancelWebsocketRetry = undefined;\n\t\tthis.receivedOnOpenPayload = event;\n\t}\n\n\tattach(provider: HocuspocusProvider) {\n\t\tconst key = provider.effectiveName;\n\t\tconst existing = this.configuration.providerMap.get(key);\n\n\t\tif (existing && existing !== provider) {\n\t\t\t// Allow replacing a provider that hasn't authenticated (e.g., after auth failure retry)\n\t\t\tif (existing.isAuthenticated) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Cannot attach two providers with the same effective name \"${key}\". ` +\n\t\t\t\t\t\"Use sessionAwareness: true to multiplex providers with the same document name.\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tthis.configuration.providerMap.set(key, provider);\n\n\t\tif (this.status === WebSocketStatus.Disconnected && this.shouldConnect) {\n\t\t\tthis.connect();\n\t\t}\n\n\t\tif (\n\t\t\tthis.receivedOnOpenPayload &&\n\t\t\tthis.status === WebSocketStatus.Connected\n\t\t) {\n\t\t\tprovider.onOpen(this.receivedOnOpenPayload);\n\t\t}\n\t}\n\n\tdetach(provider: HocuspocusProvider) {\n\t\tconst key = provider.effectiveName;\n\t\tif (this.configuration.providerMap.has(key)) {\n\t\t\tprovider.send(CloseMessage, {\n\t\t\t\tdocumentName: key,\n\t\t\t});\n\t\t\tthis.configuration.providerMap.delete(key);\n\t\t}\n\t}\n\n\tpublic setConfiguration(\n\t\tconfiguration: Partial<HocuspocusProviderWebsocketConfiguration> = {},\n\t): void {\n\t\tthis.configuration = { ...this.configuration, ...configuration };\n\n\t\tif (!this.configuration.autoConnect) {\n\t\t\tthis.shouldConnect = false;\n\t\t}\n\t}\n\n\tcancelWebsocketRetry?: () => void;\n\n\tasync connect() {\n\t\tif (this.status === WebSocketStatus.Connected) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Always cancel any previously initiated connection retryer instances\n\t\tif (this.cancelWebsocketRetry) {\n\t\t\tthis.cancelWebsocketRetry();\n\t\t\tthis.cancelWebsocketRetry = undefined;\n\t\t}\n\n\t\tthis.receivedOnOpenPayload = undefined;\n\t\tthis.shouldConnect = true;\n\n\t\tconst abortableRetry = () => {\n\t\t\tlet cancelAttempt = false;\n\n\t\t\tconst retryPromise = retry(this.createWebSocketConnection.bind(this), {\n\t\t\t\tdelay: this.configuration.delay,\n\t\t\t\tinitialDelay: this.configuration.initialDelay,\n\t\t\t\tfactor: this.configuration.factor,\n\t\t\t\tmaxAttempts: this.configuration.maxAttempts,\n\t\t\t\tminDelay: this.configuration.minDelay,\n\t\t\t\tmaxDelay: this.configuration.maxDelay,\n\t\t\t\tjitter: this.configuration.jitter,\n\t\t\t\ttimeout: this.configuration.timeout,\n\t\t\t\thandleTimeout: this.configuration.handleTimeout,\n\t\t\t\tbeforeAttempt: (context) => {\n\t\t\t\t\tif (!this.shouldConnect || cancelAttempt) {\n\t\t\t\t\t\tcontext.abort();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}).catch((error: any) => {\n\t\t\t\t// If we aborted the connection attempt then don’t throw an error\n\t\t\t\t// ref: https://github.com/lifeomic/attempt/blob/master/src/index.ts#L136\n\t\t\t\tif (error && error.code !== \"ATTEMPT_ABORTED\") {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\tretryPromise,\n\t\t\t\tcancelFunc: () => {\n\t\t\t\t\tcancelAttempt = true;\n\t\t\t\t},\n\t\t\t};\n\t\t};\n\n\t\tconst { retryPromise, cancelFunc } = abortableRetry();\n\t\tthis.cancelWebsocketRetry = cancelFunc;\n\n\t\treturn retryPromise;\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tattachWebSocketListeners(ws: HocusPocusWebSocket, reject: Function) {\n\t\tconst { identifier } = ws;\n\t\tconst onMessageHandler = (payload: any) => this.emit(\"message\", payload);\n\t\tconst onCloseHandler = (payload: any) =>\n\t\t\tthis.emit(\"close\", { event: payload });\n\t\tconst onOpenHandler = (payload: any) => this.emit(\"open\", payload);\n\t\tconst onErrorHandler = (err: any) => {\n\t\t\treject(err);\n\t\t};\n\n\t\tthis.webSocketHandlers[identifier] = {\n\t\t\tmessage: onMessageHandler,\n\t\t\tclose: onCloseHandler,\n\t\t\topen: onOpenHandler,\n\t\t\terror: onErrorHandler,\n\t\t};\n\n\t\tconst handlers = this.webSocketHandlers[ws.identifier];\n\n\t\tObject.keys(handlers).forEach((name) => {\n\t\t\tws.addEventListener(name, handlers[name]);\n\t\t});\n\t}\n\n\tcleanupWebSocket() {\n\t\tif (!this.webSocket) {\n\t\t\treturn;\n\t\t}\n\t\tconst { identifier } = this.webSocket;\n\t\tconst handlers = this.webSocketHandlers[identifier];\n\n\t\tObject.keys(handlers).forEach((name) => {\n\t\t\tthis.webSocket?.removeEventListener(name, handlers[name]);\n\t\t\tdelete this.webSocketHandlers[identifier];\n\t\t});\n\t\tthis.webSocket.close();\n\t\tthis.webSocket = null;\n\t}\n\n\tcreateWebSocketConnection() {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (this.webSocket) {\n\t\t\t\tthis.messageQueue = [];\n\t\t\t\tthis.cleanupWebSocket();\n\t\t\t}\n\t\t\tthis.lastMessageReceived = 0;\n\t\t\tthis.identifier += 1;\n\n\t\t\t// Init the WebSocket connection\n\t\t\tconst ws = new this.configuration.WebSocketPolyfill(this.url);\n\t\t\tws.binaryType = \"arraybuffer\";\n\t\t\tws.identifier = this.identifier;\n\n\t\t\tthis.attachWebSocketListeners(ws, reject);\n\n\t\t\tthis.webSocket = ws;\n\n\t\t\t// Reset the status\n\t\t\tthis.status = WebSocketStatus.Connecting;\n\t\t\tthis.emit(\"status\", { status: WebSocketStatus.Connecting });\n\n\t\t\t// Store resolve/reject for later use\n\t\t\tthis.connectionAttempt = {\n\t\t\t\tresolve,\n\t\t\t\treject,\n\t\t\t};\n\t\t});\n\t}\n\n\tonMessage(event: MessageEvent) {\n\t\tthis.resolveConnectionAttempt();\n\n\t\tthis.lastMessageReceived = time.getUnixTime();\n\n\t\tconst data = new Uint8Array(event.data as ArrayBuffer);\n\n\t\t// Check for connection-level Ping message (no document name prefix)\n\t\t// Ping messages are sent as just the message type byte (length 1)\n\t\t// We check length to avoid confusing with regular messages that happen to have\n\t\t// a document name length of 9 as the first byte\n\t\tif (data.length === 1 && data[0] === MessageType.Ping) {\n\t\t\tthis.sendPong();\n\t\t\treturn;\n\t\t}\n\n\t\tconst message = new IncomingMessage(data);\n\t\tconst rawKey = message.peekVarString();\n\n\t\tconst provider = this.configuration.providerMap.get(rawKey);\n\t\tprovider?.onMessage(event);\n\t}\n\n\t/**\n\t * Send application-level Pong response to server Ping\n\t */\n\tprivate sendPong() {\n\t\tconst encoder = encoding.createEncoder();\n\t\tencoding.writeVarUint(encoder, MessageType.Pong);\n\t\tthis.send(encoding.toUint8Array(encoder));\n\t}\n\n\tresolveConnectionAttempt() {\n\t\tif (this.connectionAttempt) {\n\t\t\tthis.connectionAttempt.resolve();\n\t\t\tthis.connectionAttempt = null;\n\n\t\t\tthis.status = WebSocketStatus.Connected;\n\t\t\tthis.emit(\"status\", { status: WebSocketStatus.Connected });\n\t\t\tthis.emit(\"connect\");\n\t\t\tthis.messageQueue.forEach((message) => this.send(message));\n\t\t\tthis.messageQueue = [];\n\t\t}\n\t}\n\n\tstopConnectionAttempt() {\n\t\tthis.connectionAttempt = null;\n\t}\n\n\trejectConnectionAttempt() {\n\t\tthis.connectionAttempt?.reject();\n\t\tthis.connectionAttempt = null;\n\t}\n\n\tcloseTries = 0;\n\n\tcheckConnection() {\n\t\t// Don’t check the connection when it’s not even established\n\t\tif (this.status !== WebSocketStatus.Connected) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Don’t close the connection while waiting for the first message\n\t\tif (!this.lastMessageReceived) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Don’t close the connection when a message was received recently\n\t\tif (\n\t\t\tthis.configuration.messageReconnectTimeout >=\n\t\t\ttime.getUnixTime() - this.lastMessageReceived\n\t\t) {\n\t\t\treturn;\n\t\t}\n\n\t\t// No message received in a long time, not even your own\n\t\t// Awareness updates, which are updated every 15 seconds\n\t\t// if awareness is enabled.\n\t\tthis.closeTries += 1;\n\t\t// https://bugs.webkit.org/show_bug.cgi?id=247943\n\t\tif (this.closeTries > 2) {\n\t\t\tthis.onClose({\n\t\t\t\tevent: {\n\t\t\t\t\tcode: 4408,\n\t\t\t\t\treason: \"forced\",\n\t\t\t\t},\n\t\t\t});\n\t\t\tthis.closeTries = 0;\n\t\t} else {\n\t\t\tthis.webSocket?.close();\n\t\t\tthis.messageQueue = [];\n\t\t}\n\t}\n\n\tget serverUrl() {\n\t\tif (this.configuration.preserveTrailingSlash) {\n\t\t\treturn this.configuration.url;\n\t\t}\n\n\t\t// By default, ensure that the URL never ends with /\n\t\tlet url = this.configuration.url;\n\t\twhile (url[url.length - 1] === \"/\") {\n\t\t\turl = url.slice(0, url.length - 1);\n\t\t}\n\n\t\treturn url;\n\t}\n\n\tget url() {\n\t\treturn this.serverUrl;\n\t}\n\n\tdisconnect() {\n\t\tthis.shouldConnect = false;\n\n\t\tif (this.webSocket === null) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tthis.webSocket.close();\n\t\t\tthis.messageQueue = [];\n\t\t} catch (e) {\n\t\t\tconsole.error(e);\n\t\t}\n\t}\n\n\tsend(message: any) {\n\t\tif (this.webSocket?.readyState === WsReadyStates.Open) {\n\t\t\tthis.webSocket.send(message);\n\t\t} else {\n\t\t\tthis.messageQueue.push(message);\n\t\t}\n\t}\n\n\tonClose({ event }: onCloseParameters) {\n\t\tthis.closeTries = 0;\n\t\tthis.cleanupWebSocket();\n\n\t\tif (this.connectionAttempt) {\n\t\t\t// That connection attempt failed.\n\t\t\tthis.rejectConnectionAttempt();\n\t\t}\n\n\t\t// Let’s update the connection status.\n\t\tthis.status = WebSocketStatus.Disconnected;\n\t\tthis.emit(\"status\", { status: WebSocketStatus.Disconnected });\n\t\tthis.emit(\"disconnect\", { event });\n\n\t\t// trigger connect if no retry is running and we want to have a connection\n\t\tif (!this.cancelWebsocketRetry && this.shouldConnect) {\n\t\t\tsetTimeout(() => {\n\t\t\t\tthis.connect();\n\t\t\t}, this.configuration.delay);\n\t\t}\n\t}\n\n\tdestroy() {\n\t\tthis.emit(\"destroy\");\n\n\t\tclearInterval(this.intervals.connectionChecker);\n\n\t\t// If there is still a connection attempt outstanding then we should stop\n\t\t// it before calling disconnect, otherwise it will be rejected in the onClose\n\t\t// handler and trigger a retry\n\t\tthis.stopConnectionAttempt();\n\n\t\tthis.disconnect();\n\n\t\tthis.removeAllListeners();\n\n\t\tthis.cleanupWebSocket();\n\t}\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<number, number>} 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 should only reply to requests, and not initiate them.\n * Therefore it is necessary 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 * @param {(error:Error)=>any} [errorHandler]\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin, errorHandler) => {\n try {\n Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n } catch (error) {\n if (errorHandler != null) errorHandler(/** @type {Error} */ (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 * @param {(error:Error)=>any} [errorHandler]\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. Does not need to be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n * @param {(error:Error)=>any} [errorHandler] Optional error handler that catches errors when reading Yjs messages.\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin, errorHandler) => {\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, errorHandler)\n break\n case messageYjsUpdate:\n readUpdate(decoder, doc, transactionOrigin, errorHandler)\n break\n default:\n throw new Error('Unknown message type')\n }\n return messageType\n}\n","import { type CloseEvent, 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 type { HocuspocusProvider } from \"./HocuspocusProvider.ts\";\nimport type { IncomingMessage } from \"./IncomingMessage.ts\";\nimport { OutgoingMessage } from \"./OutgoingMessage.ts\";\nimport { MessageType } from \"./types.ts\";\n\nexport class MessageReceiver {\n\tmessage: IncomingMessage;\n\n\tconstructor(message: IncomingMessage) {\n\t\tthis.message = message;\n\t}\n\n\tpublic apply(provider: HocuspocusProvider, emitSynced: boolean) {\n\t\tconst { message } = this;\n\t\tconst type = message.readVarUint();\n\n\t\tconst emptyMessageLength = message.length();\n\n\t\tswitch (type) {\n\t\t\tcase MessageType.Sync:\n\t\t\t\tthis.applySyncMessage(provider, emitSynced);\n\t\t\t\tbreak;\n\n\t\t\tcase MessageType.Awareness:\n\t\t\t\tthis.applyAwarenessMessage(provider);\n\t\t\t\tbreak;\n\n\t\t\tcase MessageType.Auth:\n\t\t\t\tthis.applyAuthMessage(provider);\n\t\t\t\tbreak;\n\n\t\t\tcase MessageType.QueryAwareness:\n\t\t\t\tthis.applyQueryAwarenessMessage(provider);\n\t\t\t\tbreak;\n\n\t\t\tcase MessageType.Stateless:\n\t\t\t\tprovider.receiveStateless(readVarString(message.decoder));\n\t\t\t\tbreak;\n\n\t\t\tcase MessageType.SyncStatus:\n\t\t\t\tthis.applySyncStatusMessage(\n\t\t\t\t\tprovider,\n\t\t\t\t\treadVarInt(message.decoder) === 1,\n\t\t\t\t);\n\t\t\t\tbreak;\n\n\t\t\tcase MessageType.CLOSE:\n\t\t\t\t// eslint-disable-next-line no-case-declarations\n\t\t\t\tconst event: CloseEvent = {\n\t\t\t\t\tcode: 1000,\n\t\t\t\t\treason: readVarString(message.decoder),\n\t\t\t\t};\n\t\t\t\tprovider.onClose();\n\t\t\t\tprovider.configuration.onClose({ event });\n\t\t\t\tprovider.forwardClose({ event });\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tconsole.error(`Can’t apply message of unknown type: ${type}`);\n\t\t}\n\n\t\t// Reply\n\t\tif (message.length() > emptyMessageLength + 1) {\n\t\t\t// length of documentName (considered in emptyMessageLength plus length of yjs sync type, set in applySyncMessage)\n\t\t\t// @ts-ignore\n\t\t\tprovider.send(OutgoingMessage, { encoder: message.encoder });\n\t\t}\n\t}\n\n\tprivate applySyncMessage(provider: HocuspocusProvider, emitSynced: boolean) {\n\t\tconst { message } = this;\n\n\t\tmessage.writeVarUint(MessageType.Sync);\n\n\t\t// Apply update\n\t\tconst syncMessageType = readSyncMessage(\n\t\t\tmessage.decoder,\n\t\t\tmessage.encoder,\n\t\t\tprovider.document,\n\t\t\tprovider,\n\t\t);\n\n\t\t// Synced once we receive Step2\n\t\tif (emitSynced && syncMessageType === messageYjsSyncStep2) {\n\t\t\tprovider.synced = true;\n\t\t}\n\t}\n\n\tapplySyncStatusMessage(provider: HocuspocusProvider, applied: boolean) {\n\t\tif (applied) {\n\t\t\tprovider.decrementUnsyncedChanges();\n\t\t}\n\t}\n\n\tprivate applyAwarenessMessage(provider: HocuspocusProvider) {\n\t\tif (!provider.awareness) return;\n\n\t\tconst { message } = this;\n\n\t\tawarenessProtocol.applyAwarenessUpdate(\n\t\t\tprovider.awareness,\n\t\t\tmessage.readVarUint8Array(),\n\t\t\tprovider,\n\t\t);\n\t}\n\n\tprivate applyAuthMessage(provider: HocuspocusProvider) {\n\t\tconst { message } = this;\n\n\t\treadAuthMessage(\n\t\t\tmessage.decoder,\n\t\t\tprovider.sendToken.bind(provider),\n\t\t\tprovider.permissionDeniedHandler.bind(provider),\n\t\t\tprovider.authenticatedHandler.bind(provider),\n\t\t);\n\t}\n\n\tprivate applyQueryAwarenessMessage(provider: HocuspocusProvider) {\n\t\tif (!provider.awareness) return;\n\n\t\tconst { message } = this;\n\n\t\tmessage.writeVarUint(MessageType.Awareness);\n\t\tmessage.writeVarUint8Array(\n\t\t\tawarenessProtocol.encodeAwarenessUpdate(\n\t\t\t\tprovider.awareness,\n\t\t\t\tArray.from(provider.awareness.getStates().keys()),\n\t\t\t),\n\t\t);\n\t}\n}\n","import type { Encoder } from \"lib0/encoding\";\nimport { toUint8Array } from \"lib0/encoding\";\nimport type { ConstructableOutgoingMessage } from \"./types.ts\";\n\nexport class MessageSender {\n\tencoder: Encoder;\n\n\tmessage: any;\n\n\tconstructor(Message: ConstructableOutgoingMessage, args: any = {}) {\n\t\tthis.message = new Message();\n\t\tthis.encoder = this.message.get(args);\n\t}\n\n\tcreate() {\n\t\treturn toUint8Array(this.encoder);\n\t}\n\n\tsend(webSocket: any) {\n\t\twebSocket?.send(this.create());\n\t}\n}\n","// @ts-ignore - __HOCUSPOCUS_VERSION__ is replaced at build time by rolldown\n// eslint-disable-next-line\nexport const version: string = typeof __HOCUSPOCUS_VERSION__ !== 'undefined'\n\t? __HOCUSPOCUS_VERSION__\n\t: 'unknown';\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport { writeAuthentication } from \"@hocuspocus/common\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\nimport { version } from \"../version.ts\";\n\nexport class AuthenticationMessage extends OutgoingMessage {\n\ttype = MessageType.Auth;\n\n\tdescription = \"Authentication\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tif (typeof args.token === \"undefined\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"The authentication message requires `token` as an argument.\",\n\t\t\t);\n\t\t}\n\n\t\twriteVarString(this.encoder, args.documentName!);\n\t\twriteVarUint(this.encoder, this.type);\n\t\twriteAuthentication(this.encoder, args.token);\n\t\twriteVarString(this.encoder, version);\n\n\t\treturn this.encoder;\n\t}\n}\n","import * as encoding from \"lib0/encoding\";\nimport { encodeAwarenessUpdate } from \"y-protocols/awareness\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class AwarenessMessage extends OutgoingMessage {\n\ttype = MessageType.Awareness;\n\n\tdescription = \"Awareness states update\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tif (typeof args.awareness === \"undefined\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"The awareness message requires awareness as an argument\",\n\t\t\t);\n\t\t}\n\n\t\tif (typeof args.clients === \"undefined\") {\n\t\t\tthrow new Error(\"The awareness message requires clients as an argument\");\n\t\t}\n\n\t\tencoding.writeVarString(this.encoder, args.documentName!);\n\t\tencoding.writeVarUint(this.encoder, this.type);\n\n\t\tlet awarenessUpdate;\n\t\tif (args.states === undefined) {\n\t\t\tawarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients);\n\t\t} else {\n\t\t\tawarenessUpdate = encodeAwarenessUpdate(\n\t\t\t\targs.awareness,\n\t\t\t\targs.clients,\n\t\t\t\targs.states,\n\t\t\t);\n\t\t}\n\n\t\tencoding.writeVarUint8Array(this.encoder, awarenessUpdate);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class StatelessMessage extends OutgoingMessage {\n\ttype = MessageType.Stateless;\n\n\tdescription = \"A stateless message\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\twriteVarString(this.encoder, args.documentName!);\n\t\twriteVarUint(this.encoder, this.type);\n\t\twriteVarString(this.encoder, args.payload ?? \"\");\n\n\t\treturn this.encoder;\n\t}\n}\n","import * as encoding from \"lib0/encoding\";\nimport * as syncProtocol from \"y-protocols/sync\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class SyncStepOneMessage extends OutgoingMessage {\n\ttype = MessageType.Sync;\n\n\tdescription = \"First sync step\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tif (typeof args.document === \"undefined\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"The sync step one message requires document as an argument\",\n\t\t\t);\n\t\t}\n\n\t\tencoding.writeVarString(this.encoder, args.documentName!);\n\t\tencoding.writeVarUint(this.encoder, this.type);\n\t\tsyncProtocol.writeSyncStep1(this.encoder, args.document);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport { writeUpdate } from \"y-protocols/sync\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class UpdateMessage extends OutgoingMessage {\n\ttype = MessageType.Sync;\n\n\tdescription = \"A document update\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\twriteVarString(this.encoder, args.documentName!);\n\t\twriteVarUint(this.encoder, this.type);\n\n\t\twriteUpdate(this.encoder, args.update);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { awarenessStatesToArray, makeRoutingKey, parseRoutingKey } from \"@hocuspocus/common\";\nimport { Awareness, removeAwarenessStates } from \"y-protocols/awareness\";\nimport * as Y from \"yjs\";\nimport EventEmitter from \"./EventEmitter.ts\";\nimport type { CompleteHocuspocusProviderWebsocketConfiguration } from \"./HocuspocusProviderWebsocket.ts\";\nimport { HocuspocusProviderWebsocket } from \"./HocuspocusProviderWebsocket.ts\";\nimport { IncomingMessage } from \"./IncomingMessage.ts\";\nimport { MessageReceiver } from \"./MessageReceiver.ts\";\nimport { MessageSender } from \"./MessageSender.ts\";\nimport { AuthenticationMessage } from \"./OutgoingMessages/AuthenticationMessage.ts\";\nimport { AwarenessMessage } from \"./OutgoingMessages/AwarenessMessage.ts\";\nimport { StatelessMessage } from \"./OutgoingMessages/StatelessMessage.ts\";\nimport { SyncStepOneMessage } from \"./OutgoingMessages/SyncStepOneMessage.ts\";\nimport { UpdateMessage } from \"./OutgoingMessages/UpdateMessage.ts\";\nimport {\n\ttype AuthorizedScope,\n\ttype ConstructableOutgoingMessage,\n\ttype onAuthenticatedParameters,\n\ttype onAuthenticationFailedParameters,\n\ttype onAwarenessChangeParameters,\n\ttype onAwarenessUpdateParameters,\n\ttype onCloseParameters,\n\ttype onDisconnectParameters,\n\ttype onMessageParameters,\n\ttype onOpenParameters,\n\ttype onOutgoingMessageParameters,\n\ttype onStatelessParameters,\n\ttype onStatusParameters,\n\ttype onSyncedParameters,\n\ttype onUnsyncedChangesParameters,\n} from \"./types.ts\";\n\nexport type HocuspocusProviderConfiguration = Required<\n\tPick<CompleteHocuspocusProviderConfiguration, \"name\">\n> &\n\tPartial<CompleteHocuspocusProviderConfiguration> &\n\t(\n\t\t| (Required<Pick<CompleteHocuspocusProviderWebsocketConfiguration, \"url\">> &\n\t\t\t\tPartial<\n\t\t\t\t\tPick<\n\t\t\t\t\t\tCompleteHocuspocusProviderWebsocketConfiguration,\n\t\t\t\t\t\t\"preserveTrailingSlash\"\n\t\t\t\t\t>\n\t\t\t\t>)\n\t\t| Required<\n\t\t\t\tPick<CompleteHocuspocusProviderConfiguration, \"websocketProvider\">\n\t\t >\n\t);\n\nexport interface CompleteHocuspocusProviderConfiguration {\n\t/**\n\t * The identifier/name of your document\n\t */\n\tname: string;\n\t/**\n\t * The actual Y.js document\n\t */\n\tdocument: Y.Doc;\n\n\t/**\n\t * An Awareness instance to keep the presence state of all clients.\n\t *\n\t * You can disable sharing awareness information by passing `null`.\n\t * Note that having no awareness information shared across all connections will break our ping checks\n\t * and thus trigger reconnects. You should always have at least one Provider with enabled awareness per\n\t * socket connection, or ensure that the Provider receives messages before running into `HocuspocusProviderWebsocket.messageReconnectTimeout`.\n\t */\n\tawareness: Awareness | null;\n\n\t/**\n\t * A token that’s sent to the backend for authentication purposes.\n\t */\n\ttoken: string | (() => string) | (() => Promise<string>) | null;\n\n\t/**\n\t * Hocuspocus websocket provider\n\t */\n\twebsocketProvider: HocuspocusProviderWebsocket;\n\n\t/**\n\t * Enable session-aware multiplexing. When true, the provider embeds a unique\n\t * sessionId in the documentName field of every message, allowing multiple\n\t * providers with the same document name on a single WebSocket connection.\n\t *\n\t * Only set this to `false` when connecting to a v3 server that does not\n\t * support session awareness.\n\t *\n\t * Default: true\n\t */\n\tsessionAwareness: boolean;\n\n\t/**\n\t * Force syncing the document in the defined interval.\n\t */\n\tforceSyncInterval: false | number;\n\n\tonAuthenticated: (data: onAuthenticatedParameters) => void;\n\tonAuthenticationFailed: (data: onAuthenticationFailedParameters) => void;\n\tonOpen: (data: onOpenParameters) => void;\n\tonConnect: () => void;\n\tonStatus: (data: onStatusParameters) => void;\n\tonMessage: (data: onMessageParameters) => void;\n\tonOutgoingMessage: (data: onOutgoingMessageParameters) => void;\n\tonSynced: (data: onSyncedParameters) => void;\n\tonDisconnect: (data: onDisconnectParameters) => void;\n\tonClose: (data: onCloseParameters) => void;\n\tonDestroy: () => void;\n\tonAwarenessUpdate: (data: onAwarenessUpdateParameters) => void;\n\tonAwarenessChange: (data: onAwarenessChangeParameters) => void;\n\tonStateless: (data: onStatelessParameters) => void;\n\tonUnsyncedChanges: (data: onUnsyncedChangesParameters) => void;\n}\n\nexport class AwarenessError extends Error {\n\tcode = 1001;\n}\n\nexport class HocuspocusProvider extends EventEmitter {\n\tpublic configuration: CompleteHocuspocusProviderConfiguration = {\n\t\tname: \"\",\n\t\t// @ts-ignore\n\t\tdocument: undefined,\n\t\t// @ts-ignore\n\t\tawareness: undefined,\n\t\ttoken: null,\n\t\tsessionAwareness: true,\n\t\tforceSyncInterval: false,\n\t\tonAuthenticated: () => null,\n\t\tonAuthenticationFailed: () => null,\n\t\tonOpen: () => null,\n\t\tonConnect: () => null,\n\t\tonMessage: () => null,\n\t\tonOutgoingMessage: () => null,\n\t\tonSynced: () => null,\n\t\tonStatus: () => null,\n\t\tonDisconnect: () => null,\n\t\tonClose: () => null,\n\t\tonDestroy: () => null,\n\t\tonAwarenessUpdate: () => null,\n\t\tonAwarenessChange: () => null,\n\t\tonStateless: () => null,\n\t\tonUnsyncedChanges: () => null,\n\t};\n\n\tisSynced = false;\n\n\tunsyncedChanges = 0;\n\n\tisAuthenticated = false;\n\n\tauthorizedScope: AuthorizedScope | undefined = undefined;\n\n\t// @internal\n\tmanageSocket = false;\n\n\tprivate _isAttached = false;\n\n\t/**\n\t * Unique session identifier for this provider instance.\n\t * Used for multiplexing multiple providers with the same document name on a single WebSocket.\n\t */\n\tsessionId: string = Math.random().toString(36).slice(2);\n\n\t/**\n\t * The effective name used as the first VarString in messages.\n\t * When `sessionAwareness` is enabled, returns a composite key (documentName\\0sessionId).\n\t * Otherwise, returns the plain document name.\n\t */\n\tget effectiveName(): string {\n\t\treturn this.configuration.sessionAwareness\n\t\t\t? makeRoutingKey(this.configuration.name, this.sessionId)\n\t\t\t: this.configuration.name;\n\t}\n\n\tintervals: any = {\n\t\tforceSync: null,\n\t};\n\n\tconstructor(configuration: HocuspocusProviderConfiguration) {\n\t\tsuper();\n\t\tthis.setConfiguration(configuration);\n\n\t\tthis.configuration.document = configuration.document\n\t\t\t? configuration.document\n\t\t\t: new Y.Doc();\n\t\tthis.configuration.awareness =\n\t\t\tconfiguration.awareness !== undefined\n\t\t\t\t? configuration.awareness\n\t\t\t\t: new Awareness(this.document);\n\n\t\tthis.on(\"open\", this.configuration.onOpen);\n\t\tthis.on(\"message\", this.configuration.onMessage);\n\t\tthis.on(\"outgoingMessage\", this.configuration.onOutgoingMessage);\n\t\tthis.on(\"synced\", this.configuration.onSynced);\n\t\tthis.on(\"destroy\", this.configuration.onDestroy);\n\t\tthis.on(\"awarenessUpdate\", this.configuration.onAwarenessUpdate);\n\t\tthis.on(\"awarenessChange\", this.configuration.onAwarenessChange);\n\t\tthis.on(\"stateless\", this.configuration.onStateless);\n\t\tthis.on(\"unsyncedChanges\", this.configuration.onUnsyncedChanges);\n\n\t\tthis.on(\"authenticated\", this.configuration.onAuthenticated);\n\t\tthis.on(\"authenticationFailed\", this.configuration.onAuthenticationFailed);\n\n\t\tthis.awareness?.on(\"update\", () => {\n\t\t\tthis.emit(\"awarenessUpdate\", {\n\t\t\t\tstates: awarenessStatesToArray(this.awareness!.getStates()),\n\t\t\t});\n\t\t});\n\n\t\tthis.awareness?.on(\"change\", () => {\n\t\t\tthis.emit(\"awarenessChange\", {\n\t\t\t\tstates: awarenessStatesToArray(this.awareness!.getStates()),\n\t\t\t});\n\t\t});\n\n\t\tthis.document.on(\"update\", this.boundDocumentUpdateHandler);\n\t\tthis.awareness?.on(\"update\", this.boundAwarenessUpdateHandler);\n\n\t\tthis.registerEventListeners();\n\n\t\tif (\n\t\t\tthis.configuration.forceSyncInterval &&\n\t\t\ttypeof this.configuration.forceSyncInterval === \"number\"\n\t\t) {\n\t\t\tthis.intervals.forceSync = setInterval(\n\t\t\t\tthis.forceSync.bind(this),\n\t\t\t\tthis.configuration.forceSyncInterval,\n\t\t\t);\n\t\t}\n\n\t\tif (this.manageSocket) {\n\t\t\tthis.attach();\n\t\t}\n\t}\n\n\tboundDocumentUpdateHandler = this.documentUpdateHandler.bind(this);\n\n\tboundAwarenessUpdateHandler = this.awarenessUpdateHandler.bind(this);\n\n\tboundPageHide = this.pageHide.bind(this);\n\n\tboundOnOpen = this.onOpen.bind(this);\n\n\tboundOnClose = this.onClose.bind(this);\n\n\tforwardConnect = () => this.emit(\"connect\");\n\n\tforwardStatus = (e: onStatusParameters) => this.emit(\"status\", e);\n\n\tforwardClose = (e: onCloseParameters) => this.emit(\"close\", e);\n\n\tforwardDisconnect = (e: onDisconnectParameters) => this.emit(\"disconnect\", e);\n\n\tforwardDestroy = () => this.emit(\"destroy\");\n\n\tpublic setConfiguration(\n\t\tconfiguration: Partial<HocuspocusProviderConfiguration> = {},\n\t): void {\n\t\tif (!configuration.websocketProvider) {\n\t\t\tthis.manageSocket = true;\n\t\t\tthis.configuration.websocketProvider = new HocuspocusProviderWebsocket(\n\t\t\t\tconfiguration as CompleteHocuspocusProviderWebsocketConfiguration,\n\t\t\t);\n\t\t}\n\n\t\tthis.configuration = { ...this.configuration, ...configuration };\n\t}\n\n\tget document() {\n\t\treturn this.configuration.document;\n\t}\n\n\tpublic get isAttached() {\n\t\treturn this._isAttached;\n\t}\n\n\tget awareness() {\n\t\treturn this.configuration.awareness;\n\t}\n\n\tget hasUnsyncedChanges(): boolean {\n\t\treturn this.unsyncedChanges > 0;\n\t}\n\n\tprivate resetUnsyncedChanges() {\n\t\tthis.unsyncedChanges = 1;\n\t\tthis.emit(\"unsyncedChanges\", { number: this.unsyncedChanges });\n\t}\n\n\tincrementUnsyncedChanges() {\n\t\tthis.unsyncedChanges += 1;\n\t\tthis.emit(\"unsyncedChanges\", { number: this.unsyncedChanges });\n\t}\n\n\tdecrementUnsyncedChanges() {\n\t\tif (this.unsyncedChanges > 0) {\n\t\t\tthis.unsyncedChanges -= 1;\n\t\t}\n\n\t\tif (this.unsyncedChanges === 0) {\n\t\t\tthis.synced = true;\n\t\t}\n\n\t\tthis.emit(\"unsyncedChanges\", { number: this.unsyncedChanges });\n\t}\n\n\tforceSync() {\n\t\tthis.resetUnsyncedChanges();\n\n\t\tthis.send(SyncStepOneMessage, {\n\t\t\tdocument: this.document,\n\t\t\tdocumentName: this.effectiveName,\n\t\t});\n\t}\n\n\tpageHide() {\n\t\tif (this.awareness) {\n\t\t\tremoveAwarenessStates(\n\t\t\t\tthis.awareness,\n\t\t\t\t[this.document.clientID],\n\t\t\t\t\"page hide\",\n\t\t\t);\n\t\t}\n\t}\n\n\tregisterEventListeners() {\n\t\tif (typeof window === \"undefined\" || !(\"addEventListener\" in window)) {\n\t\t\treturn;\n\t\t}\n\n\t\twindow.addEventListener(\"pagehide\", this.boundPageHide);\n\t}\n\n\tsendStateless(payload: string) {\n\t\tthis.send(StatelessMessage, {\n\t\t\tdocumentName: this.effectiveName,\n\t\t\tpayload,\n\t\t});\n\t}\n\n\tasync sendToken() {\n\t\tlet token: string | null;\n\t\ttry {\n\t\t\ttoken = await this.getToken();\n\t\t} catch (error) {\n\t\t\tthis.permissionDeniedHandler(\n\t\t\t\t`Failed to get token during sendToken(): ${error}`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.send(AuthenticationMessage, {\n\t\t\ttoken: token ?? \"\",\n\t\t\tdocumentName: this.effectiveName,\n\t\t});\n\t}\n\n\tdocumentUpdateHandler(update: Uint8Array, origin: any) {\n\t\tif (origin === this) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.incrementUnsyncedChanges();\n\t\tthis.send(UpdateMessage, { update, documentName: this.effectiveName });\n\t}\n\n\tawarenessUpdateHandler({ added, updated, removed }: any, origin: any) {\n\t\tconst changedClients = added.concat(updated).concat(removed);\n\n\t\tthis.send(AwarenessMessage, {\n\t\t\tawareness: this.awareness,\n\t\t\tclients: changedClients,\n\t\t\tdocumentName: this.effectiveName,\n\t\t});\n\t}\n\n\t/**\n\t * Indicates whether a first handshake with the server has been established\n\t *\n\t * Note: this does not mean all updates from the client have been persisted to the backend. For this,\n\t * use `hasUnsyncedChanges`.\n\t */\n\tget synced(): boolean {\n\t\treturn this.isSynced;\n\t}\n\n\tset synced(state) {\n\t\tif (this.isSynced === state) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.isSynced = state;\n\n\t\tif (state) {\n\t\t\tthis.emit(\"synced\", { state });\n\t\t}\n\t}\n\n\treceiveStateless(payload: string) {\n\t\tthis.emit(\"stateless\", { payload });\n\t}\n\n\t// not needed, but provides backward compatibility with e.g. lexical/yjs\n\tasync connect() {\n\t\tif (this.manageSocket) {\n\t\t\treturn this.configuration.websocketProvider.connect();\n\t\t}\n\n\t\tconsole.warn(\n\t\t\t\"HocuspocusProvider::connect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.\",\n\t\t);\n\t}\n\n\tdisconnect() {\n\t\tif (this.manageSocket) {\n\t\t\treturn this.configuration.websocketProvider.disconnect();\n\t\t}\n\n\t\tconsole.warn(\n\t\t\t\"HocuspocusProvider::disconnect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.\",\n\t\t);\n\t}\n\n\tasync onOpen(event: Event) {\n\t\tthis.isAuthenticated = false;\n\n\t\tthis.emit(\"open\", { event });\n\t\tawait this.sendToken();\n\t\tthis.startSync();\n\t}\n\n\tasync getToken() {\n\t\tif (typeof this.configuration.token === \"function\") {\n\t\t\tconst token = await this.configuration.token();\n\t\t\treturn token;\n\t\t}\n\n\t\treturn this.configuration.token;\n\t}\n\n\tstartSync() {\n\t\tthis.resetUnsyncedChanges();\n\n\t\tthis.send(SyncStepOneMessage, {\n\t\t\tdocument: this.document,\n\t\t\tdocumentName: this.effectiveName,\n\t\t});\n\n\t\tif (this.awareness && this.awareness.getLocalState() !== null) {\n\t\t\tthis.send(AwarenessMessage, {\n\t\t\t\tawareness: this.awareness,\n\t\t\t\tclients: [this.document.clientID],\n\t\t\t\tdocumentName: this.effectiveName,\n\t\t\t});\n\t\t}\n\t}\n\n\tsend(message: ConstructableOutgoingMessage, args: any) {\n\t\tif (!this._isAttached) return;\n\n\t\tconst messageSender = new MessageSender(message, args);\n\n\t\tthis.emit(\"outgoingMessage\", { message: messageSender.message });\n\t\tmessageSender.send(this.configuration.websocketProvider);\n\t}\n\n\tonMessage(event: MessageEvent) {\n\t\tconst message = new IncomingMessage(event.data);\n\n\t\tconst rawKey = message.readVarString();\n\t\t// Extract actual documentName from potentially composite routing key\n\t\tconst { documentName } = parseRoutingKey(rawKey);\n\n\t\tmessage.writeVarString(this.effectiveName);\n\n\t\tthis.emit(\"message\", { event, message: new IncomingMessage(event.data) });\n\n\t\tnew MessageReceiver(message).apply(this, true);\n\t}\n\n\tonClose() {\n\t\tthis.isAuthenticated = false;\n\t\tthis.synced = false;\n\n\t\t// update awareness (all users except local left)\n\t\tif (this.awareness) {\n\t\t\tremoveAwarenessStates(\n\t\t\t\tthis.awareness,\n\t\t\t\tArray.from(this.awareness.getStates().keys()).filter(\n\t\t\t\t\t(client) => client !== this.document.clientID,\n\t\t\t\t),\n\t\t\t\tthis,\n\t\t\t);\n\t\t}\n\t}\n\n\tdestroy() {\n\t\tthis.emit(\"destroy\");\n\n\t\tif (this.intervals.forceSync) {\n\t\t\tclearInterval(this.intervals.forceSync);\n\t\t}\n\n\t\tif (this.awareness) {\n\t\t\tremoveAwarenessStates(\n\t\t\t\tthis.awareness,\n\t\t\t\t[this.document.clientID],\n\t\t\t\t\"provider destroy\",\n\t\t\t);\n\t\t\tthis.awareness.off(\"update\", this.boundAwarenessUpdateHandler);\n\t\t\tthis.awareness.destroy();\n\t\t}\n\n\t\tthis.document.off(\"update\", this.boundDocumentUpdateHandler);\n\n\t\tthis.removeAllListeners();\n\n\t\tthis.detach();\n\n\t\tif (this.manageSocket) {\n\t\t\tthis.configuration.websocketProvider.destroy();\n\t\t}\n\n\t\tif (typeof window === \"undefined\" || !(\"removeEventListener\" in window)) {\n\t\t\treturn;\n\t\t}\n\n\t\twindow.removeEventListener(\"pagehide\", this.boundPageHide);\n\t}\n\n\tdetach() {\n\t\tthis.configuration.websocketProvider.off(\n\t\t\t\"connect\",\n\t\t\tthis.configuration.onConnect,\n\t\t);\n\t\tthis.configuration.websocketProvider.off(\"connect\", this.forwardConnect);\n\n\t\tthis.configuration.websocketProvider.off(\"status\", this.forwardStatus);\n\t\tthis.configuration.websocketProvider.off(\n\t\t\t\"status\",\n\t\t\tthis.configuration.onStatus,\n\t\t);\n\n\t\tthis.configuration.websocketProvider.off(\"open\", this.boundOnOpen);\n\t\tthis.configuration.websocketProvider.off(\"close\", this.boundOnClose);\n\t\tthis.configuration.websocketProvider.off(\n\t\t\t\"close\",\n\t\t\tthis.configuration.onClose,\n\t\t);\n\t\tthis.configuration.websocketProvider.off(\"close\", this.forwardClose);\n\t\tthis.configuration.websocketProvider.off(\n\t\t\t\"disconnect\",\n\t\t\tthis.configuration.onDisconnect,\n\t\t);\n\t\tthis.configuration.websocketProvider.off(\n\t\t\t\"disconnect\",\n\t\t\tthis.forwardDisconnect,\n\t\t);\n\t\tthis.configuration.websocketProvider.off(\n\t\t\t\"destroy\",\n\t\t\tthis.configuration.onDestroy,\n\t\t);\n\t\tthis.configuration.websocketProvider.off(\"destroy\", this.forwardDestroy);\n\n\t\tthis.configuration.websocketProvider.detach(this);\n\n\t\tthis._isAttached = false;\n\t}\n\n\tattach() {\n\t\tif (this._isAttached) return;\n\n\t\tthis.configuration.websocketProvider.on(\n\t\t\t\"connect\",\n\t\t\tthis.configuration.onConnect,\n\t\t);\n\t\tthis.configuration.websocketProvider.on(\"connect\", this.forwardConnect);\n\n\t\tthis.configuration.websocketProvider.on(\n\t\t\t\"status\",\n\t\t\tthis.configuration.onStatus,\n\t\t);\n\t\tthis.configuration.websocketProvider.on(\"status\", this.forwardStatus);\n\n\t\tthis.configuration.websocketProvider.on(\"open\", this.boundOnOpen);\n\n\t\tthis.configuration.websocketProvider.on(\"close\", this.boundOnClose);\n\t\tthis.configuration.websocketProvider.on(\n\t\t\t\"close\",\n\t\t\tthis.configuration.onClose,\n\t\t);\n\t\tthis.configuration.websocketProvider.on(\"close\", this.forwardClose);\n\n\t\tthis.configuration.websocketProvider.on(\n\t\t\t\"disconnect\",\n\t\t\tthis.configuration.onDisconnect,\n\t\t);\n\t\tthis.configuration.websocketProvider.on(\n\t\t\t\"disconnect\",\n\t\t\tthis.forwardDisconnect,\n\t\t);\n\n\t\tthis.configuration.websocketProvider.on(\n\t\t\t\"destroy\",\n\t\t\tthis.configuration.onDestroy,\n\t\t);\n\t\tthis.configuration.websocketProvider.on(\"destroy\", this.forwardDestroy);\n\n\t\tthis.configuration.websocketProvider.attach(this);\n\n\t\tthis._isAttached = true;\n\t}\n\n\tpermissionDeniedHandler(reason: string) {\n\t\tthis.emit(\"authenticationFailed\", { reason });\n\t\tthis.isAuthenticated = false;\n\t}\n\n\tauthenticatedHandler(scope: string) {\n\t\tthis.isAuthenticated = true;\n\t\tthis.authorizedScope = scope as AuthorizedScope;\n\n\t\tthis.emit(\"authenticated\", { scope });\n\t}\n\n\tsetAwarenessField(key: string, value: any) {\n\t\tif (!this.awareness) {\n\t\t\tthrow new AwarenessError(\n\t\t\t\t`Cannot set awareness field \"${key}\" to ${JSON.stringify(value)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`,\n\t\t\t);\n\t\t}\n\t\tthis.awareness.setLocalStateField(key, value);\n\t}\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,22],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAa,QAAQ,KAAK;;;;;;;AAwB1B,MAAa,OAAO,GAAG,MAAM,IAAI,IAAI,IAAI;;;;;;;AAQzC,MAAa,OAAO,GAAG,MAAM,IAAI,IAAI,IAAI;AAEzC,MAAaA,UAAQ,OAAO;;;;ACrB5B,MAAa,OAAO;AACpB,MAAa,OAAO;AAUpB,MAAa,QAAQ,KAAK;AAC1B,MAAa,QAAQ,KAAK;AAC1B,MAAa,QAAQ,KAAK;AAC1B,MAAa,QAAQ,KAAK;AAC1B,MAAa,QAAQ,KAAK;AAC1B,MAAa,QAAQ,KAAK;AAC1B,MAAa,QAAQ,KAAK;AAC1B,MAAa,QAAQ,KAAK;AAC1B,MAAa,QAAQ,KAAK;AAC1B,MAAa,QAAQ,KAAK;AAC1B,MAAa,QAAQ,KAAK;AAC1B,MAAa,QAAQ,KAAK;AAC1B,MAAa,QAAQ,KAAK;AAC1B,MAAa,QAAQ,KAAK;AAC1B,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,cAAc,UACnB;AACD,OAAK,cAAc,kBAAkB,GAAG,WAAW,KAAK,eAAe;AAEvE,OAAK,cAAc,kBAAkB,GACpC,UACA,KAAK,cAAc,SACnB;AACD,OAAK,cAAc,kBAAkB,GAAG,UAAU,KAAK,cAAc;AAErE,OAAK,cAAc,kBAAkB,GAAG,QAAQ,KAAK,YAAY;AAEjE,OAAK,cAAc,kBAAkB,GAAG,SAAS,KAAK,aAAa;AACnE,OAAK,cAAc,kBAAkB,GACpC,SACA,KAAK,cAAc,QACnB;AACD,OAAK,cAAc,kBAAkB,GAAG,SAAS,KAAK,aAAa;AAEnE,OAAK,cAAc,kBAAkB,GACpC,cACA,KAAK,cAAc,aACnB;AACD,OAAK,cAAc,kBAAkB,GACpC,cACA,KAAK,kBACL;AAED,OAAK,cAAc,kBAAkB,GACpC,WACA,KAAK,cAAc,UACnB;AACD,OAAK,cAAc,kBAAkB,GAAG,WAAW,KAAK,eAAe;AAEvE,OAAK,cAAc,kBAAkB,OAAO,KAAK;AAEjD,OAAK,cAAc;;CAGpB,wBAAwB,QAAgB;AACvC,OAAK,KAAK,wBAAwB,EAAE,QAAQ,CAAC;AAC7C,OAAK,kBAAkB;;CAGxB,qBAAqB,OAAe;AACnC,OAAK,kBAAkB;AACvB,OAAK,kBAAkB;AAEvB,OAAK,KAAK,iBAAiB,EAAE,OAAO,CAAC;;CAGtC,kBAAkB,KAAa,OAAY;AAC1C,MAAI,CAAC,KAAK,UACT,OAAM,IAAI,eACT,+BAA+B,IAAI,OAAO,KAAK,UAAU,MAAM,CAAC,sHAChE;AAEF,OAAK,UAAU,mBAAmB,KAAK,MAAM"}
1
+ {"version":3,"file":"hocuspocus-provider.cjs","names":["isNaN","binary.BITS31","binary.BITS32","math.floor","create","isArray","binary.BITS7","binary.BIT8","math.floor","string.encodeUtf8","string.utf8TextEncoder","math.min","math.max","create","error.create","binary.BITS7","binary.BIT8","number.MAX_SAFE_INTEGER","binary.BITS6","binary.BIT7","string.utf8TextDecoder","map.create","set.create","array.from","equalityTrait.EqualityTraitSymbol","object.size","object.hasProperty","array.isArray","time.getUnixTime","math.floor","f.equalityDeep","encoding.createEncoder","encoding.toUint8Array","decoding.createDecoder","decoding.readVarUint","decoding.readVarString","time.getUnixTime","encoding.createEncoder","encoding.toUint8Array","WsReadyStates","Y","decoding.readVarUint8Array","decoding.readVarUint","awarenessProtocol.encodeAwarenessUpdate","Y"],"sources":["../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/math.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/binary.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/number.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/set.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/array.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/string.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/encoding.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/error.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/decoding.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/time.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/map.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/observable.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/trait/equality.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/object.js","../../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/function.js","../../../node_modules/.pnpm/y-protocols@1.0.7_yjs@13.6.29/node_modules/y-protocols/awareness.js","../src/EventEmitter.ts","../src/IncomingMessage.ts","../src/types.ts","../src/OutgoingMessage.ts","../src/OutgoingMessages/CloseMessage.ts","../src/HocuspocusProviderWebsocket.ts","../../../node_modules/.pnpm/y-protocols@1.0.7_yjs@13.6.29/node_modules/y-protocols/sync.js","../src/MessageReceiver.ts","../src/MessageSender.ts","../src/version.ts","../src/OutgoingMessages/AuthenticationMessage.ts","../src/OutgoingMessages/AwarenessMessage.ts","../src/OutgoingMessages/StatelessMessage.ts","../src/OutgoingMessages/SyncStepOneMessage.ts","../src/OutgoingMessages/UpdateMessage.ts","../src/HocuspocusProvider.ts"],"sourcesContent":["/**\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 * Check whether n is negative, while considering the -0 edge case. While `-0 < 0` is false, this\n * function returns true for -0,-1,,.. and returns false for 0,1,2,...\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also distinguishes 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/**\n * Count the number of \"1\" bits in an unsigned 32bit number.\n *\n * Super fun bitcount algorithm by Brian Kernighan.\n *\n * @param {number} n\n */\nexport const countBits = n => {\n n &= binary.BITS32\n let count = 0\n while (n) {\n n &= (n - 1)\n count++\n }\n return count\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<T>} set\n * @return {Array<T>}\n */\nexport const toArray = set => Array.from(set)\n\n/**\n * @template T\n * @param {Set<T>} set\n * @return {T|undefined}\n */\nexport const first = set => set.values().next().value\n\n/**\n * @template T\n * @param {Iterable<T>} entries\n * @return {Set<T>}\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<L>} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array<C>}\n */\nexport const create = () => /** @type {Array<C>} */ ([])\n\n/**\n * @template D\n * @param {Array<D>} a\n * @return {Array<D>}\n */\nexport const copy = a => /** @type {Array<D>} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array<M>} dest\n * @param {Array<M>} 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<T>|Iterable<T>} 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 {ArrayLike<any>} ARR\n *\n * @param {ARR} arr\n * @param {ARR extends ArrayLike<infer S> ? ((value:S, index:number, arr:ARR) => boolean) : any} 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 {ArrayLike<any>} ARR\n *\n * @param {ARR} arr\n * @param {ARR extends ArrayLike<infer S> ? ((value:S, index:number, arr:ARR) => boolean) : never} 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<ELEM>} a\n * @param {ArrayLike<ELEM>} 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<Array<ELEM>>} arr\n * @return {Array<ELEM>}\n */\nexport const flatten = arr => fold(arr, /** @type {Array<ELEM>} */ ([]), (acc, val) => acc.concat(val))\n\n/**\n * @template T\n * @param {number} len\n * @param {function(number, Array<T>):T} f\n * @return {Array<T>}\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<T>} 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<T>} arr\n * @return {Array<T>}\n */\nexport const unique = arr => from(set.from(arr))\n\n/**\n * @template T\n * @template M\n * @param {ArrayLike<T>} arr\n * @param {function(T):M} mapper\n * @return {Array<T>}\n */\nexport const uniqueBy = (arr, mapper) => {\n /**\n * @type {Set<M>}\n */\n const happened = set.create()\n /**\n * @type {Array<T>}\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/**\n * @template {ArrayLike<any>} ARR\n * @template {function(ARR extends ArrayLike<infer T> ? T : never, number, ARR):any} MAPPER\n * @param {ARR} arr\n * @param {MAPPER} mapper\n * @return {Array<MAPPER extends function(...any): infer M ? M : never>}\n */\nexport const map = (arr, mapper) => {\n /**\n * @type {Array<any>}\n */\n const res = Array(arr.length)\n for (let i = 0; i < arr.length; i++) {\n res[i] = mapper(/** @type {any} */ (arr[i]), i, /** @type {any} */ (arr))\n }\n return /** @type {any} */ (res)\n}\n\n/**\n * This function bubble-sorts a single item to the correct position. The sort happens in-place and\n * might be useful to ensure that a single item is at the correct position in an otherwise sorted\n * array.\n *\n * @example\n * const arr = [3, 2, 5]\n * arr.sort((a, b) => a - b)\n * arr // => [2, 3, 5]\n * arr.splice(1, 0, 7)\n * array.bubbleSortItem(arr, 1, (a, b) => a - b)\n * arr // => [2, 3, 5, 7]\n *\n * @template T\n * @param {Array<T>} arr\n * @param {number} i\n * @param {(a:T,b:T) => number} compareFn\n */\nexport const bubblesortItem = (arr, i, compareFn) => {\n const n = arr[i]\n let j = i\n // try to sort to the right\n while (j + 1 < arr.length && compareFn(n, arr[j + 1]) > 0) {\n arr[j] = arr[j + 1]\n arr[++j] = n\n }\n if (i === j && j > 0) { // no change yet\n // sort to the left\n while (j > 0 && compareFn(arr[j - 1], n) > 0) {\n arr[j] = arr[j - 1]\n arr[--j] = n\n }\n }\n return j\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<ArrayBuffer>}\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<ArrayBuffer>}\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/**\n * Escape HTML characters &,<,>,',\" to their respective HTML entities &amp;,&lt;,&gt;,&#39;,&quot;\n *\n * @param {string} str\n */\nexport const escapeHTML = str =>\n str.replace(/[&<>'\"]/g, r => /** @type {string} */ ({\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n \"'\": '&#39;',\n '\"': '&quot;'\n }[r]))\n\n/**\n * Reverse of `escapeHTML`\n *\n * @param {string} str\n */\nexport const unescapeHTML = str =>\n str.replace(/&amp;|&lt;|&gt;|&#39;|&quot;/g, r => /** @type {string} */ ({\n '&amp;': '&',\n '&lt;': '<',\n '&gt;': '>',\n '&#39;': \"'\",\n '&quot;': '\"'\n }[r]))\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 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<Uint8Array>}\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<ArrayBuffer>} 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(new Uint8Array(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(new Uint8Array(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 * @typedef {Array<AnyEncodable>} AnyEncodableArray\n */\n\n/**\n * @typedef {undefined|null|number|bigint|boolean|string|{[k:string]:AnyEncodable}|AnyEncodableArray|Uint8Array} AnyEncodable\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<string,any> | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array<any> | 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 {AnyEncodable} 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 /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\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 /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\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 /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\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<string>}\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/**\n * @param {boolean} property\n * @return {asserts property is true}\n */\nexport const assert = property => { if (!property) throw create('Assert failed') }\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 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 * @template {ArrayBufferLike} [Buf=ArrayBufferLike]\n */\nexport class Decoder {\n /**\n * @param {Uint8Array<Buf>} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array<Buf>}\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 * @template {ArrayBufferLike} Buf\n * @param {Uint8Array<Buf>} uint8Array\n * @return {Decoder<Buf>}\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 * @template {ArrayBufferLike} Buf\n * @param {Decoder<Buf>} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array<Buf>}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = new Uint8Array(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 * @template {ArrayBufferLike} Buf\n * @param {Decoder<Buf>} decoder\n * @return {Uint8Array<Buf>}\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<function(Decoder):any>}\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<string,any>\n const len = readVarUint(decoder)\n /**\n * @type {Object<string,any>}\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<any>\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 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 * Utility module to work with key-value stores.\n *\n * @module map\n */\n\n/**\n * @template K\n * @template V\n * @typedef {Map<K,V>} GlobalMap\n */\n\n/**\n * Creates a new Map instance.\n *\n * @function\n * @return {Map<any, any>}\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 K,V\n * @param {Map<K,V>} m\n * @return {Map<K,V>}\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 {Map<any, any>} MAP\n * @template {MAP extends Map<any,infer V> ? function():V : unknown} CF\n * @param {MAP} map\n * @param {MAP extends Map<infer K,any> ? K : unknown} key\n * @param {CF} createT\n * @return {ReturnType<CF>}\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<K,V>} m\n * @param {function(V,K):R} f\n * @return {Array<R>}\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<K,V>} 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<K,V>} 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 * 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 * @experimental\n *\n * This is basically a (better typed) duplicate of Observable, which will replace Observable in the\n * next release.\n *\n * @template {{[key in keyof EVENTS]: function(...any):void}} EVENTS\n */\nexport class ObservableV2 {\n constructor () {\n /**\n * Some desc.\n * @type {Map<string, Set<any>>}\n */\n this._observers = map.create()\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, /** @type {string} */ (name), set.create).add(f)\n return f\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, /** @type {any} */ (_f))\n f(...args)\n }\n this.on(name, /** @type {any} */ (_f))\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} 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 * @template {keyof EVENTS & string} NAME\n * @param {NAME} name The event name.\n * @param {Parameters<EVENTS[NAME]>} 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/* c8 ignore start */\n/**\n * Handles named events.\n *\n * @deprecated\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map<N, any>}\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<any>} 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/* c8 ignore end */\n","export const EqualityTraitSymbol = Symbol('Equality')\n\n/**\n * @typedef {{ [EqualityTraitSymbol]:(other:EqualityTrait)=>boolean }} EqualityTrait\n */\n\n/**\n *\n * Utility function to compare any two objects.\n *\n * Note that it is expected that the first parameter is more specific than the latter one.\n *\n * @example js\n * class X { [traits.EqualityTraitSymbol] (other) { return other === this } }\n * class X2 { [traits.EqualityTraitSymbol] (other) { return other === this }, x2 () { return 2 } }\n * // this is fine\n * traits.equals(new X2(), new X())\n * // this is not, because the left type is less specific than the right one\n * traits.equals(new X(), new X2())\n *\n * @template {EqualityTrait} T\n * @param {NoInfer<T>} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equals = (a, b) => a === b || !!a?.[EqualityTraitSymbol]?.(b) || false\n","import * as equalityTrait from './trait/equality.js'\n\n/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object<string,any>} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * @param {any} o\n * @return {o is { [k:string]:any }}\n */\nexport const isObject = o => typeof o === 'object'\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object<string,any>} obj\n */\nexport const keys = Object.keys\n\n/**\n * @template V\n * @param {{[key:string]: V}} obj\n * @return {Array<V>}\n */\nexport const values = Object.values\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<string,any>} obj\n * @param {function(any,string):R} f\n * @return {Array<R>}\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 * @deprecated use object.size instead\n * @param {Object<string,any>} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object<string,any>} obj\n * @return {number}\n */\nexport const size = obj => keys(obj).length\n\n/**\n * @template {{ [key:string|number|symbol]: any }} T\n * @param {T} obj\n * @param {(v:T[keyof T],k:keyof T)=>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|null|undefined} obj\n */\nexport const isEmpty = obj => {\n // eslint-disable-next-line no-unreachable-loop\n for (const _k in obj) {\n return false\n }\n return true\n}\n\n/**\n * @template {{ [key:string|number|symbol]: any }} T\n * @param {T} obj\n * @param {(v:T[keyof T],k:keyof T)=>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|number|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object<string,any>} a\n * @param {Object<string,any>} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (size(a) === size(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && equalityTrait.equals(b[key], val)))\n\n/**\n * Make an object immutable. This hurts performance and is usually not needed if you perform good\n * coding practices.\n */\nexport const freeze = Object.freeze\n\n/**\n * Make an object and all its children immutable.\n * This *really* hurts performance and is usually not needed if you perform good coding practices.\n *\n * @template {any} T\n * @param {T} o\n * @return {Readonly<T>}\n */\nexport const deepFreeze = (o) => {\n for (const key in o) {\n const c = o[key]\n if (typeof c === 'object' || typeof c === 'function') {\n deepFreeze(o[key])\n }\n }\n return freeze(o)\n}\n\n/**\n * Get object property. Create T if property is undefined and set T on object.\n *\n * @function\n * @template {object} KV\n * @template {keyof KV} [K=keyof KV]\n * @param {KV} o\n * @param {K} key\n * @param {() => KV[K]} createT\n * @return {KV[K]}\n */\nexport const setIfUndefined = (o, key, createT) => hasProperty(o, key) ? o[key] : (o[key] = createT())\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'\nimport * as equalityTrait from './trait/equality.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array<function>} fs\n * @param {Array<any>} 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<T>|object} a\n * @param {Array<T>|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<T>} */ (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 === b) {\n return true\n }\n if (a == null || b == null || (a.constructor !== b.constructor && (a.constructor || Object) !== (b.constructor || Object))) {\n return false\n }\n if (a[equalityTrait.EqualityTraitSymbol] != null) {\n return a[equalityTrait.EqualityTraitSymbol](b)\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 undefined:\n case Object:\n if (object.size(a) !== object.size(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<OPTS>} 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<TYPE>}\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<TYPE>}\n **/\n n => n && n.constructor === T\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<string>}\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<number, Object<string, any>>}\n */\n this.states = new Map()\n /**\n * @type {Map<number, MetaClientState>}\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<number>}\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<string,any>|null}\n */\n getLocalState () {\n return this.states.get(this.clientID) || null\n }\n\n /**\n * @param {Object<string,any>|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<number,Object<string,any>>}\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<number>} 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<number>} 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\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic callbacks: { [key: string]: Function[] } = {};\n\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic on(event: string, fn: Function): this {\n\t\tif (!this.callbacks[event]) {\n\t\t\tthis.callbacks[event] = [];\n\t\t}\n\n\t\tthis.callbacks[event].push(fn);\n\n\t\treturn this;\n\t}\n\n\tprotected emit(event: string, ...args: any): this {\n\t\tconst callbacks = this.callbacks[event];\n\n\t\tif (callbacks) {\n\t\t\tcallbacks.forEach((callback) => callback.apply(this, args));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic off(event: string, fn?: Function): this {\n\t\tconst callbacks = this.callbacks[event];\n\n\t\tif (callbacks) {\n\t\t\tif (fn) {\n\t\t\t\tthis.callbacks[event] = callbacks.filter((callback) => callback !== fn);\n\t\t\t} else {\n\t\t\t\tdelete this.callbacks[event];\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tremoveAllListeners(): void {\n\t\tthis.callbacks = {};\n\t}\n}\n","import type { Decoder } from \"lib0/decoding\";\nimport {\n\tcreateDecoder,\n\tpeekVarString,\n\treadVarUint,\n\treadVarUint8Array,\n\treadVarString,\n} from \"lib0/decoding\";\nimport type { Encoder } from \"lib0/encoding\";\nimport {\n\tcreateEncoder,\n\twriteVarUint,\n\twriteVarUint8Array,\n\twriteVarString,\n\tlength,\n} from \"lib0/encoding\";\nimport type { MessageType } from \"./types.ts\";\n\nexport class IncomingMessage {\n\tdata: any;\n\n\tencoder: Encoder;\n\n\tdecoder: Decoder;\n\n\tconstructor(data: any) {\n\t\tthis.data = data;\n\t\tthis.encoder = createEncoder();\n\t\tthis.decoder = createDecoder(new Uint8Array(this.data));\n\t}\n\n\tpeekVarString(): string {\n\t\treturn peekVarString(this.decoder);\n\t}\n\n\treadVarUint(): MessageType {\n\t\treturn readVarUint(this.decoder);\n\t}\n\n\treadVarString(): string {\n\t\treturn readVarString(this.decoder);\n\t}\n\n\treadVarUint8Array() {\n\t\treturn readVarUint8Array(this.decoder);\n\t}\n\n\twriteVarUint(type: MessageType) {\n\t\treturn writeVarUint(this.encoder, type);\n\t}\n\n\twriteVarString(string: string) {\n\t\treturn writeVarString(this.encoder, string);\n\t}\n\n\twriteVarUint8Array(data: Uint8Array) {\n\t\treturn writeVarUint8Array(this.encoder, data);\n\t}\n\n\tlength() {\n\t\treturn length(this.encoder);\n\t}\n}\n","import type { Encoder } from \"lib0/encoding\";\nimport type { Awareness } from \"y-protocols/awareness\";\nimport type * as Y from \"yjs\";\nimport type { CloseEvent } from \"@hocuspocus/common\";\nimport type { IncomingMessage } from \"./IncomingMessage.ts\";\nimport type { OutgoingMessage } from \"./OutgoingMessage.ts\";\nimport type { AuthenticationMessage } from \"./OutgoingMessages/AuthenticationMessage.ts\";\nimport type { AwarenessMessage } from \"./OutgoingMessages/AwarenessMessage.ts\";\nimport type { QueryAwarenessMessage } from \"./OutgoingMessages/QueryAwarenessMessage.ts\";\nimport type { SyncStepOneMessage } from \"./OutgoingMessages/SyncStepOneMessage.ts\";\nimport type { SyncStepTwoMessage } from \"./OutgoingMessages/SyncStepTwoMessage.ts\";\nimport type { UpdateMessage } from \"./OutgoingMessages/UpdateMessage.ts\";\n\nexport enum MessageType {\n\tSync = 0,\n\tAwareness = 1,\n\tAuth = 2,\n\tQueryAwareness = 3,\n\tStateless = 5,\n\tCLOSE = 7,\n\tSyncStatus = 8,\n\tPing = 9,\n\tPong = 10,\n}\n\nexport enum WebSocketStatus {\n\tConnecting = \"connecting\",\n\tConnected = \"connected\",\n\tDisconnected = \"disconnected\",\n}\n\nexport type AuthorizedScope = \"read-write\" | \"readonly\";\n\nexport interface OutgoingMessageInterface {\n\tencoder: Encoder;\n\ttype?: MessageType;\n}\n\nexport interface OutgoingMessageArguments {\n\tdocumentName: string;\n\ttoken: string;\n\tdocument: Y.Doc;\n\tawareness: Awareness;\n\tclients: number[];\n\tstates: Map<number, { [key: string]: any }>;\n\tupdate: any;\n\tpayload: string;\n\tencoder: Encoder;\n}\n\nexport interface Constructable<T> {\n\tnew (...args: any): T;\n}\n\nexport type ConstructableOutgoingMessage =\n\t| Constructable<AuthenticationMessage>\n\t| Constructable<AwarenessMessage>\n\t| Constructable<QueryAwarenessMessage>\n\t| Constructable<SyncStepOneMessage>\n\t| Constructable<SyncStepTwoMessage>\n\t| Constructable<UpdateMessage>;\n\nexport type onAuthenticationFailedParameters = {\n\treason: string;\n};\n\nexport type onAuthenticatedParameters = {\n\tscope: AuthorizedScope;\n};\n\nexport type onOpenParameters = {\n\tevent: Event;\n};\n\nexport type onMessageParameters = {\n\tevent: MessageEvent;\n\tmessage: IncomingMessage;\n};\n\nexport type onOutgoingMessageParameters = {\n\tmessage: OutgoingMessage;\n};\n\nexport type onStatusParameters = {\n\tstatus: WebSocketStatus;\n};\n\nexport type onSyncedParameters = {\n\tstate: boolean;\n};\n\nexport type onUnsyncedChangesParameters = {\n\tnumber: number;\n};\n\nexport type onDisconnectParameters = {\n\tevent: CloseEvent;\n};\n\nexport type onCloseParameters = {\n\tevent: CloseEvent;\n};\n\nexport type onAwarenessUpdateParameters = {\n\tstates: StatesArray;\n};\n\nexport type onAwarenessChangeParameters = {\n\tstates: StatesArray;\n};\n\nexport type onStatelessParameters = {\n\tpayload: string;\n};\n\nexport type StatesArray = { clientId: number; [key: string | number]: any }[];\n","import type { Encoder } from \"lib0/encoding\";\nimport { createEncoder, toUint8Array } from \"lib0/encoding\";\nimport type {\n\tMessageType,\n\tOutgoingMessageArguments,\n\tOutgoingMessageInterface,\n} from \"./types.ts\";\n\nexport class OutgoingMessage implements OutgoingMessageInterface {\n\tencoder: Encoder;\n\n\ttype?: MessageType;\n\n\tconstructor() {\n\t\tthis.encoder = createEncoder();\n\t}\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\treturn args.encoder;\n\t}\n\n\ttoUint8Array() {\n\t\treturn toUint8Array(this.encoder);\n\t}\n}\n","import * as encoding from \"lib0/encoding\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class CloseMessage extends OutgoingMessage {\n\ttype = MessageType.CLOSE;\n\n\tdescription = \"Ask the server to close the connection\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tencoding.writeVarString(this.encoder, args.documentName!);\n\t\tencoding.writeVarUint(this.encoder, this.type);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { WsReadyStates } from \"@hocuspocus/common\";\nimport { retry } from \"@lifeomic/attempt\";\nimport { createDecoder, readVarString, readVarUint } from \"lib0/decoding\";\nimport * as encoding from \"lib0/encoding\";\nimport * as time from \"lib0/time\";\nimport EventEmitter from \"./EventEmitter.ts\";\nimport type { HocuspocusProvider } from \"./HocuspocusProvider.ts\";\nimport { IncomingMessage } from \"./IncomingMessage.ts\";\nimport { CloseMessage } from \"./OutgoingMessages/CloseMessage.ts\";\nimport {\n\tMessageType,\n\ttype onAwarenessChangeParameters,\n\ttype onAwarenessUpdateParameters,\n\ttype onCloseParameters,\n\ttype onDisconnectParameters,\n\ttype onMessageParameters,\n\ttype onOpenParameters,\n\ttype onOutgoingMessageParameters,\n\ttype onStatusParameters,\n\tWebSocketStatus,\n} from \"./types.ts\";\n\nexport type HocuspocusWebSocket = WebSocket & { identifier: string };\nexport type HocusPocusWebSocket = HocuspocusWebSocket;\n\nexport type HocuspocusProviderWebsocketConfiguration = Required<\n\tPick<CompleteHocuspocusProviderWebsocketConfiguration, \"url\">\n> &\n\tPartial<CompleteHocuspocusProviderWebsocketConfiguration>;\n\nexport interface CompleteHocuspocusProviderWebsocketConfiguration {\n\t/**\n\t * Whether to connect automatically when creating the provider instance. Default=true\n\t */\n\tautoConnect: boolean;\n\n\t/**\n\t * URL of your @hocuspocus/server instance\n\t */\n\turl: string;\n\n\t/**\n\t * By default, trailing slashes are removed from the URL. Set this to true\n\t * to preserve trailing slashes if your server configuration requires them.\n\t */\n\tpreserveTrailingSlash: boolean;\n\n\t/**\n\t * An optional WebSocket polyfill, for example for Node.js\n\t */\n\tWebSocketPolyfill: any;\n\n\t/**\n\t * Disconnect when no message is received for the defined amount of milliseconds.\n\t */\n\tmessageReconnectTimeout: number;\n\t/**\n\t * The delay between each attempt in milliseconds. You can provide a factor to have the delay grow exponentially.\n\t */\n\tdelay: number;\n\t/**\n\t * The initialDelay 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\t */\n\tinitialDelay: number;\n\t/**\n\t * The factor option is used to grow the delay exponentially.\n\t */\n\tfactor: number;\n\t/**\n\t * The maximum number of attempts or 0 if there is no limit on number of attempts.\n\t */\n\tmaxAttempts: number;\n\t/**\n\t * minDelay is used to set a lower bound of delay when jitter is enabled. This property has no effect if jitter is disabled.\n\t */\n\tminDelay: number;\n\t/**\n\t * 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\t */\n\tmaxDelay: number;\n\t/**\n\t * 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\t */\n\tjitter: boolean;\n\t/**\n\t * 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\t */\n\ttimeout: number;\n\thandleTimeout: (() => Promise<unknown>) | null;\n\tonOpen: (data: onOpenParameters) => void;\n\tonConnect: () => void;\n\tonMessage: (data: onMessageParameters) => void;\n\tonOutgoingMessage: (data: onOutgoingMessageParameters) => void;\n\tonStatus: (data: onStatusParameters) => void;\n\tonDisconnect: (data: onDisconnectParameters) => void;\n\tonClose: (data: onCloseParameters) => void;\n\tonDestroy: () => void;\n\tonAwarenessUpdate: (data: onAwarenessUpdateParameters) => void;\n\tonAwarenessChange: (data: onAwarenessChangeParameters) => void;\n\n\t/**\n\t * Map of attached providers keyed by documentName.\n\t */\n\tproviderMap: Map<string, HocuspocusProvider>;\n}\n\nexport class HocuspocusProviderWebsocket extends EventEmitter {\n\tprivate static readonly DEDUPLICATABLE_TYPES = new Set([\n\t\tMessageType.Awareness,\n\t\tMessageType.QueryAwareness,\n\t]);\n\n\tprivate messageQueue: any[] = [];\n\n\tpublic configuration: CompleteHocuspocusProviderWebsocketConfiguration = {\n\t\turl: \"\",\n\t\tautoConnect: true,\n\t\tpreserveTrailingSlash: false,\n\t\t// @ts-expect-error\n\t\tdocument: undefined,\n\t\tWebSocketPolyfill: undefined,\n\t\t// TODO: this should depend on awareness.outdatedTime\n\t\tmessageReconnectTimeout: 30000,\n\t\t// 1 second\n\t\tdelay: 1000,\n\t\t// instant\n\t\tinitialDelay: 0,\n\t\t// double the delay each time\n\t\tfactor: 2,\n\t\t// unlimited retries\n\t\tmaxAttempts: 0,\n\t\t// wait at least 1 second\n\t\tminDelay: 1000,\n\t\t// at least every 30 seconds\n\t\tmaxDelay: 30000,\n\t\t// randomize\n\t\tjitter: true,\n\t\t// retry forever\n\t\ttimeout: 0,\n\t\tonOpen: () => null,\n\t\tonConnect: () => null,\n\t\tonMessage: () => null,\n\t\tonOutgoingMessage: () => null,\n\t\tonStatus: () => null,\n\t\tonDisconnect: () => null,\n\t\tonClose: () => null,\n\t\tonDestroy: () => null,\n\t\tonAwarenessUpdate: () => null,\n\t\tonAwarenessChange: () => null,\n\t\thandleTimeout: null,\n\t\tproviderMap: new Map(),\n\t};\n\n\twebSocket: HocusPocusWebSocket | null = null;\n\n\twebSocketHandlers: { [key: string]: any } = {};\n\n\tshouldConnect = true;\n\n\tstatus = WebSocketStatus.Disconnected;\n\n\tlastMessageReceived = 0;\n\n\tidentifier = 0;\n\n\tintervals: any = {\n\t\tconnectionChecker: null,\n\t};\n\n\tconnectionAttempt: {\n\t\tresolve: (value?: any) => void;\n\t\treject: (reason?: any) => void;\n\t} | null = null;\n\n\tconstructor(configuration: HocuspocusProviderWebsocketConfiguration) {\n\t\tsuper();\n\t\tthis.setConfiguration(configuration);\n\n\t\tthis.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill\n\t\t\t? configuration.WebSocketPolyfill\n\t\t\t: WebSocket;\n\n\t\tthis.on(\"open\", this.configuration.onOpen);\n\t\tthis.on(\"open\", this.onOpen.bind(this));\n\t\tthis.on(\"connect\", this.configuration.onConnect);\n\t\tthis.on(\"message\", this.configuration.onMessage);\n\t\tthis.on(\"outgoingMessage\", this.configuration.onOutgoingMessage);\n\t\tthis.on(\"status\", this.configuration.onStatus);\n\t\tthis.on(\"disconnect\", this.configuration.onDisconnect);\n\t\tthis.on(\"close\", this.configuration.onClose);\n\t\tthis.on(\"destroy\", this.configuration.onDestroy);\n\t\tthis.on(\"awarenessUpdate\", this.configuration.onAwarenessUpdate);\n\t\tthis.on(\"awarenessChange\", this.configuration.onAwarenessChange);\n\n\t\tthis.on(\"close\", this.onClose.bind(this));\n\t\tthis.on(\"message\", this.onMessage.bind(this));\n\n\t\tthis.intervals.connectionChecker = setInterval(\n\t\t\tthis.checkConnection.bind(this),\n\t\t\tthis.configuration.messageReconnectTimeout / 10,\n\t\t);\n\n\t\tif (this.shouldConnect) {\n\t\t\tthis.connect();\n\t\t}\n\t}\n\n\treceivedOnOpenPayload?: Event | undefined = undefined;\n\n\tasync onOpen(event: Event) {\n\t\tthis.status = WebSocketStatus.Connected;\n\t\tthis.emit(\"status\", { status: WebSocketStatus.Connected });\n\n\t\tthis.cancelWebsocketRetry = undefined;\n\t\tthis.receivedOnOpenPayload = event;\n\t}\n\n\tattach(provider: HocuspocusProvider) {\n\t\tconst key = provider.effectiveName;\n\t\tconst existing = this.configuration.providerMap.get(key);\n\n\t\tif (existing && existing !== provider) {\n\t\t\t// Allow replacing a provider that hasn't authenticated (e.g., after auth failure retry)\n\t\t\tif (existing.isAuthenticated) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Cannot attach two providers with the same effective name \"${key}\". ` +\n\t\t\t\t\t\t\"Use sessionAwareness: true to multiplex providers with the same document name.\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tthis.configuration.providerMap.set(key, provider);\n\n\t\tif (this.status === WebSocketStatus.Disconnected && this.shouldConnect) {\n\t\t\tthis.connect();\n\t\t}\n\n\t\tif (\n\t\t\tthis.receivedOnOpenPayload &&\n\t\t\tthis.status === WebSocketStatus.Connected\n\t\t) {\n\t\t\tprovider.onOpen(this.receivedOnOpenPayload);\n\t\t}\n\t}\n\n\tdetach(provider: HocuspocusProvider) {\n\t\tconst key = provider.effectiveName;\n\t\tif (this.configuration.providerMap.has(key)) {\n\t\t\tprovider.send(CloseMessage, {\n\t\t\t\tdocumentName: key,\n\t\t\t});\n\t\t\tthis.configuration.providerMap.delete(key);\n\t\t}\n\t}\n\n\tpublic setConfiguration(\n\t\tconfiguration: Partial<HocuspocusProviderWebsocketConfiguration> = {},\n\t): void {\n\t\tthis.configuration = { ...this.configuration, ...configuration };\n\n\t\tif (!this.configuration.autoConnect) {\n\t\t\tthis.shouldConnect = false;\n\t\t}\n\t}\n\n\tcancelWebsocketRetry?: () => void;\n\n\tasync connect() {\n\t\tif (this.status === WebSocketStatus.Connected) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Always cancel any previously initiated connection retryer instances\n\t\tif (this.cancelWebsocketRetry) {\n\t\t\tthis.cancelWebsocketRetry();\n\t\t\tthis.cancelWebsocketRetry = undefined;\n\t\t}\n\n\t\tthis.receivedOnOpenPayload = undefined;\n\t\tthis.shouldConnect = true;\n\n\t\tconst abortableRetry = () => {\n\t\t\tlet cancelAttempt = false;\n\n\t\t\tconst retryPromise = retry(this.createWebSocketConnection.bind(this), {\n\t\t\t\tdelay: this.configuration.delay,\n\t\t\t\tinitialDelay: this.configuration.initialDelay,\n\t\t\t\tfactor: this.configuration.factor,\n\t\t\t\tmaxAttempts: this.configuration.maxAttempts,\n\t\t\t\tminDelay: this.configuration.minDelay,\n\t\t\t\tmaxDelay: this.configuration.maxDelay,\n\t\t\t\tjitter: this.configuration.jitter,\n\t\t\t\ttimeout: this.configuration.timeout,\n\t\t\t\thandleTimeout: this.configuration.handleTimeout,\n\t\t\t\tbeforeAttempt: (context) => {\n\t\t\t\t\tif (!this.shouldConnect || cancelAttempt) {\n\t\t\t\t\t\tcontext.abort();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}).catch((error: any) => {\n\t\t\t\t// If we aborted the connection attempt then don’t throw an error\n\t\t\t\t// ref: https://github.com/lifeomic/attempt/blob/master/src/index.ts#L136\n\t\t\t\tif (error && error.code !== \"ATTEMPT_ABORTED\") {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\tretryPromise,\n\t\t\t\tcancelFunc: () => {\n\t\t\t\t\tcancelAttempt = true;\n\t\t\t\t},\n\t\t\t};\n\t\t};\n\n\t\tconst { retryPromise, cancelFunc } = abortableRetry();\n\t\tthis.cancelWebsocketRetry = cancelFunc;\n\n\t\treturn retryPromise;\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tattachWebSocketListeners(ws: HocusPocusWebSocket, reject: Function) {\n\t\tconst { identifier } = ws;\n\t\tconst onMessageHandler = (payload: any) => this.emit(\"message\", payload);\n\t\tconst onCloseHandler = (payload: any) =>\n\t\t\tthis.emit(\"close\", { event: payload });\n\t\tconst onOpenHandler = (payload: any) => this.emit(\"open\", payload);\n\t\tconst onErrorHandler = (err: any) => {\n\t\t\treject(err);\n\t\t};\n\n\t\tthis.webSocketHandlers[identifier] = {\n\t\t\tmessage: onMessageHandler,\n\t\t\tclose: onCloseHandler,\n\t\t\topen: onOpenHandler,\n\t\t\terror: onErrorHandler,\n\t\t};\n\n\t\tconst handlers = this.webSocketHandlers[ws.identifier];\n\n\t\tObject.keys(handlers).forEach((name) => {\n\t\t\tws.addEventListener(name, handlers[name]);\n\t\t});\n\t}\n\n\tcleanupWebSocket() {\n\t\tif (!this.webSocket) {\n\t\t\treturn;\n\t\t}\n\t\tconst { identifier } = this.webSocket;\n\t\tconst handlers = this.webSocketHandlers[identifier];\n\n\t\tObject.keys(handlers).forEach((name) => {\n\t\t\tthis.webSocket?.removeEventListener(name, handlers[name]);\n\t\t\tdelete this.webSocketHandlers[identifier];\n\t\t});\n\t\tthis.webSocket.close();\n\t\tthis.webSocket = null;\n\t}\n\n\tcreateWebSocketConnection() {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (this.webSocket) {\n\t\t\t\tthis.messageQueue = [];\n\t\t\t\tthis.cleanupWebSocket();\n\t\t\t}\n\t\t\tthis.lastMessageReceived = 0;\n\t\t\tthis.identifier += 1;\n\n\t\t\t// Init the WebSocket connection\n\t\t\tconst ws = new this.configuration.WebSocketPolyfill(this.url);\n\t\t\tws.binaryType = \"arraybuffer\";\n\t\t\tws.identifier = this.identifier;\n\n\t\t\tthis.attachWebSocketListeners(ws, reject);\n\n\t\t\tthis.webSocket = ws;\n\n\t\t\t// Reset the status\n\t\t\tthis.status = WebSocketStatus.Connecting;\n\t\t\tthis.emit(\"status\", { status: WebSocketStatus.Connecting });\n\n\t\t\t// Store resolve/reject for later use\n\t\t\tthis.connectionAttempt = {\n\t\t\t\tresolve,\n\t\t\t\treject,\n\t\t\t};\n\t\t});\n\t}\n\n\tonMessage(event: MessageEvent) {\n\t\tthis.resolveConnectionAttempt();\n\n\t\tthis.lastMessageReceived = time.getUnixTime();\n\n\t\tconst data = new Uint8Array(event.data as ArrayBuffer);\n\n\t\t// Check for connection-level Ping message (no document name prefix)\n\t\t// Ping messages are sent as just the message type byte (length 1)\n\t\t// We check length to avoid confusing with regular messages that happen to have\n\t\t// a document name length of 9 as the first byte\n\t\tif (data.length === 1 && data[0] === MessageType.Ping) {\n\t\t\tthis.sendPong();\n\t\t\treturn;\n\t\t}\n\n\t\tconst message = new IncomingMessage(data);\n\t\tconst rawKey = message.peekVarString();\n\n\t\tconst provider = this.configuration.providerMap.get(rawKey);\n\t\tprovider?.onMessage(event);\n\t}\n\n\t/**\n\t * Send application-level Pong response to server Ping\n\t */\n\tprivate sendPong() {\n\t\tconst encoder = encoding.createEncoder();\n\t\tencoding.writeVarUint(encoder, MessageType.Pong);\n\t\tthis.send(encoding.toUint8Array(encoder));\n\t}\n\n\tresolveConnectionAttempt() {\n\t\tif (this.connectionAttempt) {\n\t\t\tthis.connectionAttempt.resolve();\n\t\t\tthis.connectionAttempt = null;\n\n\t\t\tthis.status = WebSocketStatus.Connected;\n\t\t\tthis.emit(\"status\", { status: WebSocketStatus.Connected });\n\t\t\tthis.emit(\"connect\");\n\t\t\tthis.messageQueue.forEach((message) => this.send(message));\n\t\t\tthis.messageQueue = [];\n\t\t}\n\t}\n\n\tstopConnectionAttempt() {\n\t\tthis.connectionAttempt = null;\n\t}\n\n\trejectConnectionAttempt() {\n\t\tthis.connectionAttempt?.reject();\n\t\tthis.connectionAttempt = null;\n\t}\n\n\tcloseTries = 0;\n\n\tcheckConnection() {\n\t\t// Don’t check the connection when it’s not even established\n\t\tif (this.status !== WebSocketStatus.Connected) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Don’t close the connection while waiting for the first message\n\t\tif (!this.lastMessageReceived) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Don’t close the connection when a message was received recently\n\t\tif (\n\t\t\tthis.configuration.messageReconnectTimeout >=\n\t\t\ttime.getUnixTime() - this.lastMessageReceived\n\t\t) {\n\t\t\treturn;\n\t\t}\n\n\t\t// No message received in a long time, not even your own\n\t\t// Awareness updates, which are updated every 15 seconds\n\t\t// if awareness is enabled.\n\t\tthis.closeTries += 1;\n\t\t// https://bugs.webkit.org/show_bug.cgi?id=247943\n\t\tif (this.closeTries > 2) {\n\t\t\tthis.onClose({\n\t\t\t\tevent: {\n\t\t\t\t\tcode: 4408,\n\t\t\t\t\treason: \"forced\",\n\t\t\t\t},\n\t\t\t});\n\t\t\tthis.closeTries = 0;\n\t\t} else {\n\t\t\tthis.webSocket?.close();\n\t\t\tthis.messageQueue = [];\n\t\t}\n\t}\n\n\tget serverUrl() {\n\t\tif (this.configuration.preserveTrailingSlash) {\n\t\t\treturn this.configuration.url;\n\t\t}\n\n\t\t// By default, ensure that the URL never ends with /\n\t\tlet url = this.configuration.url;\n\t\twhile (url[url.length - 1] === \"/\") {\n\t\t\turl = url.slice(0, url.length - 1);\n\t\t}\n\n\t\treturn url;\n\t}\n\n\tget url() {\n\t\treturn this.serverUrl;\n\t}\n\n\tdisconnect() {\n\t\tthis.shouldConnect = false;\n\n\t\tif (this.webSocket === null) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tthis.webSocket.close();\n\t\t\tthis.messageQueue = [];\n\t\t} catch (e) {\n\t\t\tconsole.error(e);\n\t\t}\n\t}\n\n\tprivate parseQueuedMessage(\n\t\tmessage: Uint8Array,\n\t): { documentName: string; messageType: number } | null {\n\t\ttry {\n\t\t\tconst decoder = createDecoder(message);\n\t\t\tconst documentName = readVarString(decoder);\n\t\t\tconst messageType = readVarUint(decoder);\n\t\t\treturn { documentName, messageType };\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate addToQueue(message: any) {\n\t\tif (message instanceof Uint8Array) {\n\t\t\tconst parsed = this.parseQueuedMessage(message);\n\t\t\tif (\n\t\t\t\tparsed &&\n\t\t\t\tHocuspocusProviderWebsocket.DEDUPLICATABLE_TYPES.has(parsed.messageType)\n\t\t\t) {\n\t\t\t\tthis.messageQueue = this.messageQueue.filter((queued) => {\n\t\t\t\t\tif (!(queued instanceof Uint8Array)) return true;\n\t\t\t\t\tconst queuedParsed = this.parseQueuedMessage(queued);\n\t\t\t\t\tif (!queuedParsed) return true;\n\t\t\t\t\treturn !(\n\t\t\t\t\t\tqueuedParsed.documentName === parsed.documentName &&\n\t\t\t\t\t\tqueuedParsed.messageType === parsed.messageType\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthis.messageQueue.push(message);\n\t}\n\n\tsend(message: any) {\n\t\tif (this.webSocket?.readyState === WsReadyStates.Open) {\n\t\t\tthis.webSocket.send(message);\n\t\t} else {\n\t\t\tthis.addToQueue(message);\n\t\t}\n\t}\n\n\tonClose({ event }: onCloseParameters) {\n\t\tthis.closeTries = 0;\n\t\tthis.cleanupWebSocket();\n\n\t\tif (this.connectionAttempt) {\n\t\t\t// That connection attempt failed.\n\t\t\tthis.rejectConnectionAttempt();\n\t\t}\n\n\t\t// Let’s update the connection status.\n\t\tthis.status = WebSocketStatus.Disconnected;\n\t\tthis.emit(\"status\", { status: WebSocketStatus.Disconnected });\n\t\tthis.emit(\"disconnect\", { event });\n\n\t\t// trigger connect if no retry is running and we want to have a connection\n\t\tif (!this.cancelWebsocketRetry && this.shouldConnect) {\n\t\t\tsetTimeout(() => {\n\t\t\t\tthis.connect();\n\t\t\t}, this.configuration.delay);\n\t\t}\n\t}\n\n\tdestroy() {\n\t\tthis.emit(\"destroy\");\n\n\t\tclearInterval(this.intervals.connectionChecker);\n\n\t\t// If there is still a connection attempt outstanding then we should stop\n\t\t// it before calling disconnect, otherwise it will be rejected in the onClose\n\t\t// handler and trigger a retry\n\t\tthis.stopConnectionAttempt();\n\n\t\tthis.disconnect();\n\n\t\tthis.removeAllListeners();\n\n\t\tthis.cleanupWebSocket();\n\t}\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<number, number>} 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 should only reply to requests, and not initiate them.\n * Therefore it is necessary 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 * @param {(error:Error)=>any} [errorHandler]\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin, errorHandler) => {\n try {\n Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n } catch (error) {\n if (errorHandler != null) errorHandler(/** @type {Error} */ (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 * @param {(error:Error)=>any} [errorHandler]\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. Does not need to be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n * @param {(error:Error)=>any} [errorHandler] Optional error handler that catches errors when reading Yjs messages.\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin, errorHandler) => {\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, errorHandler)\n break\n case messageYjsUpdate:\n readUpdate(decoder, doc, transactionOrigin, errorHandler)\n break\n default:\n throw new Error('Unknown message type')\n }\n return messageType\n}\n","import { type CloseEvent, 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 type { HocuspocusProvider } from \"./HocuspocusProvider.ts\";\nimport type { IncomingMessage } from \"./IncomingMessage.ts\";\nimport { OutgoingMessage } from \"./OutgoingMessage.ts\";\nimport { MessageType } from \"./types.ts\";\n\nexport class MessageReceiver {\n\tmessage: IncomingMessage;\n\n\tconstructor(message: IncomingMessage) {\n\t\tthis.message = message;\n\t}\n\n\tpublic apply(provider: HocuspocusProvider, emitSynced: boolean) {\n\t\tconst { message } = this;\n\t\tconst type = message.readVarUint();\n\n\t\tconst emptyMessageLength = message.length();\n\n\t\tswitch (type) {\n\t\t\tcase MessageType.Sync:\n\t\t\t\tthis.applySyncMessage(provider, emitSynced);\n\t\t\t\tbreak;\n\n\t\t\tcase MessageType.Awareness:\n\t\t\t\tthis.applyAwarenessMessage(provider);\n\t\t\t\tbreak;\n\n\t\t\tcase MessageType.Auth:\n\t\t\t\tthis.applyAuthMessage(provider);\n\t\t\t\tbreak;\n\n\t\t\tcase MessageType.QueryAwareness:\n\t\t\t\tthis.applyQueryAwarenessMessage(provider);\n\t\t\t\tbreak;\n\n\t\t\tcase MessageType.Stateless:\n\t\t\t\tprovider.receiveStateless(readVarString(message.decoder));\n\t\t\t\tbreak;\n\n\t\t\tcase MessageType.SyncStatus:\n\t\t\t\tthis.applySyncStatusMessage(\n\t\t\t\t\tprovider,\n\t\t\t\t\treadVarInt(message.decoder) === 1,\n\t\t\t\t);\n\t\t\t\tbreak;\n\n\t\t\tcase MessageType.CLOSE:\n\t\t\t\t// eslint-disable-next-line no-case-declarations\n\t\t\t\tconst event: CloseEvent = {\n\t\t\t\t\tcode: 1000,\n\t\t\t\t\treason: readVarString(message.decoder),\n\t\t\t\t};\n\t\t\t\tprovider.onClose();\n\t\t\t\tprovider.configuration.onClose({ event });\n\t\t\t\tprovider.forwardClose({ event });\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tconsole.error(`Can’t apply message of unknown type: ${type}`);\n\t\t}\n\n\t\t// Reply\n\t\tif (message.length() > emptyMessageLength + 1) {\n\t\t\t// length of documentName (considered in emptyMessageLength plus length of yjs sync type, set in applySyncMessage)\n\t\t\t// @ts-ignore\n\t\t\tprovider.send(OutgoingMessage, { encoder: message.encoder });\n\t\t}\n\t}\n\n\tprivate applySyncMessage(provider: HocuspocusProvider, emitSynced: boolean) {\n\t\tconst { message } = this;\n\n\t\tmessage.writeVarUint(MessageType.Sync);\n\n\t\t// Apply update\n\t\tconst syncMessageType = readSyncMessage(\n\t\t\tmessage.decoder,\n\t\t\tmessage.encoder,\n\t\t\tprovider.document,\n\t\t\tprovider,\n\t\t);\n\n\t\t// Synced once we receive Step2\n\t\tif (emitSynced && syncMessageType === messageYjsSyncStep2) {\n\t\t\tprovider.synced = true;\n\t\t}\n\t}\n\n\tapplySyncStatusMessage(provider: HocuspocusProvider, applied: boolean) {\n\t\tif (applied) {\n\t\t\tprovider.decrementUnsyncedChanges();\n\t\t}\n\t}\n\n\tprivate applyAwarenessMessage(provider: HocuspocusProvider) {\n\t\tif (!provider.awareness) return;\n\n\t\tconst { message } = this;\n\n\t\tawarenessProtocol.applyAwarenessUpdate(\n\t\t\tprovider.awareness,\n\t\t\tmessage.readVarUint8Array(),\n\t\t\tprovider,\n\t\t);\n\t}\n\n\tprivate applyAuthMessage(provider: HocuspocusProvider) {\n\t\tconst { message } = this;\n\n\t\treadAuthMessage(\n\t\t\tmessage.decoder,\n\t\t\tprovider.sendToken.bind(provider),\n\t\t\tprovider.permissionDeniedHandler.bind(provider),\n\t\t\tprovider.authenticatedHandler.bind(provider),\n\t\t);\n\t}\n\n\tprivate applyQueryAwarenessMessage(provider: HocuspocusProvider) {\n\t\tif (!provider.awareness) return;\n\n\t\tconst { message } = this;\n\n\t\tmessage.writeVarUint(MessageType.Awareness);\n\t\tmessage.writeVarUint8Array(\n\t\t\tawarenessProtocol.encodeAwarenessUpdate(\n\t\t\t\tprovider.awareness,\n\t\t\t\tArray.from(provider.awareness.getStates().keys()),\n\t\t\t),\n\t\t);\n\t}\n}\n","import type { Encoder } from \"lib0/encoding\";\nimport { toUint8Array } from \"lib0/encoding\";\nimport type { ConstructableOutgoingMessage } from \"./types.ts\";\n\nexport class MessageSender {\n\tencoder: Encoder;\n\n\tmessage: any;\n\n\tconstructor(Message: ConstructableOutgoingMessage, args: any = {}) {\n\t\tthis.message = new Message();\n\t\tthis.encoder = this.message.get(args);\n\t}\n\n\tcreate() {\n\t\treturn toUint8Array(this.encoder);\n\t}\n\n\tsend(webSocket: any) {\n\t\twebSocket?.send(this.create());\n\t}\n}\n","// @ts-ignore - __HOCUSPOCUS_VERSION__ is replaced at build time by rolldown\n// eslint-disable-next-line\nexport const version: string = typeof __HOCUSPOCUS_VERSION__ !== 'undefined'\n\t? __HOCUSPOCUS_VERSION__\n\t: 'unknown';\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport { writeAuthentication } from \"@hocuspocus/common\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\nimport { version } from \"../version.ts\";\n\nexport class AuthenticationMessage extends OutgoingMessage {\n\ttype = MessageType.Auth;\n\n\tdescription = \"Authentication\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tif (typeof args.token === \"undefined\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"The authentication message requires `token` as an argument.\",\n\t\t\t);\n\t\t}\n\n\t\twriteVarString(this.encoder, args.documentName!);\n\t\twriteVarUint(this.encoder, this.type);\n\t\twriteAuthentication(this.encoder, args.token);\n\t\twriteVarString(this.encoder, version);\n\n\t\treturn this.encoder;\n\t}\n}\n","import * as encoding from \"lib0/encoding\";\nimport { encodeAwarenessUpdate } from \"y-protocols/awareness\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class AwarenessMessage extends OutgoingMessage {\n\ttype = MessageType.Awareness;\n\n\tdescription = \"Awareness states update\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tif (typeof args.awareness === \"undefined\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"The awareness message requires awareness as an argument\",\n\t\t\t);\n\t\t}\n\n\t\tif (typeof args.clients === \"undefined\") {\n\t\t\tthrow new Error(\"The awareness message requires clients as an argument\");\n\t\t}\n\n\t\tencoding.writeVarString(this.encoder, args.documentName!);\n\t\tencoding.writeVarUint(this.encoder, this.type);\n\n\t\tlet awarenessUpdate;\n\t\tif (args.states === undefined) {\n\t\t\tawarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients);\n\t\t} else {\n\t\t\tawarenessUpdate = encodeAwarenessUpdate(\n\t\t\t\targs.awareness,\n\t\t\t\targs.clients,\n\t\t\t\targs.states,\n\t\t\t);\n\t\t}\n\n\t\tencoding.writeVarUint8Array(this.encoder, awarenessUpdate);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class StatelessMessage extends OutgoingMessage {\n\ttype = MessageType.Stateless;\n\n\tdescription = \"A stateless message\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\twriteVarString(this.encoder, args.documentName!);\n\t\twriteVarUint(this.encoder, this.type);\n\t\twriteVarString(this.encoder, args.payload ?? \"\");\n\n\t\treturn this.encoder;\n\t}\n}\n","import * as encoding from \"lib0/encoding\";\nimport * as syncProtocol from \"y-protocols/sync\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class SyncStepOneMessage extends OutgoingMessage {\n\ttype = MessageType.Sync;\n\n\tdescription = \"First sync step\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tif (typeof args.document === \"undefined\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"The sync step one message requires document as an argument\",\n\t\t\t);\n\t\t}\n\n\t\tencoding.writeVarString(this.encoder, args.documentName!);\n\t\tencoding.writeVarUint(this.encoder, this.type);\n\t\tsyncProtocol.writeSyncStep1(this.encoder, args.document);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport { writeUpdate } from \"y-protocols/sync\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class UpdateMessage extends OutgoingMessage {\n\ttype = MessageType.Sync;\n\n\tdescription = \"A document update\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\twriteVarString(this.encoder, args.documentName!);\n\t\twriteVarUint(this.encoder, this.type);\n\n\t\twriteUpdate(this.encoder, args.update);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { awarenessStatesToArray, makeRoutingKey, parseRoutingKey } from \"@hocuspocus/common\";\nimport { Awareness, removeAwarenessStates } from \"y-protocols/awareness\";\nimport * as Y from \"yjs\";\nimport EventEmitter from \"./EventEmitter.ts\";\nimport type { CompleteHocuspocusProviderWebsocketConfiguration } from \"./HocuspocusProviderWebsocket.ts\";\nimport { HocuspocusProviderWebsocket } from \"./HocuspocusProviderWebsocket.ts\";\nimport { IncomingMessage } from \"./IncomingMessage.ts\";\nimport { MessageReceiver } from \"./MessageReceiver.ts\";\nimport { MessageSender } from \"./MessageSender.ts\";\nimport { AuthenticationMessage } from \"./OutgoingMessages/AuthenticationMessage.ts\";\nimport { AwarenessMessage } from \"./OutgoingMessages/AwarenessMessage.ts\";\nimport { StatelessMessage } from \"./OutgoingMessages/StatelessMessage.ts\";\nimport { SyncStepOneMessage } from \"./OutgoingMessages/SyncStepOneMessage.ts\";\nimport { UpdateMessage } from \"./OutgoingMessages/UpdateMessage.ts\";\nimport {\n\ttype AuthorizedScope,\n\ttype ConstructableOutgoingMessage,\n\ttype onAuthenticatedParameters,\n\ttype onAuthenticationFailedParameters,\n\ttype onAwarenessChangeParameters,\n\ttype onAwarenessUpdateParameters,\n\ttype onCloseParameters,\n\ttype onDisconnectParameters,\n\ttype onMessageParameters,\n\ttype onOpenParameters,\n\ttype onOutgoingMessageParameters,\n\ttype onStatelessParameters,\n\ttype onStatusParameters,\n\ttype onSyncedParameters,\n\ttype onUnsyncedChangesParameters,\n} from \"./types.ts\";\n\nexport type HocuspocusProviderConfiguration = Required<\n\tPick<CompleteHocuspocusProviderConfiguration, \"name\">\n> &\n\tPartial<CompleteHocuspocusProviderConfiguration> &\n\t(\n\t\t| (Required<Pick<CompleteHocuspocusProviderWebsocketConfiguration, \"url\">> &\n\t\t\t\tPartial<\n\t\t\t\t\tPick<\n\t\t\t\t\t\tCompleteHocuspocusProviderWebsocketConfiguration,\n\t\t\t\t\t\t\"preserveTrailingSlash\"\n\t\t\t\t\t>\n\t\t\t\t>)\n\t\t| Required<\n\t\t\t\tPick<CompleteHocuspocusProviderConfiguration, \"websocketProvider\">\n\t\t >\n\t);\n\nexport interface CompleteHocuspocusProviderConfiguration {\n\t/**\n\t * The identifier/name of your document\n\t */\n\tname: string;\n\t/**\n\t * The actual Y.js document\n\t */\n\tdocument: Y.Doc;\n\n\t/**\n\t * An Awareness instance to keep the presence state of all clients.\n\t *\n\t * You can disable sharing awareness information by passing `null`.\n\t * Note that having no awareness information shared across all connections will break our ping checks\n\t * and thus trigger reconnects. You should always have at least one Provider with enabled awareness per\n\t * socket connection, or ensure that the Provider receives messages before running into `HocuspocusProviderWebsocket.messageReconnectTimeout`.\n\t */\n\tawareness: Awareness | null;\n\n\t/**\n\t * A token that’s sent to the backend for authentication purposes.\n\t */\n\ttoken: string | (() => string) | (() => Promise<string>) | null;\n\n\t/**\n\t * Hocuspocus websocket provider\n\t */\n\twebsocketProvider: HocuspocusProviderWebsocket;\n\n\t/**\n\t * Enable session-aware multiplexing. When true, the provider embeds a unique\n\t * sessionId in the documentName field of every message, allowing multiple\n\t * providers with the same document name on a single WebSocket connection.\n\t *\n\t * Only set this to `false` when connecting to a v3 server that does not\n\t * support session awareness.\n\t *\n\t * Default: true\n\t */\n\tsessionAwareness: boolean;\n\n\t/**\n\t * Force syncing the document in the defined interval.\n\t */\n\tforceSyncInterval: false | number;\n\n\tonAuthenticated: (data: onAuthenticatedParameters) => void;\n\tonAuthenticationFailed: (data: onAuthenticationFailedParameters) => void;\n\tonOpen: (data: onOpenParameters) => void;\n\tonConnect: () => void;\n\tonStatus: (data: onStatusParameters) => void;\n\tonMessage: (data: onMessageParameters) => void;\n\tonOutgoingMessage: (data: onOutgoingMessageParameters) => void;\n\tonSynced: (data: onSyncedParameters) => void;\n\tonDisconnect: (data: onDisconnectParameters) => void;\n\tonClose: (data: onCloseParameters) => void;\n\tonDestroy: () => void;\n\tonAwarenessUpdate: (data: onAwarenessUpdateParameters) => void;\n\tonAwarenessChange: (data: onAwarenessChangeParameters) => void;\n\tonStateless: (data: onStatelessParameters) => void;\n\tonUnsyncedChanges: (data: onUnsyncedChangesParameters) => void;\n}\n\nexport class AwarenessError extends Error {\n\tcode = 1001;\n}\n\nexport class HocuspocusProvider extends EventEmitter {\n\tpublic configuration: CompleteHocuspocusProviderConfiguration = {\n\t\tname: \"\",\n\t\t// @ts-ignore\n\t\tdocument: undefined,\n\t\t// @ts-ignore\n\t\tawareness: undefined,\n\t\ttoken: null,\n\t\tsessionAwareness: true,\n\t\tforceSyncInterval: false,\n\t\tonAuthenticated: () => null,\n\t\tonAuthenticationFailed: () => null,\n\t\tonOpen: () => null,\n\t\tonConnect: () => null,\n\t\tonMessage: () => null,\n\t\tonOutgoingMessage: () => null,\n\t\tonSynced: () => null,\n\t\tonStatus: () => null,\n\t\tonDisconnect: () => null,\n\t\tonClose: () => null,\n\t\tonDestroy: () => null,\n\t\tonAwarenessUpdate: () => null,\n\t\tonAwarenessChange: () => null,\n\t\tonStateless: () => null,\n\t\tonUnsyncedChanges: () => null,\n\t};\n\n\tisSynced = false;\n\n\tunsyncedChanges = 0;\n\n\tisAuthenticated = false;\n\n\tauthorizedScope: AuthorizedScope | undefined = undefined;\n\n\t// @internal\n\tmanageSocket = false;\n\n\tprivate _isAttached = false;\n\n\t/**\n\t * Unique session identifier for this provider instance.\n\t * Used for multiplexing multiple providers with the same document name on a single WebSocket.\n\t */\n\tsessionId: string = Math.random().toString(36).slice(2);\n\n\t/**\n\t * The effective name used as the first VarString in messages.\n\t * When `sessionAwareness` is enabled, returns a composite key (documentName\\0sessionId).\n\t * Otherwise, returns the plain document name.\n\t */\n\tget effectiveName(): string {\n\t\treturn this.configuration.sessionAwareness\n\t\t\t? makeRoutingKey(this.configuration.name, this.sessionId)\n\t\t\t: this.configuration.name;\n\t}\n\n\tintervals: any = {\n\t\tforceSync: null,\n\t};\n\n\tconstructor(configuration: HocuspocusProviderConfiguration) {\n\t\tsuper();\n\t\tthis.setConfiguration(configuration);\n\n\t\tthis.configuration.document = configuration.document\n\t\t\t? configuration.document\n\t\t\t: new Y.Doc();\n\t\tthis.configuration.awareness =\n\t\t\tconfiguration.awareness !== undefined\n\t\t\t\t? configuration.awareness\n\t\t\t\t: new Awareness(this.document);\n\n\t\tthis.on(\"open\", this.configuration.onOpen);\n\t\tthis.on(\"message\", this.configuration.onMessage);\n\t\tthis.on(\"outgoingMessage\", this.configuration.onOutgoingMessage);\n\t\tthis.on(\"synced\", this.configuration.onSynced);\n\t\tthis.on(\"destroy\", this.configuration.onDestroy);\n\t\tthis.on(\"awarenessUpdate\", this.configuration.onAwarenessUpdate);\n\t\tthis.on(\"awarenessChange\", this.configuration.onAwarenessChange);\n\t\tthis.on(\"stateless\", this.configuration.onStateless);\n\t\tthis.on(\"unsyncedChanges\", this.configuration.onUnsyncedChanges);\n\n\t\tthis.on(\"authenticated\", this.configuration.onAuthenticated);\n\t\tthis.on(\"authenticationFailed\", this.configuration.onAuthenticationFailed);\n\n\t\tthis.awareness?.on(\"update\", () => {\n\t\t\tthis.emit(\"awarenessUpdate\", {\n\t\t\t\tstates: awarenessStatesToArray(this.awareness!.getStates()),\n\t\t\t});\n\t\t});\n\n\t\tthis.awareness?.on(\"change\", () => {\n\t\t\tthis.emit(\"awarenessChange\", {\n\t\t\t\tstates: awarenessStatesToArray(this.awareness!.getStates()),\n\t\t\t});\n\t\t});\n\n\t\tthis.document.on(\"update\", this.boundDocumentUpdateHandler);\n\t\tthis.awareness?.on(\"update\", this.boundAwarenessUpdateHandler);\n\n\t\tthis.registerEventListeners();\n\n\t\tif (\n\t\t\tthis.configuration.forceSyncInterval &&\n\t\t\ttypeof this.configuration.forceSyncInterval === \"number\"\n\t\t) {\n\t\t\tthis.intervals.forceSync = setInterval(\n\t\t\t\tthis.forceSync.bind(this),\n\t\t\t\tthis.configuration.forceSyncInterval,\n\t\t\t);\n\t\t}\n\n\t\tif (this.manageSocket) {\n\t\t\tthis.attach();\n\t\t}\n\t}\n\n\tboundDocumentUpdateHandler = this.documentUpdateHandler.bind(this);\n\n\tboundAwarenessUpdateHandler = this.awarenessUpdateHandler.bind(this);\n\n\tboundPageHide = this.pageHide.bind(this);\n\n\tboundOnOpen = this.onOpen.bind(this);\n\n\tboundOnClose = this.onClose.bind(this);\n\n\tforwardConnect = () => this.emit(\"connect\");\n\n\tforwardStatus = (e: onStatusParameters) => this.emit(\"status\", e);\n\n\tforwardClose = (e: onCloseParameters) => this.emit(\"close\", e);\n\n\tforwardDisconnect = (e: onDisconnectParameters) => this.emit(\"disconnect\", e);\n\n\tforwardDestroy = () => this.emit(\"destroy\");\n\n\tpublic setConfiguration(\n\t\tconfiguration: Partial<HocuspocusProviderConfiguration> = {},\n\t): void {\n\t\tif (!configuration.websocketProvider) {\n\t\t\tthis.manageSocket = true;\n\t\t\tthis.configuration.websocketProvider = new HocuspocusProviderWebsocket(\n\t\t\t\tconfiguration as CompleteHocuspocusProviderWebsocketConfiguration,\n\t\t\t);\n\t\t}\n\n\t\tthis.configuration = { ...this.configuration, ...configuration };\n\t}\n\n\tget document() {\n\t\treturn this.configuration.document;\n\t}\n\n\tpublic get isAttached() {\n\t\treturn this._isAttached;\n\t}\n\n\tget awareness() {\n\t\treturn this.configuration.awareness;\n\t}\n\n\tget hasUnsyncedChanges(): boolean {\n\t\treturn this.unsyncedChanges > 0;\n\t}\n\n\tprivate resetUnsyncedChanges() {\n\t\tthis.unsyncedChanges = 1;\n\t\tthis.emit(\"unsyncedChanges\", { number: this.unsyncedChanges });\n\t}\n\n\tincrementUnsyncedChanges() {\n\t\tthis.unsyncedChanges += 1;\n\t\tthis.emit(\"unsyncedChanges\", { number: this.unsyncedChanges });\n\t}\n\n\tdecrementUnsyncedChanges() {\n\t\tif (this.unsyncedChanges > 0) {\n\t\t\tthis.unsyncedChanges -= 1;\n\t\t}\n\n\t\tif (this.unsyncedChanges === 0) {\n\t\t\tthis.synced = true;\n\t\t}\n\n\t\tthis.emit(\"unsyncedChanges\", { number: this.unsyncedChanges });\n\t}\n\n\tforceSync() {\n\t\tthis.resetUnsyncedChanges();\n\n\t\tthis.send(SyncStepOneMessage, {\n\t\t\tdocument: this.document,\n\t\t\tdocumentName: this.effectiveName,\n\t\t});\n\t}\n\n\tpageHide() {\n\t\tif (this.awareness) {\n\t\t\tremoveAwarenessStates(\n\t\t\t\tthis.awareness,\n\t\t\t\t[this.document.clientID],\n\t\t\t\t\"page hide\",\n\t\t\t);\n\t\t}\n\t}\n\n\tregisterEventListeners() {\n\t\tif (typeof window === \"undefined\" || !(\"addEventListener\" in window)) {\n\t\t\treturn;\n\t\t}\n\n\t\twindow.addEventListener(\"pagehide\", this.boundPageHide);\n\t}\n\n\tsendStateless(payload: string) {\n\t\tthis.send(StatelessMessage, {\n\t\t\tdocumentName: this.effectiveName,\n\t\t\tpayload,\n\t\t});\n\t}\n\n\tasync sendToken() {\n\t\tlet token: string | null;\n\t\ttry {\n\t\t\ttoken = await this.getToken();\n\t\t} catch (error) {\n\t\t\tthis.permissionDeniedHandler(\n\t\t\t\t`Failed to get token during sendToken(): ${error}`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.send(AuthenticationMessage, {\n\t\t\ttoken: token ?? \"\",\n\t\t\tdocumentName: this.effectiveName,\n\t\t});\n\t}\n\n\tdocumentUpdateHandler(update: Uint8Array, origin: any) {\n\t\tif (origin === this) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.incrementUnsyncedChanges();\n\t\tthis.send(UpdateMessage, { update, documentName: this.effectiveName });\n\t}\n\n\tawarenessUpdateHandler({ added, updated, removed }: any, origin: any) {\n\t\tconst changedClients = added.concat(updated).concat(removed);\n\n\t\tthis.send(AwarenessMessage, {\n\t\t\tawareness: this.awareness,\n\t\t\tclients: changedClients,\n\t\t\tdocumentName: this.effectiveName,\n\t\t});\n\t}\n\n\t/**\n\t * Indicates whether a first handshake with the server has been established\n\t *\n\t * Note: this does not mean all updates from the client have been persisted to the backend. For this,\n\t * use `hasUnsyncedChanges`.\n\t */\n\tget synced(): boolean {\n\t\treturn this.isSynced;\n\t}\n\n\tset synced(state) {\n\t\tif (this.isSynced === state) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.isSynced = state;\n\n\t\tif (state) {\n\t\t\tthis.emit(\"synced\", { state });\n\t\t}\n\t}\n\n\treceiveStateless(payload: string) {\n\t\tthis.emit(\"stateless\", { payload });\n\t}\n\n\t// not needed, but provides backward compatibility with e.g. lexical/yjs\n\tasync connect() {\n\t\tif (this.manageSocket) {\n\t\t\treturn this.configuration.websocketProvider.connect();\n\t\t}\n\n\t\tconsole.warn(\n\t\t\t\"HocuspocusProvider::connect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.\",\n\t\t);\n\t}\n\n\tdisconnect() {\n\t\tif (this.manageSocket) {\n\t\t\treturn this.configuration.websocketProvider.disconnect();\n\t\t}\n\n\t\tconsole.warn(\n\t\t\t\"HocuspocusProvider::disconnect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.\",\n\t\t);\n\t}\n\n\tasync onOpen(event: Event) {\n\t\tthis.isAuthenticated = false;\n\n\t\tthis.emit(\"open\", { event });\n\t\tawait this.sendToken();\n\t\tthis.startSync();\n\t}\n\n\tasync getToken() {\n\t\tif (typeof this.configuration.token === \"function\") {\n\t\t\tconst token = await this.configuration.token();\n\t\t\treturn token;\n\t\t}\n\n\t\treturn this.configuration.token;\n\t}\n\n\tstartSync() {\n\t\tthis.resetUnsyncedChanges();\n\n\t\tthis.send(SyncStepOneMessage, {\n\t\t\tdocument: this.document,\n\t\t\tdocumentName: this.effectiveName,\n\t\t});\n\n\t\tif (this.awareness && this.awareness.getLocalState() !== null) {\n\t\t\tthis.send(AwarenessMessage, {\n\t\t\t\tawareness: this.awareness,\n\t\t\t\tclients: [this.document.clientID],\n\t\t\t\tdocumentName: this.effectiveName,\n\t\t\t});\n\t\t}\n\t}\n\n\tsend(message: ConstructableOutgoingMessage, args: any) {\n\t\tif (!this._isAttached) return;\n\n\t\tconst messageSender = new MessageSender(message, args);\n\n\t\tthis.emit(\"outgoingMessage\", { message: messageSender.message });\n\t\tmessageSender.send(this.configuration.websocketProvider);\n\t}\n\n\tonMessage(event: MessageEvent) {\n\t\tconst message = new IncomingMessage(event.data);\n\n\t\tconst rawKey = message.readVarString();\n\t\t// Extract actual documentName from potentially composite routing key\n\t\tconst { documentName } = parseRoutingKey(rawKey);\n\n\t\tmessage.writeVarString(this.effectiveName);\n\n\t\tthis.emit(\"message\", { event, message: new IncomingMessage(event.data) });\n\n\t\tnew MessageReceiver(message).apply(this, true);\n\t}\n\n\tonClose() {\n\t\tthis.isAuthenticated = false;\n\t\tthis.synced = false;\n\n\t\t// update awareness (all users except local left)\n\t\tif (this.awareness) {\n\t\t\tremoveAwarenessStates(\n\t\t\t\tthis.awareness,\n\t\t\t\tArray.from(this.awareness.getStates().keys()).filter(\n\t\t\t\t\t(client) => client !== this.document.clientID,\n\t\t\t\t),\n\t\t\t\tthis,\n\t\t\t);\n\t\t}\n\t}\n\n\tdestroy() {\n\t\tthis.emit(\"destroy\");\n\n\t\tif (this.intervals.forceSync) {\n\t\t\tclearInterval(this.intervals.forceSync);\n\t\t}\n\n\t\tif (this.awareness) {\n\t\t\tremoveAwarenessStates(\n\t\t\t\tthis.awareness,\n\t\t\t\t[this.document.clientID],\n\t\t\t\t\"provider destroy\",\n\t\t\t);\n\t\t\tthis.awareness.off(\"update\", this.boundAwarenessUpdateHandler);\n\t\t\tthis.awareness.destroy();\n\t\t}\n\n\t\tthis.document.off(\"update\", this.boundDocumentUpdateHandler);\n\n\t\tthis.removeAllListeners();\n\n\t\tthis.detach();\n\n\t\tif (this.manageSocket) {\n\t\t\tthis.configuration.websocketProvider.destroy();\n\t\t}\n\n\t\tif (typeof window === \"undefined\" || !(\"removeEventListener\" in window)) {\n\t\t\treturn;\n\t\t}\n\n\t\twindow.removeEventListener(\"pagehide\", this.boundPageHide);\n\t}\n\n\tdetach() {\n\t\tthis.configuration.websocketProvider.off(\n\t\t\t\"connect\",\n\t\t\tthis.configuration.onConnect,\n\t\t);\n\t\tthis.configuration.websocketProvider.off(\"connect\", this.forwardConnect);\n\n\t\tthis.configuration.websocketProvider.off(\"status\", this.forwardStatus);\n\t\tthis.configuration.websocketProvider.off(\n\t\t\t\"status\",\n\t\t\tthis.configuration.onStatus,\n\t\t);\n\n\t\tthis.configuration.websocketProvider.off(\"open\", this.boundOnOpen);\n\t\tthis.configuration.websocketProvider.off(\"close\", this.boundOnClose);\n\t\tthis.configuration.websocketProvider.off(\n\t\t\t\"close\",\n\t\t\tthis.configuration.onClose,\n\t\t);\n\t\tthis.configuration.websocketProvider.off(\"close\", this.forwardClose);\n\t\tthis.configuration.websocketProvider.off(\n\t\t\t\"disconnect\",\n\t\t\tthis.configuration.onDisconnect,\n\t\t);\n\t\tthis.configuration.websocketProvider.off(\n\t\t\t\"disconnect\",\n\t\t\tthis.forwardDisconnect,\n\t\t);\n\t\tthis.configuration.websocketProvider.off(\n\t\t\t\"destroy\",\n\t\t\tthis.configuration.onDestroy,\n\t\t);\n\t\tthis.configuration.websocketProvider.off(\"destroy\", this.forwardDestroy);\n\n\t\tthis.configuration.websocketProvider.detach(this);\n\n\t\tthis._isAttached = false;\n\t}\n\n\tattach() {\n\t\tif (this._isAttached) return;\n\n\t\tthis.configuration.websocketProvider.on(\n\t\t\t\"connect\",\n\t\t\tthis.configuration.onConnect,\n\t\t);\n\t\tthis.configuration.websocketProvider.on(\"connect\", this.forwardConnect);\n\n\t\tthis.configuration.websocketProvider.on(\n\t\t\t\"status\",\n\t\t\tthis.configuration.onStatus,\n\t\t);\n\t\tthis.configuration.websocketProvider.on(\"status\", this.forwardStatus);\n\n\t\tthis.configuration.websocketProvider.on(\"open\", this.boundOnOpen);\n\n\t\tthis.configuration.websocketProvider.on(\"close\", this.boundOnClose);\n\t\tthis.configuration.websocketProvider.on(\n\t\t\t\"close\",\n\t\t\tthis.configuration.onClose,\n\t\t);\n\t\tthis.configuration.websocketProvider.on(\"close\", this.forwardClose);\n\n\t\tthis.configuration.websocketProvider.on(\n\t\t\t\"disconnect\",\n\t\t\tthis.configuration.onDisconnect,\n\t\t);\n\t\tthis.configuration.websocketProvider.on(\n\t\t\t\"disconnect\",\n\t\t\tthis.forwardDisconnect,\n\t\t);\n\n\t\tthis.configuration.websocketProvider.on(\n\t\t\t\"destroy\",\n\t\t\tthis.configuration.onDestroy,\n\t\t);\n\t\tthis.configuration.websocketProvider.on(\"destroy\", this.forwardDestroy);\n\n\t\tthis.configuration.websocketProvider.attach(this);\n\n\t\tthis._isAttached = true;\n\t}\n\n\tpermissionDeniedHandler(reason: string) {\n\t\tthis.emit(\"authenticationFailed\", { reason });\n\t\tthis.isAuthenticated = false;\n\t}\n\n\tauthenticatedHandler(scope: string) {\n\t\tthis.isAuthenticated = true;\n\t\tthis.authorizedScope = scope as AuthorizedScope;\n\n\t\tthis.emit(\"authenticated\", { scope });\n\t}\n\n\tsetAwarenessField(key: string, value: any) {\n\t\tif (!this.awareness) {\n\t\t\tthrow new AwarenessError(\n\t\t\t\t`Cannot set awareness field \"${key}\" to ${JSON.stringify(value)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`,\n\t\t\t);\n\t\t}\n\t\tthis.awareness.setLocalStateField(key, value);\n\t}\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,22],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAa,QAAQ,KAAK;;;;;;;AAwB1B,MAAa,OAAO,GAAG,MAAM,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