{"version":3,"file":"hocuspocus-server.cjs","sources":["../../../node_modules/lib0/map.js","../../../node_modules/lib0/math.js","../../../node_modules/lib0/binary.js","../../../node_modules/lib0/encoding.js","../../../node_modules/lib0/buffer.js","../../../node_modules/lib0/decoding.js","../src/types.ts","../../../node_modules/lib0/time.js","../../../node_modules/lib0/set.js","../../../node_modules/lib0/array.js","../../../node_modules/lib0/observable.js","../../../node_modules/lib0/object.js","../../../node_modules/lib0/function.js","../../../node_modules/y-protocols/awareness.js","../../../node_modules/lib0/mutex.js","../../../node_modules/y-protocols/sync.js","../src/OutgoingMessage.ts","../src/Debugger.ts","../src/Document.ts","../src/IncomingMessage.ts","../src/MessageReceiver.ts","../src/Connection.ts","../src/Hocuspocus.ts"],"sourcesContent":["/**\n * Utility module to work with key-value stores.\n *\n * @module map\n */\n\n/**\n * Creates a new Map instance.\n *\n * @function\n * @return {Map<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 X,Y\n * @param {Map<X,Y>} m\n * @return {Map<X,Y>}\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 T,K\n * @param {Map<K, T>} map\n * @param {K} key\n * @param {function():T} createT\n * @return {T}\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 * Common Math expressions.\n *\n * @module math\n */\n\nexport const floor = Math.floor\nexport const ceil = Math.ceil\nexport const abs = Math.abs\nexport const imul = Math.imul\nexport const round = Math.round\nexport const log10 = Math.log10\nexport const log2 = Math.log2\nexport const log = Math.log\nexport const sqrt = Math.sqrt\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The sum of a and b\n */\nexport const add = (a, b) => a + b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The smaller element of a and b\n */\nexport const min = (a, b) => a < b ? a : b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The bigger element of a and b\n */\nexport const max = (a, b) => a > b ? a : b\n\nexport const isNaN = Number.isNaN\n\nexport const pow = Math.pow\n/**\n * Base 10 exponential function. Returns the value of 10 raised to the power of pow.\n *\n * @param {number} exp\n * @return {number}\n */\nexport const exp10 = exp => Math.pow(10, exp)\n\nexport const sign = Math.sign\n\n/**\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * 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 = new 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 = new decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\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 * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n  let len = encoder.cpos\n  for (let i = 0; i < encoder.bufs.length; i++) {\n    len += encoder.bufs[i].length\n  }\n  return len\n}\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n  const uint8arr = new Uint8Array(length(encoder))\n  let curPos = 0\n  for (let i = 0; i < encoder.bufs.length; i++) {\n    const d = encoder.bufs[i]\n    uint8arr.set(d, curPos)\n    curPos += d.length\n  }\n  uint8arr.set(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n  return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nconst verifyLen = (encoder, len) => {\n  const bufferLen = encoder.cbuf.length\n  if (bufferLen - encoder.cpos < len) {\n    encoder.bufs.push(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos))\n    encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n    encoder.cpos = 0\n  }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n  const bufferLen = encoder.cbuf.length\n  if (encoder.cpos === bufferLen) {\n    encoder.bufs.push(encoder.cbuf)\n    encoder.cbuf = new Uint8Array(bufferLen * 2)\n    encoder.cpos = 0\n  }\n  encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n  let buffer = null\n  // iterate all buffers and adjust position\n  for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n    const b = encoder.bufs[i]\n    if (pos < b.length) {\n      buffer = b // found buffer\n    } else {\n      pos -= b.length\n    }\n  }\n  if (buffer === null) {\n    // use current buffer\n    buffer = encoder.cbuf\n  }\n  buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n  write(encoder, num & binary.BITS8)\n  write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n  set(encoder, pos, num & binary.BITS8)\n  set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n  for (let i = 0; i < 4; i++) {\n    write(encoder, num & binary.BITS8)\n    num >>>= 8\n  }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n  for (let i = 3; i >= 0; i--) {\n    write(encoder, (num >>> (8 * i)) & binary.BITS8)\n  }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n  for (let i = 0; i < 4; i++) {\n    set(encoder, pos + i, num & binary.BITS8)\n    num >>>= 8\n  }\n}\n\n/**\n * Write a variable length unsigned integer.\n *\n * Encodes integers in the range from [0, 4294967295] / [0, 0xffffffff]. (max 32 bit unsigned integer)\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 >>>= 7\n  }\n  write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * Encodes integers in the range from [-2147483648, -2147483647].\n *\n * We don't use zig-zag encoding because we want to keep the option open\n * to use the same function for BigInt and 53bit integers (doubles).\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 >>>= 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 >>>= 7\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 writeVarString = (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 the content of another Encoder.\n *\n * @TODO: can be improved!\n *        - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n *                Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n  const bufferLen = encoder.cbuf.length\n  const cpos = encoder.cpos\n  const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n  const rightCopyLen = uint8Array.length - leftCopyLen\n  encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n  encoder.cpos += leftCopyLen\n  if (rightCopyLen > 0) {\n    // Still something to write, write right half..\n    // Append new buffer\n    encoder.bufs.push(encoder.cbuf)\n    // must have at least size of remaining buffer\n    encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n    // copy array\n    encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n    encoder.cpos = rightCopyLen\n  }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n  writeVarUint(encoder, uint8Array.byteLength)\n  writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n  verifyLen(encoder, len)\n  const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n  encoder.cpos += len\n  return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n  floatTestBed.setFloat32(0, num)\n  return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n *   32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type           | Prefix   | Encoding Method    | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined           | 127      |                    | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null                | 126      |                    | |\n * | integer             | 125      | writeVarInt        | Only encodes 32 bit signed integers |\n * | float32             | 124      | writeFloat32       | |\n * | float64             | 123      | writeFloat64       | |\n * | bigint              | 122      | writeBigInt64      | |\n * | boolean (false)     | 121      |                    | True and false are different data types so we save the following byte |\n * | boolean (true)      | 120      |                    | - 0b01111000 so the last bit determines whether true or false |\n * | string              | 119      | writeVarString     | |\n * | object<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 {undefined|null|number|bigint|boolean|string|Object<string,any>|Array<any>|Uint8Array} data\n */\nexport const writeAny = (encoder, data) => {\n  switch (typeof data) {\n    case 'string':\n      // TYPE 119: STRING\n      write(encoder, 119)\n      writeVarString(encoder, data)\n      break\n    case 'number':\n      if (number.isInteger(data) && data <= binary.BITS31) {\n        // TYPE 125: INTEGER\n        write(encoder, 125)\n        writeVarInt(encoder, data)\n      } else if (isFloat32(data)) {\n        // TYPE 124: FLOAT32\n        write(encoder, 124)\n        writeFloat32(encoder, data)\n      } else {\n        // TYPE 123: FLOAT64\n        write(encoder, 123)\n        writeFloat64(encoder, data)\n      }\n      break\n    case 'bigint':\n      // TYPE 122: BigInt\n      write(encoder, 122)\n      writeBigInt64(encoder, data)\n      break\n    case 'object':\n      if (data === null) {\n        // TYPE 126: null\n        write(encoder, 126)\n      } else if (data instanceof Array) {\n        // TYPE 117: Array\n        write(encoder, 117)\n        writeVarUint(encoder, data.length)\n        for (let i = 0; i < data.length; i++) {\n          writeAny(encoder, data[i])\n        }\n      } else if (data instanceof Uint8Array) {\n        // TYPE 116: ArrayBuffer\n        write(encoder, 116)\n        writeVarUint8Array(encoder, data)\n      } else {\n        // TYPE 118: Object\n        write(encoder, 118)\n        const keys = Object.keys(data)\n        writeVarUint(encoder, keys.length)\n        for (let i = 0; i < keys.length; i++) {\n          const key = keys[i]\n          writeVarString(encoder, key)\n          writeAny(encoder, data[key])\n        }\n      }\n      break\n    case 'boolean':\n      // TYPE 120/121: boolean (true/false)\n      write(encoder, data ? 120 : 121)\n      break\n    default:\n      // TYPE 127: undefined\n      write(encoder, 127)\n  }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n  /**\n   * @param {function(Encoder, T):void} writer\n   */\n  constructor (writer) {\n    super()\n    /**\n     * The writer\n     */\n    this.w = writer\n    /**\n     * Current state\n     * @type {T|null}\n     */\n    this.s = null\n    this.count = 0\n  }\n\n  /**\n   * @param {T} v\n   */\n  write (v) {\n    if (this.s === v) {\n      this.count++\n    } else {\n      if (this.count > 0) {\n        // flush counter, unless this is the first value (count = 0)\n        writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n      }\n      this.count = 1\n      // write first value\n      this.w(this, v)\n      this.s = v\n    }\n  }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n  /**\n   * @param {number} start\n   */\n  constructor (start) {\n    super()\n    /**\n     * Current state\n     * @type {number}\n     */\n    this.s = start\n  }\n\n  /**\n   * @param {number} v\n   */\n  write (v) {\n    writeVarInt(this, v - this.s)\n    this.s = v\n  }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n  /**\n   * @param {number} start\n   */\n  constructor (start) {\n    super()\n    /**\n     * Current state\n     * @type {number}\n     */\n    this.s = start\n    this.count = 0\n  }\n\n  /**\n   * @param {number} v\n   */\n  write (v) {\n    if (this.s === v && this.count > 0) {\n      this.count++\n    } else {\n      if (this.count > 0) {\n        // flush counter, unless this is the first value (count = 0)\n        writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n      }\n      this.count = 1\n      // write first value\n      writeVarInt(this, v - this.s)\n      this.s = v\n    }\n  }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n  /* istanbul ignore else */\n  if (encoder.count > 0) {\n    // flush counter, unless this is the first value (count = 0)\n    // case 1: just a single value. set sign to positive\n    // case 2: write several values. set sign to negative to indicate that there is a length coming\n    writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n    if (encoder.count > 1) {\n      writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n    }\n  }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n  constructor () {\n    this.encoder = new Encoder()\n    /**\n     * @type {number}\n     */\n    this.s = 0\n    this.count = 0\n  }\n\n  /**\n   * @param {number} v\n   */\n  write (v) {\n    if (this.s === v) {\n      this.count++\n    } else {\n      flushUintOptRleEncoder(this)\n      this.count = 1\n      this.s = v\n    }\n  }\n\n  toUint8Array () {\n    flushUintOptRleEncoder(this)\n    return toUint8Array(this.encoder)\n  }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n  constructor () {\n    this.encoder = new Encoder()\n    /**\n     * @type {number}\n     */\n    this.s = 0\n    this.count = 0\n  }\n\n  /**\n   * @param {number} v\n   */\n  write (v) {\n    if (this.s + this.count === v) {\n      this.count++\n    } else {\n      flushUintOptRleEncoder(this)\n      this.count = 1\n      this.s = v\n    }\n  }\n\n  toUint8Array () {\n    flushUintOptRleEncoder(this)\n    return toUint8Array(this.encoder)\n  }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n  if (encoder.count > 0) {\n    //          31 bit making up the diff | wether to write the counter\n    const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n    // flush counter, unless this is the first value (count = 0)\n    // case 1: just a single value. set first bit to positive\n    // case 2: write several values. set first bit to negative to indicate that there is a length coming\n    writeVarInt(encoder.encoder, encodedDiff)\n    if (encoder.count > 1) {\n      writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n    }\n  }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n  constructor () {\n    this.encoder = new Encoder()\n    /**\n     * @type {number}\n     */\n    this.s = 0\n    this.count = 0\n    this.diff = 0\n  }\n\n  /**\n   * @param {number} v\n   */\n  write (v) {\n    if (this.diff === v - this.s) {\n      this.s = v\n      this.count++\n    } else {\n      flushIntDiffOptRleEncoder(this)\n      this.count = 1\n      this.diff = v - this.s\n      this.s = v\n    }\n  }\n\n  toUint8Array () {\n    flushIntDiffOptRleEncoder(this)\n    return toUint8Array(this.encoder)\n  }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n  constructor () {\n    /**\n     * @type {Array<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 * Utility functions to work with buffers (Uint8Array).\n *\n * @module buffer\n */\n\nimport * as string from './string.js'\nimport * as env from './environment.js'\nimport * as encoding from './encoding.js'\nimport * as decoding from './decoding.js'\n\n/**\n * @param {number} len\n */\nexport const createUint8ArrayFromLen = len => new Uint8Array(len)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n * @param {number} byteOffset\n * @param {number} length\n */\nexport const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n */\nexport const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer)\n\n/* istanbul ignore next */\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Browser = bytes => {\n  let s = ''\n  for (let i = 0; i < bytes.byteLength; i++) {\n    s += string.fromCharCode(bytes[i])\n  }\n  // eslint-disable-next-line no-undef\n  return btoa(s)\n}\n\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')\n\n/* istanbul ignore next */\n/**\n * @param {string} s\n * @return {Uint8Array}\n */\nconst fromBase64Browser = s => {\n  // eslint-disable-next-line no-undef\n  const a = atob(s)\n  const bytes = createUint8ArrayFromLen(a.length)\n  for (let i = 0; i < a.length; i++) {\n    bytes[i] = a.charCodeAt(i)\n  }\n  return bytes\n}\n\n/**\n * @param {string} s\n */\nconst fromBase64Node = s => {\n  const buf = Buffer.from(s, 'base64')\n  return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n}\n\n/* istanbul ignore next */\nexport const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node\n\n/* istanbul ignore next */\nexport const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node\n\n/**\n * Copy the content of an Uint8Array view to a new ArrayBuffer.\n *\n * @param {Uint8Array} uint8Array\n * @return {Uint8Array}\n */\nexport const copyUint8Array = uint8Array => {\n  const newBuf = createUint8ArrayFromLen(uint8Array.byteLength)\n  newBuf.set(uint8Array)\n  return newBuf\n}\n\n/**\n * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type.\n * See encoding.writeAny for more information.\n *\n * @param {any} data\n * @return {Uint8Array}\n */\nexport const encodeAny = data => {\n  const encoder = encoding.createEncoder()\n  encoding.writeAny(encoder, data)\n  return encoding.toUint8Array(encoder)\n}\n\n/**\n * Decode an any-encoded value.\n *\n * @param {Uint8Array} buf\n * @return {any}\n */\nexport const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf))\n","/**\n * 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 = new 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 = new decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as binary from './binary.js'\nimport * as math from './math.js'\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n */\nexport class Decoder {\n  /**\n   * @param {Uint8Array} uint8Array Binary data to decode\n   */\n  constructor (uint8Array) {\n    /**\n     * Decoding target.\n     *\n     * @type {Uint8Array}\n     */\n    this.arr = uint8Array\n    /**\n     * Current decoding position.\n     *\n     * @type {number}\n     */\n    this.pos = 0\n  }\n}\n\n/**\n * @function\n * @param {Uint8Array} uint8Array\n * @return {Decoder}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n  const _decoder = createDecoder(decoder.arr)\n  _decoder.pos = newPos\n  return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n *            Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array}\n */\nexport const readUint8Array = (decoder, len) => {\n  const view = buffer.createUint8ArrayViewFromArrayBuffer(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n  decoder.pos += len\n  return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n *            Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n  const uint =\n    decoder.arr[decoder.pos] +\n    (decoder.arr[decoder.pos + 1] << 8)\n  decoder.pos += 2\n  return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n  const uint =\n    (decoder.arr[decoder.pos] +\n    (decoder.arr[decoder.pos + 1] << 8) +\n    (decoder.arr[decoder.pos + 2] << 16) +\n    (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n  decoder.pos += 4\n  return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n  const uint =\n    (decoder.arr[decoder.pos + 3] +\n    (decoder.arr[decoder.pos + 2] << 8) +\n    (decoder.arr[decoder.pos + 1] << 16) +\n    (decoder.arr[decoder.pos] << 24)) >>> 0\n  decoder.pos += 4\n  return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n  decoder.arr[decoder.pos] +\n  (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n  decoder.arr[decoder.pos] +\n  (decoder.arr[decoder.pos + 1] << 8) +\n  (decoder.arr[decoder.pos + 2] << 16) +\n  (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n *  * numbers < 2^7 is stored in one bytlength\n *  * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n  let num = 0\n  let len = 0\n  while (true) {\n    const r = decoder.arr[decoder.pos++]\n    num = num | ((r & binary.BITS7) << len)\n    len += 7\n    if (r < binary.BIT8) {\n      return num >>> 0 // return unsigned number!\n    }\n    /* istanbul ignore if */\n    if (len > 35) {\n      throw new Error('Integer out of range!')\n    }\n  }\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 len = 6\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  while (true) {\n    r = decoder.arr[decoder.pos++]\n    num = num | ((r & binary.BITS7) << len)\n    len += 7\n    if (r < binary.BIT8) {\n      return sign * (num >>> 0)\n    }\n    /* istanbul ignore if */\n    if (len > 41) {\n      throw new Error('Integer out of range!')\n    }\n  }\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 * Read string of variable length\n * * varUint is used to store the length of the string\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 */\nexport const readVarString = 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\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 = diff >> 1\n      this.count = 1\n      if (hasCount) {\n        this.count = readVarUint(this) + 2\n      }\n    }\n    this.s += this.diff\n    this.count--\n    return this.s\n  }\n}\n\nexport class StringDecoder {\n  /**\n   * @param {Uint8Array} uint8Array\n   */\n  constructor (uint8Array) {\n    this.decoder = new UintOptRleDecoder(uint8Array)\n    this.str = readVarString(this.decoder)\n    /**\n     * @type {number}\n     */\n    this.spos = 0\n  }\n\n  /**\n   * @return {string}\n   */\n  read () {\n    const end = this.spos + this.decoder.read()\n    const res = this.str.slice(this.spos, end)\n    this.spos = end\n    return res\n  }\n}\n","import {\n  IncomingHttpHeaders, IncomingMessage, ServerResponse,\n} from 'http'\nimport { URLSearchParams } from 'url'\nimport { Socket } from 'net'\nimport { Awareness } from 'y-protocols/awareness'\nimport Document from './Document'\nimport { Hocuspocus } from './Hocuspocus'\n\nexport enum MessageType {\n  Unknown = -1,\n  Sync = 0,\n  Awareness = 1,\n  Auth = 2,\n  QueryAwareness = 3,\n}\n\n/**\n * State of the WebSocket connection.\n * https://developer.mozilla.org/de/docs/Web/API/WebSocket/readyState\n */\nexport enum WsReadyStates {\n  Connecting = 0,\n  Open = 1,\n  Closing = 2,\n  Closed = 3,\n}\n\nexport interface AwarenessUpdate {\n  added: Array<any>,\n  updated: Array<any>,\n  removed: Array<any>,\n}\n\nexport interface ConnectionConfiguration {\n  readOnly: boolean\n  requiresAuthentication: boolean\n  isAuthenticated: boolean\n}\n\nexport interface Extension {\n  priority?: number,\n  onConfigure?(data: onConfigurePayload): Promise<any>,\n  onListen?(data: onListenPayload): Promise<any>,\n  onUpgrade?(data: onUpgradePayload): Promise<any>,\n  onConnect?(data: onConnectPayload): Promise<any>,\n  onAuthenticate?(data: onAuthenticatePayload): Promise<any>,\n  /**\n   * @deprecated onCreateDocument is deprecated, use onLoadDocument instead\n   */\n  onCreateDocument?(data: onLoadDocumentPayload): Promise<any>,\n  onLoadDocument?(data: onLoadDocumentPayload): Promise<any>,\n  afterLoadDocument?(data: onLoadDocumentPayload): Promise<any>,\n  onChange?(data: onChangePayload): Promise<any>,\n  onStoreDocument?(data: onStoreDocumentPayload): Promise<any>,\n  afterStoreDocument?(data: afterStoreDocumentPayload): Promise<any>,\n  onAwarenessUpdate?(data: onAwarenessUpdatePayload): Promise<any>,\n  onRequest?(data: onRequestPayload): Promise<any>,\n  onDisconnect?(data: onDisconnectPayload): Promise<any>\n  onDestroy?(data: onDestroyPayload): Promise<any>,\n}\n\nexport type Hook =\n  'onConfigure' |\n  'onListen' |\n  'onUpgrade' |\n  'onConnect' |\n  'onAuthenticate' |\n  /**\n   * @deprecated onCreateDocument is deprecated, use onLoadDocument instead\n   */\n  'onCreateDocument' |\n  'onLoadDocument' |\n  'afterLoadDocument' |\n  'onChange' |\n  'onStoreDocument' |\n  'afterStoreDocument' |\n  'onAwarenessUpdate' |\n  'onRequest' |\n  'onDisconnect' |\n  'onDestroy'\n\nexport interface Configuration extends Extension {\n  /**\n   * A name for the instance, used for logging.\n   */\n  name: string | null,\n  /**\n   * A list of hocuspocus extenions.\n   */\n  extensions: Array<Extension>,\n  /**\n   * The port which the server listens on.\n   */\n  port: number | null,\n  /**\n   * Defines in which interval the server sends a ping, and closes the connection when no pong is sent back.\n   */\n  timeout: number,\n  /**\n   * Debounces the call of the `onStoreDocument` hook for the given amount of time in ms.\n   * Otherwise every single update would be persisted.\n   */\n  debounce: number,\n  /**\n   * Makes sure to call `onStoreDocument` at least in the given amount of time (ms).\n   */\n  maxDebounce: number\n  /**\n   * By default, the servers show a start screen. If passed false, the server will start quietly.\n   */\n  quiet: boolean,\n  /**\n   * Function which returns the (customized) document name based on the request\n   */\n  getDocumentName?(data: {\n    documentName: string,\n    request: IncomingMessage,\n    requestParameters: URLSearchParams,\n  }): string | Promise<string>,\n}\n\nexport interface onAuthenticatePayload {\n  documentName: string,\n  instance: Hocuspocus,\n  requestHeaders: IncomingHttpHeaders,\n  requestParameters: URLSearchParams,\n  socketId: string,\n  token: string,\n  connection: ConnectionConfiguration\n}\n\nexport interface onConnectPayload {\n  documentName: string,\n  instance: Hocuspocus,\n  request: IncomingMessage,\n  requestHeaders: IncomingHttpHeaders,\n  requestParameters: URLSearchParams,\n  socketId: string,\n  connection: ConnectionConfiguration\n}\n\nexport interface onLoadDocumentPayload {\n  context: any,\n  document: Document,\n  documentName: string,\n  instance: Hocuspocus,\n  requestHeaders: IncomingHttpHeaders,\n  requestParameters: URLSearchParams,\n  socketId: string,\n  connection: ConnectionConfiguration\n}\n\nexport interface afterLoadDocumentPayload {\n  context: any,\n  document: Document,\n  documentName: string,\n  instance: Hocuspocus,\n  requestHeaders: IncomingHttpHeaders,\n  requestParameters: URLSearchParams,\n  socketId: string,\n  connection: ConnectionConfiguration\n}\n\nexport interface onChangePayload {\n  clientsCount: number,\n  context: any,\n  document: Document,\n  documentName: string,\n  instance: Hocuspocus,\n  requestHeaders: IncomingHttpHeaders,\n  requestParameters: URLSearchParams,\n  update: Uint8Array,\n  socketId: string,\n}\n\nexport interface onStoreDocumentPayload {\n  clientsCount: number,\n  context: any,\n  document: Document,\n  documentName: string,\n  instance: Hocuspocus,\n  requestHeaders: IncomingHttpHeaders,\n  requestParameters: URLSearchParams,\n  socketId: string,\n}\n\nexport interface afterStoreDocumentPayload extends onStoreDocumentPayload {}\n\nexport interface onAwarenessUpdatePayload {\n  clientsCount: number,\n  context: any,\n  document: Document,\n  documentName: string,\n  instance: Hocuspocus,\n  requestHeaders: IncomingHttpHeaders,\n  requestParameters: URLSearchParams,\n  update: Uint8Array,\n  socketId: string,\n  added: number[],\n  updated: number[],\n  removed: number[],\n  awareness: Awareness,\n  states: any[],\n}\n\nexport interface storePayload extends onStoreDocumentPayload {\n  state: Buffer,\n}\n\nexport interface onDisconnectPayload {\n  clientsCount: number,\n  context: any,\n  document: Document,\n  documentName: string,\n  instance: Hocuspocus,\n  requestHeaders: IncomingHttpHeaders,\n  requestParameters: URLSearchParams,\n  socketId: string,\n}\n\nexport interface onRequestPayload {\n  request: IncomingMessage,\n  response: ServerResponse,\n  instance: Hocuspocus,\n}\n\nexport interface onUpgradePayload {\n  head: any,\n  request: IncomingMessage,\n  socket: Socket,\n  instance: Hocuspocus,\n}\n\nexport interface onListenPayload {\n  port: number,\n}\n\nexport interface onDestroyPayload {\n  instance: Hocuspocus,\n}\n\nexport interface onConfigurePayload {\n  configuration: Configuration,\n  version: string,\n  yjsVersion: string,\n  instance: Hocuspocus,\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    /* istanbul 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 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 * Utility module to work with Arrays.\n *\n * @module array\n */\n\n/**\n * Return the last element of an array. The element must exist\n *\n * @template L\n * @param {Array<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 ITEM\n *\n * @param {Array<ITEM>} arr\n * @param {function(ITEM, number, Array<ITEM>):boolean} f\n * @return {boolean}\n */\nexport const every = (arr, f) => arr.every(f)\n\n/**\n * True iff condition holds on some element in the Array.\n *\n * @function\n * @template S\n * @param {Array<S>} arr\n * @param {function(S, number, Array<S>):boolean} f\n * @return {boolean}\n */\nexport const some = (arr, f) => arr.some(f)\n\n/**\n * @template ELEM\n *\n * @param {Array<ELEM>} a\n * @param {Array<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 => arr.reduce((acc, val) => acc.concat(val), [])\n","/**\n * Observable class prototype.\n *\n * @module observable\n */\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as array from './array.js'\n\n/**\n * Handles named events.\n *\n * @template N\n */\nexport class Observable {\n  constructor () {\n    /**\n     * Some desc.\n     * @type {Map<N, 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","/**\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 * 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 * @param {Object<string,any>} obj\n * @param {function(any,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 * @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 * @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 * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n  for (const key in obj) {\n    if (f(obj[key], key)) {\n      return true\n    }\n  }\n  return false\n}\n\n/**\n * @param {Object<string,any>} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n  for (const key in obj) {\n    if (!f(obj[key], key)) {\n      return false\n    }\n  }\n  return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object<string,any>} a\n * @param {Object<string,any>} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val))\n","/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array<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 && ((a instanceof Array && array.equalFlat(a, /** @type {Array<T>} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n  if (a == null || b == null) {\n    return equalityStrict(a, b)\n  }\n  if (a.constructor !== b.constructor) {\n    return false\n  }\n  if (a === b) {\n    return true\n  }\n  switch (a.constructor) {\n    case ArrayBuffer:\n      a = new Uint8Array(a)\n      b = new Uint8Array(b)\n    // eslint-disable-next-line no-fallthrough\n    case Uint8Array: {\n      if (a.byteLength !== b.byteLength) {\n        return false\n      }\n      for (let i = 0; i < a.length; i++) {\n        if (a[i] !== b[i]) {\n          return false\n        }\n      }\n      break\n    }\n    case Set: {\n      if (a.size !== b.size) {\n        return false\n      }\n      for (const value of a) {\n        if (!b.has(value)) {\n          return false\n        }\n      }\n      break\n    }\n    case Map: {\n      if (a.size !== b.size) {\n        return false\n      }\n      for (const key of a.keys()) {\n        if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n          return false\n        }\n      }\n      break\n    }\n    case Object:\n      if (object.length(a) !== object.length(b)) {\n        return false\n      }\n      for (const key in a) {\n        if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n          return false\n        }\n      }\n      break\n    case Array:\n      if (a.length !== b.length) {\n        return false\n      }\n      for (let i = 0; i < a.length; i++) {\n        if (!equalityDeep(a[i], b[i])) {\n          return false\n        }\n      }\n      break\n    default:\n      return false\n  }\n  return true\n}\n","/**\n * @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","/**\n * Mutual exclude for JavaScript.\n *\n * @module mutex\n */\n\n/**\n * @callback mutex\n * @param {function():void} cb Only executed when this mutex is not in the current stack\n * @param {function():void} [elseCb] Executed when this mutex is in the current stack\n */\n\n/**\n * Creates a mutual exclude function with the following property:\n *\n * ```js\n * const mutex = createMutex()\n * mutex(() => {\n *   // This function is immediately executed\n *   mutex(() => {\n *     // This function is not executed, as the mutex is already active.\n *   })\n * })\n * ```\n *\n * @return {mutex} A mutual exclude function\n * @public\n */\nexport const createMutex = () => {\n  let token = true\n  return (f, g) => {\n    if (token) {\n      token = false\n      try {\n        f()\n      } finally {\n        token = true\n      }\n    } else if (g !== undefined) {\n      g()\n    }\n  }\n}\n","/**\n * @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 shoul only reply to requests, and not initiate them.\n * Therefore it is necesarry that the client initiates the sync.\n *\n * Construction of a message:\n * [messageType : varUint, message definition..]\n *\n * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!\n *\n * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)\n */\n\nexport const messageYjsSyncStep1 = 0\nexport const messageYjsSyncStep2 = 1\nexport const messageYjsUpdate = 2\n\n/**\n * Create a sync step 1 message based on the state of the current shared document.\n *\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n */\nexport const writeSyncStep1 = (encoder, doc) => {\n  encoding.writeVarUint(encoder, messageYjsSyncStep1)\n  const sv = Y.encodeStateVector(doc)\n  encoding.writeVarUint8Array(encoder, sv)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n * @param {Uint8Array} [encodedStateVector]\n */\nexport const writeSyncStep2 = (encoder, doc, encodedStateVector) => {\n  encoding.writeVarUint(encoder, messageYjsSyncStep2)\n  encoding.writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector))\n}\n\n/**\n * Read SyncStep1 message and reply with SyncStep2.\n *\n * @param {decoding.Decoder} decoder The reply to the received message\n * @param {encoding.Encoder} encoder The received message\n * @param {Y.Doc} doc\n */\nexport const readSyncStep1 = (decoder, encoder, doc) =>\n  writeSyncStep2(encoder, doc, decoding.readVarUint8Array(decoder))\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin) => {\n  try {\n    Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n  } catch (error) {\n    // This catches errors that are thrown by event handlers\n    console.error('Caught error while handling a Yjs update', error)\n  }\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Uint8Array} update\n */\nexport const writeUpdate = (encoder, update) => {\n  encoding.writeVarUint(encoder, messageYjsUpdate)\n  encoding.writeVarUint8Array(encoder, update)\n}\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readUpdate = readSyncStep2\n\n/**\n * @param {decoding.Decoder} decoder A message received from another client\n * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => {\n  const messageType = decoding.readVarUint(decoder)\n  switch (messageType) {\n    case messageYjsSyncStep1:\n      readSyncStep1(decoder, encoder, doc)\n      break\n    case messageYjsSyncStep2:\n      readSyncStep2(decoder, doc, transactionOrigin)\n      break\n    case messageYjsUpdate:\n      readUpdate(decoder, doc, transactionOrigin)\n      break\n    default:\n      throw new Error('Unknown message type')\n  }\n  return messageType\n}\n","import {\n  createEncoder,\n  Encoder,\n  toUint8Array,\n  writeVarUint,\n  writeVarUint8Array,\n} from 'lib0/encoding'\nimport { writeSyncStep1, writeUpdate } from 'y-protocols/sync'\nimport { Awareness, encodeAwarenessUpdate } from 'y-protocols/awareness'\n\nimport { writeAuthenticated, writePermissionDenied } from '@hocuspocus/common'\nimport { MessageType } from './types'\nimport Document from './Document'\n\nexport class OutgoingMessage {\n\n  encoder: Encoder\n\n  type?: number\n\n  category?: string\n\n  constructor() {\n    this.encoder = createEncoder()\n  }\n\n  createSyncMessage(): OutgoingMessage {\n    this.type = MessageType.Sync\n\n    writeVarUint(this.encoder, MessageType.Sync)\n\n    return this\n  }\n\n  createAwarenessUpdateMessage(awareness: Awareness, changedClients?: Array<any>): OutgoingMessage {\n    this.type = MessageType.Awareness\n    this.category = 'Update'\n\n    const message = encodeAwarenessUpdate(\n      awareness,\n      changedClients || Array.from(awareness.getStates().keys()),\n    )\n\n    writeVarUint(this.encoder, MessageType.Awareness)\n    writeVarUint8Array(this.encoder, message)\n\n    return this\n  }\n\n  writeQueryAwareness(): OutgoingMessage {\n    this.type = MessageType.QueryAwareness\n    this.category = 'Update'\n\n    writeVarUint(this.encoder, MessageType.QueryAwareness)\n\n    return this\n  }\n\n  writeAuthenticated(): OutgoingMessage {\n    this.type = MessageType.Auth\n    this.category = 'Authenticated'\n\n    writeVarUint(this.encoder, MessageType.Auth)\n    writeAuthenticated(this.encoder)\n\n    return this\n  }\n\n  writePermissionDenied(reason: string): OutgoingMessage {\n    this.type = MessageType.Auth\n    this.category = 'PermissionDenied'\n\n    writeVarUint(this.encoder, MessageType.Auth)\n    writePermissionDenied(this.encoder, reason)\n\n    return this\n  }\n\n  writeFirstSyncStepFor(document: Document): OutgoingMessage {\n    this.category = 'SyncStep1'\n\n    writeSyncStep1(this.encoder, document)\n\n    return this\n  }\n\n  writeUpdate(update: Uint8Array): OutgoingMessage {\n    this.category = 'Update'\n\n    writeUpdate(this.encoder, update)\n\n    return this\n  }\n\n  toUint8Array(): Uint8Array {\n    return toUint8Array(this.encoder)\n  }\n}\n","// import * as time from 'lib0/time'\nimport { MessageType } from './types'\n\nexport class MessageLogger {\n  logs: any[] = []\n\n  listen = false\n\n  output = false\n\n  enable() {\n    this.flush()\n\n    this.listen = true\n  }\n\n  disable() {\n    this.listen = false\n  }\n\n  verbose() {\n    this.output = true\n  }\n\n  quiet() {\n    this.output = false\n  }\n\n  log(message: any) {\n    if (!this.listen) {\n      return this\n    }\n\n    const item = {\n      ...message,\n      type: MessageType[message.type],\n      // time: time.getUnixTime(),\n    }\n\n    this.logs.push(item)\n\n    if (this.output) {\n      console.log('[DEBUGGER]', item.direction === 'in' ? 'IN –>' : 'OUT <–', `${item.type}/${item.category}`)\n    }\n\n    return this\n  }\n\n  flush() {\n    this.logs = []\n\n    return this\n  }\n\n  get() {\n    return {\n      logs: this.logs,\n    }\n  }\n}\n\nexport const Debugger = new MessageLogger()\n","import WebSocket from 'ws'\nimport { Awareness, removeAwarenessStates, applyAwarenessUpdate } from 'y-protocols/awareness'\nimport { applyUpdate, Doc, encodeStateAsUpdate } from 'yjs'\nimport { mutex, createMutex } from 'lib0/mutex.js'\nimport { AwarenessUpdate } from './types'\nimport Connection from './Connection'\nimport { OutgoingMessage } from './OutgoingMessage'\nimport { Debugger, MessageLogger } from './Debugger'\n\nexport class Document extends Doc {\n\n  awareness: Awareness\n\n  callbacks = {\n    // eslint-disable-next-line @typescript-eslint/no-empty-function\n    onUpdate: (document: Document, connection: Connection, update: Uint8Array) => {},\n  }\n\n  connections: Map<WebSocket, {\n    clients: Set<any>,\n    connection: Connection\n  }> = new Map()\n\n  name: string\n\n  mux: mutex\n\n  debugger: MessageLogger = Debugger\n\n  /**\n   * Constructor.\n   */\n  constructor(name: string) {\n    super({ gc: true })\n\n    this.name = name\n    this.mux = createMutex()\n\n    this.awareness = new Awareness(this)\n    this.awareness.setLocalState(null)\n\n    this.awareness.on('update', this.handleAwarenessUpdate.bind(this))\n    this.on('update', this.handleUpdate.bind(this))\n  }\n\n  /**\n   * Check if the Document is empty\n   */\n  isEmpty(fieldName: string): boolean {\n    // eslint-disable-next-line no-underscore-dangle\n    return !this.get(fieldName)._start\n  }\n\n  /**\n   * Merge the given document(s) into this one\n   */\n  merge(documents: Doc|Array<Doc>): Document {\n    (Array.isArray(documents) ? documents : [documents]).forEach(document => {\n      applyUpdate(this, encodeStateAsUpdate(document))\n    })\n\n    return this\n  }\n\n  /**\n   * Set a callback that will be triggered when the document is updated\n   */\n  onUpdate(callback: (document: Document, connection: Connection, update: Uint8Array) => void): Document {\n    this.callbacks.onUpdate = callback\n\n    return this\n  }\n\n  /**\n   * Register a connection and a set of clients on this document keyed by the\n   * underlying websocket connection\n   */\n  addConnection(connection: Connection): Document {\n    this.connections.set(connection.webSocket, {\n      clients: new Set(),\n      connection,\n    })\n\n    return this\n  }\n\n  /**\n   * Is the given connection registered on this document\n   */\n  hasConnection(connection: Connection): boolean {\n    return this.connections.has(connection.webSocket)\n  }\n\n  /**\n   * Remove the given connection from this document\n   */\n  removeConnection(connection: Connection): Document {\n    removeAwarenessStates(\n      this.awareness,\n      Array.from(this.getClients(connection.webSocket)),\n      null,\n    )\n\n    this.connections.delete(connection.webSocket)\n\n    return this\n  }\n\n  /**\n   * Get the number of active connections for this document\n   */\n  getConnectionsCount(): number {\n    return this.connections.size\n  }\n\n  /**\n   * Get an array of registered connections\n   */\n  getConnections(): Array<Connection> {\n    return Array.from(this.connections.values()).map(data => data.connection)\n  }\n\n  /**\n   * Get the client ids for the given connection instance\n   */\n  getClients(connectionInstance: WebSocket): Set<any> {\n    const connection = this.connections.get(connectionInstance)\n\n    return connection?.clients === undefined ? new Set() : connection.clients\n  }\n\n  /**\n   * Has the document awareness states\n   */\n  hasAwarenessStates(): boolean {\n    return this.awareness.getStates().size > 0\n  }\n\n  /**\n   * Apply the given awareness update\n   */\n  applyAwarenessUpdate(connection: Connection, update: Uint8Array): Document {\n    applyAwarenessUpdate(\n      this.awareness,\n      update,\n      connection.webSocket,\n    )\n\n    return this\n  }\n\n  /**\n   * Handle an awareness update and sync changes to clients\n   * @private\n   */\n  private handleAwarenessUpdate(\n    { added, updated, removed }: AwarenessUpdate,\n    connectionInstance: WebSocket,\n  ): Document {\n    const changedClients = added.concat(updated, removed)\n\n    if (connectionInstance !== null) {\n      const connection = this.connections.get(connectionInstance)\n\n      if (connection) {\n        added.forEach((clientId: any) => connection.clients.add(clientId))\n        removed.forEach((clientId: any) => connection.clients.delete(clientId))\n      }\n    }\n\n    this.getConnections().forEach(connection => {\n      const awarenessMessage = new OutgoingMessage()\n        .createAwarenessUpdateMessage(this.awareness, changedClients)\n\n      this.debugger.log({\n        direction: 'out',\n        type: awarenessMessage.type,\n        category: awarenessMessage.category,\n      })\n\n      connection.send(\n        awarenessMessage.toUint8Array(),\n      )\n    })\n\n    return this\n  }\n\n  /**\n   * Handle an updated document and sync changes to clients\n   */\n  private handleUpdate(update: Uint8Array, connection: Connection): Document {\n    this.callbacks.onUpdate(this, connection, update)\n\n    const message = new OutgoingMessage()\n      .createSyncMessage()\n      .writeUpdate(update)\n\n    this.getConnections().forEach(connection => {\n      this.debugger.log({\n        direction: 'out',\n        type: message.type,\n        category: message.category,\n      })\n\n      connection.send(\n        message.toUint8Array(),\n      )\n    })\n\n    return this\n  }\n}\n\nexport default Document\n","import {\n  createDecoder,\n  Decoder,\n  readVarUint,\n  readVarUint8Array,\n} from 'lib0/decoding'\nimport {\n  createEncoder,\n  Encoder,\n  toUint8Array,\n  writeVarUint,\n  length,\n} from 'lib0/encoding'\nimport { MessageType } from './types'\n\nexport class IncomingMessage {\n  /**\n   * Access to the received message.\n   */\n  decoder: Decoder\n\n  /**\n   * Access to the reply.\n   */\n  encoder: Encoder\n\n  constructor(input: any) {\n    if (!(input instanceof Uint8Array)) {\n      input = new Uint8Array(input)\n    }\n\n    this.encoder = createEncoder()\n    this.decoder = createDecoder(input)\n  }\n\n  readVarUint8Array() {\n    return readVarUint8Array(this.decoder)\n  }\n\n  readVarUint() {\n    return readVarUint(this.decoder)\n  }\n\n  toUint8Array() {\n    return toUint8Array(this.encoder)\n  }\n\n  writeVarUint(type: MessageType) {\n    writeVarUint(this.encoder, type)\n  }\n\n  get length(): number {\n    return length(this.encoder)\n  }\n}\n","import {\n  messageYjsSyncStep1,\n  messageYjsSyncStep2,\n  messageYjsUpdate,\n  readSyncStep1,\n  readSyncStep2,\n  readUpdate,\n} from 'y-protocols/sync'\nimport { applyAwarenessUpdate, Awareness } from 'y-protocols/awareness'\nimport { MessageType } from './types'\nimport Connection from './Connection'\nimport { IncomingMessage } from './IncomingMessage'\nimport { OutgoingMessage } from './OutgoingMessage'\nimport { Debugger, MessageLogger } from './Debugger'\nimport Document from './Document'\n\nexport class MessageReceiver {\n\n  message: IncomingMessage\n\n  debugger: MessageLogger = Debugger\n\n  constructor(message: IncomingMessage) {\n    this.message = message\n  }\n\n  public apply(document: Document, connection?: Connection, reply?: (message: Uint8Array) => void) {\n    const { message } = this\n    const type = message.readVarUint()\n\n    switch (type) {\n      case MessageType.Sync:\n        message.writeVarUint(MessageType.Sync)\n        this.readSyncMessage(message, document, connection, reply)\n\n        if (message.length > 1) {\n          if (reply) {\n            reply(message.toUint8Array())\n          } else if (connection) {\n            // TODO: We should log this, shouldn’t we?\n            // this.debugger.log({\n            //   direction: 'out',\n            //   type: MessageType.Awareness,\n            //   category: 'Update',\n            // })\n            connection.send(message.toUint8Array())\n          }\n        }\n\n        break\n      case MessageType.Awareness:\n        this.debugger.log({\n          direction: 'in',\n          type: MessageType.Awareness,\n          category: 'Update',\n        })\n\n        applyAwarenessUpdate(document.awareness, message.readVarUint8Array(), connection)\n\n        break\n      case MessageType.QueryAwareness:\n\n        this.applyQueryAwarenessMessage(document.awareness, reply)\n\n        break\n      default:\n        // Do nothing\n    }\n  }\n\n  readSyncMessage(message: IncomingMessage, document: Document, connection?: Connection, reply?: (message: Uint8Array) => void) {\n    const type = message.readVarUint()\n\n    switch (type) {\n      case messageYjsSyncStep1: {\n        this.debugger.log({\n          direction: 'in',\n          type: MessageType.Sync,\n          category: 'SyncStep1',\n        })\n\n        readSyncStep1(message.decoder, message.encoder, document)\n\n        // When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1.\n        this.debugger.log({\n          direction: 'out',\n          type: MessageType.Sync,\n          category: 'SyncStep2',\n        })\n\n        const syncMessage = (new OutgoingMessage()\n          .createSyncMessage()\n          .writeFirstSyncStepFor(document))\n\n        if (reply) {\n          reply(syncMessage.toUint8Array())\n        } else if (connection) {\n          this.debugger.log({\n            direction: 'out',\n            type: MessageType.Sync,\n            category: 'SyncStep1',\n          })\n\n          connection.send(syncMessage.toUint8Array())\n        }\n\n        break\n      }\n      case messageYjsSyncStep2:\n        this.debugger.log({\n          direction: 'in',\n          type: MessageType.Sync,\n          category: 'SyncStep2',\n        })\n\n        if (connection?.readOnly) {\n          break\n        }\n\n        readSyncStep2(message.decoder, document, connection)\n        break\n      case messageYjsUpdate:\n        this.debugger.log({\n          direction: 'in',\n          type: MessageType.Sync,\n          category: 'Update',\n        })\n\n        if (connection?.readOnly) {\n          break\n        }\n\n        readUpdate(message.decoder, document, connection)\n        break\n      default:\n        throw new Error(`Received a message with an unknown type: ${type}`)\n    }\n\n    return type\n  }\n\n  applyQueryAwarenessMessage(awareness: Awareness, reply?: (message: Uint8Array) => void) {\n    const message = new OutgoingMessage()\n      .createAwarenessUpdateMessage(awareness)\n\n    if (reply) {\n      reply(message.toUint8Array())\n    }\n\n    // TODO: We should add support for WebSocket connections, too, right?\n    // this.debugger.log({\n    //   direction: 'out',\n    //   type: MessageType.Sync,\n    //   category: 'SyncStep1',\n    // })\n\n    // connection.send(syncMessage.toUint8Array())\n  }\n}\n","import AsyncLock from 'async-lock'\nimport WebSocket from 'ws'\nimport { IncomingMessage as HTTPIncomingMessage } from 'http'\nimport { CloseEvent, ConnectionTimeout } from '@hocuspocus/common'\nimport Document from './Document'\nimport { IncomingMessage } from './IncomingMessage'\nimport { WsReadyStates } from './types'\nimport { OutgoingMessage } from './OutgoingMessage'\nimport { MessageReceiver } from './MessageReceiver'\nimport { Debugger, MessageLogger } from './Debugger'\n\nexport class Connection {\n\n  webSocket: WebSocket\n\n  context: any\n\n  document: Document\n\n  pingInterval: NodeJS.Timeout\n\n  pongReceived = true\n\n  request: HTTPIncomingMessage\n\n  timeout: number\n\n  callbacks: any = {\n    onClose: (document: Document) => null,\n  }\n\n  socketId: string\n\n  lock: AsyncLock\n\n  readOnly: Boolean\n\n  debugger: MessageLogger = Debugger\n\n  /**\n   * Constructor.\n   */\n  constructor(\n    connection: WebSocket,\n    request: HTTPIncomingMessage,\n    document: Document,\n    timeout: number,\n    socketId: string,\n    context: any,\n    readOnly = false,\n  ) {\n    this.webSocket = connection\n    this.context = context\n    this.document = document\n    this.request = request\n    this.timeout = timeout\n    this.socketId = socketId\n    this.readOnly = readOnly\n\n    this.lock = new AsyncLock()\n\n    this.webSocket.binaryType = 'arraybuffer'\n    this.document.addConnection(this)\n\n    this.pingInterval = setInterval(this.check.bind(this), this.timeout)\n\n    this.webSocket.on('close', this.close.bind(this))\n    this.webSocket.on('message', this.handleMessage.bind(this))\n    this.webSocket.on('pong', () => { this.pongReceived = true })\n\n    this.sendCurrentAwareness()\n  }\n\n  /**\n   * Set a callback that will be triggered when the connection is closed\n   */\n  onClose(callback: (document: Document) => void): Connection {\n    this.callbacks.onClose = callback\n\n    return this\n  }\n\n  /**\n   * Send the given message\n   */\n  send(message: any): void {\n    if (\n      this.webSocket.readyState === WsReadyStates.Closing\n      || this.webSocket.readyState === WsReadyStates.Closed\n    ) {\n      this.close()\n    }\n\n    try {\n      this.webSocket.send(message, (error: any) => {\n        if (error != null) this.close()\n      })\n    } catch (exception) {\n      this.close()\n    }\n  }\n\n  /**\n   * Graceful wrapper around the WebSocket close method.\n   */\n  close(event?: CloseEvent): void {\n    this.lock.acquire('close', (done: Function) => {\n\n      if (this.pingInterval) {\n        clearInterval(this.pingInterval)\n      }\n\n      if (!this.document.hasConnection(this)) {\n        return\n      }\n\n      this.document.removeConnection(this)\n      this.callbacks.onClose(this.document)\n      this.webSocket.close(event?.code, event?.reason)\n\n      done()\n    })\n  }\n\n  /**\n   * Check if pong was received and close the connection otherwise\n   * @private\n   */\n  private check(): void {\n    if (!this.pongReceived) {\n      return this.close(ConnectionTimeout)\n    }\n\n    if (this.document.hasConnection(this)) {\n      this.pongReceived = false\n\n      try {\n        this.webSocket.ping()\n      } catch (error) {\n        this.close(ConnectionTimeout)\n      }\n    }\n  }\n\n  /**\n   * Send the current document awareness to the client, if any\n   * @private\n   */\n  private sendCurrentAwareness(): void {\n    if (!this.document.hasAwarenessStates()) {\n      return\n    }\n\n    const awarenessMessage = new OutgoingMessage()\n      .createAwarenessUpdateMessage(this.document.awareness)\n\n    this.debugger.log({\n      direction: 'out',\n      type: awarenessMessage.type,\n      category: awarenessMessage.category,\n    })\n\n    this.send(awarenessMessage.toUint8Array())\n  }\n\n  /**\n   * Handle an incoming message\n   * @private\n   */\n  private handleMessage(data: Iterable<number>): void {\n    new MessageReceiver(\n      new IncomingMessage(data),\n    ).apply(this.document, this)\n  }\n\n  /**\n   * Get the underlying connection instance\n   * @deprecated\n   */\n  get instance(): WebSocket {\n    console.warn('connection.instance is deprecated, use `connection.webSocket` instead.')\n\n    return this.webSocket\n  }\n\n  /**\n   * Get the underlying connection instance\n   * @deprecated\n   */\n  public get connection(): WebSocket {\n    console.warn('connection.connection is deprecated, use `connection.webSocket` instead.')\n\n    return this.webSocket\n  }\n}\n\nexport default Connection\n","import * as decoding from 'lib0/decoding'\nimport WebSocket, { AddressInfo, WebSocketServer } from 'ws'\nimport { createServer, IncomingMessage, Server as HTTPServer } from 'http'\nimport { Doc, encodeStateAsUpdate, applyUpdate } from 'yjs'\nimport { URLSearchParams } from 'url'\nimport { v4 as uuid } from 'uuid'\nimport kleur from 'kleur'\nimport { ResetConnection, Unauthorized, Forbidden } from '@hocuspocus/common'\nimport { awarenessStatesToArray } from '@hocuspocus/provider'\nimport {\n  MessageType,\n  Configuration,\n  ConnectionConfiguration,\n  WsReadyStates,\n  Hook,\n  AwarenessUpdate,\n} from './types'\nimport Document from './Document'\nimport Connection from './Connection'\nimport { OutgoingMessage } from './OutgoingMessage'\nimport meta from '../package.json'\nimport { Debugger, MessageLogger } from './Debugger'\nimport { onListenPayload } from '.'\n\nexport const defaultConfiguration = {\n  name: null,\n  port: 80,\n  timeout: 30000,\n  debounce: 2000,\n  maxDebounce: 10000,\n  quiet: false,\n}\n\nconst defaultOnCreateDocument = () => new Promise(r => r(null))\n\n/**\n * Hocuspocus Server\n */\nexport class Hocuspocus {\n  configuration: Configuration = {\n    ...defaultConfiguration,\n    extensions: [],\n    onConfigure: () => new Promise(r => r(null)),\n    onListen: () => new Promise(r => r(null)),\n    onUpgrade: () => new Promise(r => r(null)),\n    onConnect: () => new Promise(r => r(null)),\n    onChange: () => new Promise(r => r(null)),\n    onCreateDocument: defaultOnCreateDocument,\n    onLoadDocument: () => new Promise(r => r(null)),\n    onStoreDocument: () => new Promise(r => r(null)),\n    afterStoreDocument: () => new Promise(r => r(null)),\n    onAwarenessUpdate: () => new Promise(r => r(null)),\n    onRequest: () => new Promise(r => r(null)),\n    onDisconnect: () => new Promise(r => r(null)),\n    onDestroy: () => new Promise(r => r(null)),\n  }\n\n  documents: Map<string, Document> = new Map()\n\n  httpServer?: HTTPServer\n\n  webSocketServer?: WebSocketServer\n\n  debugger: MessageLogger = Debugger\n\n  constructor(configuration?: Partial<Configuration>) {\n    if (configuration) {\n      this.configure(configuration)\n    }\n  }\n\n  /**\n   * Configure the server\n   */\n  configure(configuration: Partial<Configuration>): Hocuspocus {\n    this.configuration = {\n      ...this.configuration,\n      ...configuration,\n    }\n\n    /**\n     * The `onCreateDocument` hook has been renamed to `onLoadDocument`.\n     * We’ll keep this workaround to support the deprecated hook for a while, but output a warning.\n     */\n    let onLoadDocument\n    if (this.configuration.onCreateDocument !== defaultOnCreateDocument) {\n      console.warn('[hocuspocus warn]: The onCreateDocument hook has been renamed. Use the onLoadDocument hook instead.')\n      onLoadDocument = this.configuration.onCreateDocument\n    } else {\n      onLoadDocument = this.configuration.onLoadDocument\n    }\n\n    this.configuration.extensions.sort((a, b) => {\n      const one = typeof a.priority === 'undefined' ? 100 : a.priority\n      const two = typeof b.priority === 'undefined' ? 100 : b.priority\n\n      if (one > two) {\n        return -1\n      }\n\n      if (one < two) {\n        return 1\n      }\n\n      return 0\n    })\n\n    this.configuration.extensions.push({\n      onConfigure: this.configuration.onConfigure,\n      onListen: this.configuration.onListen,\n      onUpgrade: this.configuration.onUpgrade,\n      onConnect: this.configuration.onConnect,\n      onAuthenticate: this.configuration.onAuthenticate,\n      onLoadDocument,\n      onChange: this.configuration.onChange,\n      onStoreDocument: this.configuration.onStoreDocument,\n      afterStoreDocument: this.configuration.afterStoreDocument,\n      onAwarenessUpdate: this.configuration.onAwarenessUpdate,\n      onRequest: this.configuration.onRequest,\n      onDisconnect: this.configuration.onDisconnect,\n      onDestroy: this.configuration.onDestroy,\n    })\n\n    this.hooks('onConfigure', {\n      configuration: this.configuration,\n      version: meta.version,\n      yjsVersion: null,\n      instance: this,\n    })\n\n    return this\n  }\n\n  get requiresAuthentication(): boolean {\n    return !!this.configuration.extensions.find(extension => {\n      return extension.onAuthenticate !== undefined\n    })\n  }\n\n  /**\n   * Start the server\n   */\n  async listen(\n    portOrCallback: number | ((data: onListenPayload) => Promise<any>) | null = null,\n    callback: any = null,\n  ): Promise<Hocuspocus> {\n    if (typeof portOrCallback === 'number') {\n      this.configuration.port = portOrCallback\n    }\n\n    if (typeof portOrCallback === 'function') {\n      this.configuration.extensions.push({\n        onListen: portOrCallback,\n      })\n    }\n\n    if (typeof callback === 'function') {\n      this.configuration.extensions.push({\n        onListen: callback,\n      })\n    }\n\n    const webSocketServer = new WebSocketServer({ noServer: true })\n\n    webSocketServer.on('connection', async (incoming: WebSocket, request: IncomingMessage) => {\n      this.handleConnection(incoming, request, await this.getDocumentNameFromRequest(request))\n    })\n\n    const server = createServer((request, response) => {\n      this.hooks('onRequest', { request, response, instance: this })\n        .then(() => {\n          // default response if all prior hooks don't interfere\n          response.writeHead(200, { 'Content-Type': 'text/plain' })\n          response.end('OK')\n        })\n        .catch(error => {\n          // if a hook rejects and the error is empty, do nothing\n          // this is only meant to prevent later hooks and the\n          // default handler to do something. if a error is present\n          // just rethrow it\n          if (error) {\n            throw error\n          }\n        })\n    })\n\n    server.on('upgrade', (request, socket, head) => {\n      this.hooks('onUpgrade', {\n        request, socket, head, instance: this,\n      })\n        .then(() => {\n          // let the default websocket server handle the connection if\n          // prior hooks don't interfere\n          // TODO: Argument of type 'Duplex' is not assignable to parameter of type 'Socket'.\n          // @ts-ignore\n          webSocketServer.handleUpgrade(request, socket, head, ws => {\n            webSocketServer.emit('connection', ws, request)\n          })\n        })\n        .catch(error => {\n          // if a hook rejects and the error is empty, do nothing\n          // this is only meant to prevent later hooks and the\n          // default handler to do something. if a error is present\n          // just rethrow it\n          if (error) {\n            throw error\n          }\n        })\n    })\n\n    this.httpServer = server\n    this.webSocketServer = webSocketServer\n\n    return new Promise((resolve: Function, reject: Function) => {\n      server.listen(this.configuration.port, () => {\n        if (!this.configuration.quiet && process.env.NODE_ENV !== 'testing') {\n          this.showStartScreen()\n        }\n\n        this.hooks('onListen', { port: this.address.port })\n          .then(() => resolve(this))\n          .catch(error => reject(error))\n      })\n    })\n  }\n\n  get address(): AddressInfo {\n    return (this.httpServer?.address() || {\n      port: this.configuration.port,\n      address: '127.0.0.1',\n      family: 'IPv4',\n    }) as AddressInfo\n  }\n\n  get URL(): string {\n    return `127.0.0.1:${this.address.port}`\n  }\n\n  get webSocketURL(): string {\n    return `ws://${this.URL}`\n  }\n\n  get httpURL(): string {\n    return `http://${this.URL}`\n  }\n\n  private showStartScreen() {\n    const name = this.configuration.name ? ` (${this.configuration.name})` : ''\n\n    console.log()\n    console.log(`  ${kleur.cyan(`Hocuspocus v${meta.version}${name}`)}${kleur.green(' running at:')}`)\n    console.log()\n    console.log(`  > HTTP: ${kleur.cyan(`${this.httpURL}`)}`)\n    console.log(`  > WebSocket: ${this.webSocketURL}`)\n\n    const extensions = this.configuration?.extensions.map(extension => {\n      return extension.constructor?.name\n    })\n      .filter(name => name)\n      .filter(name => name !== 'Object')\n\n    if (!extensions.length) {\n      return\n    }\n\n    console.log()\n    console.log('  Extensions:')\n\n    extensions\n      .forEach(name => {\n        console.log(`  - ${name}`)\n      })\n\n    console.log()\n    console.log(`  ${kleur.green('Ready.')}`)\n    console.log()\n  }\n\n  /**\n   * Get the total number of active documents\n   */\n  getDocumentsCount(): number {\n    return this.documents.size\n  }\n\n  /**\n   * Get the total number of active connections\n   */\n  getConnectionsCount(): number {\n    return Array.from(this.documents.values()).reduce((acc, document) => {\n      acc += document.getConnectionsCount()\n      return acc\n    }, 0)\n  }\n\n  /**\n   * Force close one or more connections\n   */\n  closeConnections(documentName?: string) {\n    // Iterate through all connections for all documents\n    // and invoke their close method, which is a graceful\n    // disconnect wrapper around the underlying websocket.close\n    this.documents.forEach((document: Document) => {\n      // If a documentName was specified, bail if it doesnt match\n      if (documentName && document.name !== documentName) {\n        return\n      }\n\n      document.connections.forEach(({ connection }) => {\n        connection.close(ResetConnection)\n      })\n    })\n  }\n\n  /**\n   * Destroy the server\n   */\n  async destroy(): Promise<any> {\n    this.httpServer?.close()\n\n    try {\n      this.webSocketServer?.close()\n      this.webSocketServer?.clients.forEach(client => {\n        client.terminate()\n      })\n    } catch (error) {\n      //\n    }\n\n    this.debugger.flush()\n\n    await this.hooks('onDestroy', { instance: this })\n  }\n\n  /**\n   * The `handleConnection` method receives incoming WebSocket connections,\n   * runs all hooks:\n   *\n   *  - onConnect for all connections\n   *  - onAuthenticate only if required\n   *\n   * … and if nothings fails it’ll fully establish the connection and\n   * load the Document then.\n   */\n  handleConnection(incoming: WebSocket, request: IncomingMessage, documentName: string, context: any = null): void {\n    // Make sure to close an idle connection after a while.\n    const closeIdleConnection = setTimeout(() => {\n      incoming.close(Unauthorized.code, Unauthorized.reason)\n    }, this.configuration.timeout)\n\n    // Every new connection gets an unique identifier.\n    const socketId = uuid()\n\n    // To override settings for specific connections, we’ll\n    // keep track of a few things in the `ConnectionConfiguration`.\n    const connection: ConnectionConfiguration = {\n      readOnly: false,\n      requiresAuthentication: this.requiresAuthentication,\n      isAuthenticated: false,\n    }\n\n    // The `onConnect` and `onAuthenticate` hooks need some context\n    // to decide who’s connecting, so let’s put it together:\n    const hookPayload = {\n      documentName,\n      instance: this,\n      request,\n      requestHeaders: request.headers,\n      requestParameters: Hocuspocus.getParameters(request),\n      socketId,\n      connection,\n    }\n\n    // While the connection will be establishing messages will\n    // be queued and handled later.\n    const incomingMessageQueue: Uint8Array[] = []\n\n    // Once all hooks are run, we’ll fully establish the connection:\n    const setUpNewConnection = async (listener: (input: Uint8Array) => void) => {\n      // Not an idle connection anymore, no need to close it then.\n      clearTimeout(closeIdleConnection)\n\n      // If no hook interrupts, create a document and connection\n      const document = await this.createDocument(documentName, request, socketId, connection, context)\n      this.createConnection(incoming, request, document, socketId, connection.readOnly, context)\n\n      // There’s no need to queue messages anymore.\n      incoming.off('message', listener)\n      // Let’s work through queued messages.\n      incomingMessageQueue.forEach(input => {\n        incoming.emit('message', input)\n      })\n    }\n\n    // This listener handles authentication messages and queues everything else.\n    const queueIncomingMessageListener = (data: Uint8Array) => {\n      const decoder = decoding.createDecoder(data)\n      const type = decoding.readVarUint(decoder)\n\n      // Okay, we’ve got the authentication message we’re waiting for:\n      if (type === MessageType.Auth) {\n        // The 2nd integer contains the submessage type\n        // which will always be authentication when sent from client -> server\n        decoding.readVarUint(decoder)\n        const token = decoding.readVarString(decoder)\n\n        this.debugger.log({\n          direction: 'in',\n          type,\n          category: 'Token',\n        })\n\n        this.hooks('onAuthenticate', { token, ...hookPayload }, (contextAdditions: any) => {\n          // Hooks are allowed to give us even more context and we’ll merge everything together.\n          // We’ll pass the context to other hooks then.\n          context = { ...context, ...contextAdditions }\n        })\n          .then(() => {\n            // All `onAuthenticate` hooks passed.\n            connection.isAuthenticated = true\n\n            // Let the client know that authentication was successful.\n            const message = new OutgoingMessage().writeAuthenticated()\n\n            this.debugger.log({\n              direction: 'out',\n              type: message.type,\n              category: message.category,\n            })\n\n            incoming.send(message.toUint8Array())\n          })\n          .then(() => {\n            // Time to actually establish the connection.\n            setUpNewConnection(queueIncomingMessageListener)\n          })\n          .catch(error => {\n            // We could pass the Error message through to the client here but it\n            // risks exposing server internals or being a very long stack trace\n            // hardcoded to 'permission-denied' for now\n            const message = new OutgoingMessage().writePermissionDenied('permission-denied')\n\n            this.debugger.log({\n              direction: 'out',\n              type: message.type,\n              category: message.category,\n            })\n\n            // Ensure that the permission denied message is sent before the\n            // connection is closed\n            incoming.send(message.toUint8Array(), () => {\n              incoming.close(Forbidden.code, Forbidden.reason)\n              incoming.off('message', queueIncomingMessageListener)\n            })\n          })\n      } else {\n        // It’s not the Auth message we’re waiting for, so just queue it.\n        incomingMessageQueue.push(data)\n      }\n    }\n\n    incoming.on('message', queueIncomingMessageListener)\n\n    this.hooks('onConnect', hookPayload, (contextAdditions: any) => {\n      // merge context from all hooks\n      context = { ...context, ...contextAdditions }\n    })\n      .then(() => {\n        // Authentication is required, we’ll need to wait for the Authentication message.\n        if (connection.requiresAuthentication && !connection.isAuthenticated) {\n          return\n        }\n\n        // Authentication isn’t required, let’s establish the connection\n        setUpNewConnection(queueIncomingMessageListener)\n      })\n      .catch(() => {\n        // if a hook interrupts, close the websocket connection\n        incoming.close(Forbidden.code, Forbidden.reason)\n        incoming.off('message', queueIncomingMessageListener)\n      })\n  }\n\n  /**\n   * Handle update of the given document\n   */\n  private handleDocumentUpdate(document: Document, connection: Connection, update: Uint8Array, request: IncomingMessage, socketId: string): void {\n    const hookPayload = {\n      instance: this,\n      clientsCount: document.getConnectionsCount(),\n      context: connection?.context || {},\n      document,\n      documentName: document.name,\n      requestHeaders: request.headers,\n      requestParameters: Hocuspocus.getParameters(request),\n      socketId,\n      update,\n    }\n\n    this.hooks('onChange', hookPayload).catch(error => {\n      throw error\n    })\n\n    // If the update was received through other ways than the\n    // WebSocket connection, we don’t need to feel responsible for\n    // storing the content.\n    if (!connection) {\n      return\n    }\n\n    this.debounce(`onStoreDocument-${document.name}`, () => {\n      this.hooks('onStoreDocument', hookPayload)\n        .catch(error => {\n          if (error?.message) {\n            throw error\n          }\n        })\n        .then(() => {\n          this.hooks('afterStoreDocument', hookPayload)\n        })\n    })\n  }\n\n  timers: Map<string, {\n    timeout: NodeJS.Timeout,\n    start: number\n  }> = new Map()\n\n  /**\n   * debounce the given function, using the given identifier\n   */\n  debounce(id: string, func: Function, immediately = false) {\n    const old = this.timers.get(id)\n    const start = old?.start || Date.now()\n\n    const run = () => {\n      this.timers.delete(id)\n      func()\n    }\n\n    if (old?.timeout) {\n      clearTimeout(old.timeout)\n    }\n\n    if (immediately) {\n      return run()\n    }\n\n    if (Date.now() - start >= this.configuration.maxDebounce) {\n      return run()\n    }\n\n    this.timers.set(id, {\n      start,\n      timeout: setTimeout(run, this.configuration.debounce),\n    })\n  }\n\n  /**\n   * Create a new document by the given request\n   */\n  private async createDocument(documentName: string, request: IncomingMessage, socketId: string, connection: ConnectionConfiguration, context?: any): Promise<Document> {\n    if (this.documents.has(documentName)) {\n      const document = this.documents.get(documentName)\n\n      if (document) {\n        return document\n      }\n    }\n\n    const document = new Document(documentName)\n    this.documents.set(documentName, document)\n\n    const hookPayload = {\n      instance: this,\n      context,\n      connection,\n      document,\n      documentName,\n      socketId,\n      requestHeaders: request.headers,\n      requestParameters: Hocuspocus.getParameters(request),\n    }\n\n    await this.hooks('onLoadDocument', hookPayload, (loadedDocument: Doc | undefined) => {\n      // if a hook returns a Y-Doc, encode the document state as update\n      // and apply it to the newly created document\n      // Note: instanceof doesn't work, because Doc !== Doc for some reason I don't understand\n      if (\n        loadedDocument?.constructor.name === 'Document'\n        || loadedDocument?.constructor.name === 'Doc'\n      ) {\n        applyUpdate(document, encodeStateAsUpdate(loadedDocument))\n      }\n    })\n\n    await this.hooks('afterLoadDocument', hookPayload)\n\n    document.onUpdate((document: Document, connection: Connection, update: Uint8Array) => {\n      this.handleDocumentUpdate(document, connection, update, request, connection?.socketId)\n    })\n\n    document.awareness.on('update', ({ update }: { update: AwarenessUpdate }) => {\n      this.hooks('onAwarenessUpdate', {\n        ...hookPayload,\n        ...update,\n        awareness: document.awareness,\n        states: awarenessStatesToArray(document.awareness.getStates()),\n      })\n    })\n\n    return document\n  }\n\n  /**\n   * Create a new connection by the given request and document\n   */\n  private createConnection(connection: WebSocket, request: IncomingMessage, document: Document, socketId: string, readOnly = false, context?: any): Connection {\n    const instance = new Connection(connection, request, document, this.configuration.timeout, socketId, context, readOnly)\n\n    instance.onClose(document => {\n      const hookPayload = {\n        instance: this,\n        clientsCount: document.getConnectionsCount(),\n        context,\n        document,\n        socketId,\n        documentName: document.name,\n        requestHeaders: request.headers,\n        requestParameters: Hocuspocus.getParameters(request),\n      }\n\n      this.hooks('onDisconnect', hookPayload)\n\n      // Check if there are still no connections to the document, as these hooks\n      // may take some time to resolve (e.g. database queries). If a\n      // new connection were to come in during that time it would rely on the\n      // document in the map that we remove now.\n      if (document.getConnectionsCount() > 0) {\n        return\n      }\n\n      // If it’s the last connection, we need to make sure to store the\n      // document. Use the debounce helper, to clear running timers,\n      // but make it run immediately (`true`).\n      this.debounce(`onStoreDocument-${document.name}`, () => {\n        this.hooks('onStoreDocument', hookPayload)\n          .catch(error => {\n            if (error?.message) {\n              throw error\n            }\n          })\n          .then(() => {\n            this.hooks('afterStoreDocument', hookPayload)\n          })\n      }, true)\n\n      // Remove document from memory.\n      this.documents.delete(document.name)\n      document.destroy()\n    })\n\n    // If the WebSocket has already disconnected (wow, that was fast) – then\n    // immediately call close to cleanup the connection and document in memory.\n    if (\n      connection.readyState === WsReadyStates.Closing\n      || connection.readyState === WsReadyStates.Closed\n    ) {\n      instance.close()\n    }\n\n    return instance\n  }\n\n  /**\n   * Run the given hook on all configured extensions.\n   * Runs the given callback after each hook.\n   */\n  hooks(name: Hook, payload: any, callback: Function | null = null): Promise<any> {\n    const { extensions } = this.configuration\n\n    // create a new `thenable` chain\n    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve\n    let chain = Promise.resolve()\n\n    extensions\n      // get me all extensions which have the given hook\n      .filter(extension => typeof extension[name] === 'function')\n      // run through all the configured hooks\n      .forEach(extension => {\n        chain = chain\n          .then(() => extension[name]?.(payload))\n          .catch(error => {\n            // make sure to log error messages\n            if (error?.message) {\n              console.error(`[${name}]`, error.message)\n            }\n\n            throw error\n          })\n\n        if (callback) {\n          chain = chain.then((...args: any[]) => callback(...args))\n        }\n      })\n\n    return chain\n  }\n\n  /**\n   * Get parameters by the given request\n   */\n  private static getParameters(request: IncomingMessage): URLSearchParams {\n    const query = request?.url?.split('?') || []\n    return new URLSearchParams(query[1] ? query[1] : '')\n  }\n\n  /**\n   * Get document name by the given request\n   */\n  private async getDocumentNameFromRequest(request: IncomingMessage): Promise<string> {\n    const documentName = decodeURI(\n      request.url?.slice(1)?.split('?')[0] || '',\n    )\n\n    if (!this.configuration.getDocumentName) {\n      return documentName\n    }\n\n    const requestParameters = Hocuspocus.getParameters(request)\n\n    return this.configuration.getDocumentName({ documentName, request, requestParameters })\n  }\n\n  enableDebugging() {\n    this.debugger.enable()\n  }\n\n  enableMessageLogging() {\n    this.debugger.enable()\n    this.debugger.verbose()\n  }\n\n  disableLogging() {\n    this.debugger.quiet()\n  }\n\n  disableDebugging() {\n    this.debugger.disable()\n  }\n\n  flushMessageLogs() {\n    this.debugger.flush()\n\n    return this\n  }\n\n  getMessageLogs() {\n    return this.debugger.get()?.logs\n  }\n}\n\nexport const Server = new Hocuspocus()\n"],"names":["create","length","buffer.createUint8ArrayViewFromArrayBuffer","binary.BITS7","binary.BIT8","math.min","math.max","MessageType","WsReadyStates","map.create","map.setIfUndefined","set.create","array.from","object.length","object.hasProperty","time.getUnixTime","math.floor","f.equalityDeep","encoding.createEncoder","encoding.writeVarUint","encoding.writeVarString","encoding.toUint8Array","decoding.createDecoder","decoding.readVarUint","decoding.readVarString","Y","encoding.writeVarUint8Array","decoding.readVarUint8Array","writeAuthenticated","writePermissionDenied","Doc","applyUpdate","encodeStateAsUpdate","AsyncLock","ConnectionTimeout","WebSocketServer","createServer","kleur","ResetConnection","Unauthorized","uuid","Forbidden","URLSearchParams"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMA,QAAM,GAAG,MAAM,IAAI,GAAG,GAAE;AAerC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,cAAc,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,KAAK;AACrD,EAAE,IAAI,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,EAAC;AACxB,EAAE,IAAI,GAAG,KAAK,SAAS,EAAE;AACzB,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,GAAG,OAAO,EAAE,EAAC;AACjC,GAAG;A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