@abraca/dabra 1.0.0 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/abracadabra-provider.cjs +53 -0
- package/dist/abracadabra-provider.cjs.map +1 -1
- package/dist/abracadabra-provider.esm.js +53 -0
- package/dist/abracadabra-provider.esm.js.map +1 -1
- package/dist/index.d.ts +35 -1
- package/package.json +1 -1
- package/src/AbracadabraClient.ts +49 -0
- package/src/FileBlobStore.ts +36 -0
- package/src/types.ts +14 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"abracadabra-provider.cjs","names":["floor","min","max","isNaN","BIT8","BIT18","BIT19","BIT20","BIT21","BIT22","BIT23","BIT24","BIT25","BIT26","BIT27","BIT28","BIT29","BIT30","BIT31","BIT32","BITS7","BITS17","BITS18","BITS19","BITS20","BITS21","BITS22","BITS23","BITS24","BITS25","BITS26","BITS27","BITS28","BITS29","BITS30","BITS31","BITS32","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","LOWEST_INT32","HIGHEST_INT32","binary.BITS31","HIGHEST_UINT32","binary.BITS32","isInteger","math.floor","isNaN","parseInt","create","isArray","fromCharCode","fromCodePoint","MAX_UTF16_CHARACTER","_encodeUtf8Polyfill","utf8TextEncoder","_encodeUtf8Native","encodeUtf8","utf8TextDecoder","Encoder","createEncoder","length","toUint8Array","write","writeVarUint","binary.BITS7","binary.BIT8","math.floor","_strBuffer","_maxStrBSize","_writeVarStringNative","string.encodeUtf8","_writeVarStringPolyfill","writeVarString","string.utf8TextEncoder","writeUint8Array","math.min","math.max","writeVarUint8Array","create","errorUnexpectedEndOfArray","error.create","errorIntegerOutOfRange","Decoder","createDecoder","readUint8Array","readVarUint8Array","readVarUint","readUint8","binary.BITS7","binary.BIT8","number.MAX_SAFE_INTEGER","_readVarStringPolyfill","_readVarStringNative","readVarString","string.utf8TextDecoder","getUnixTime","create","map.create","set.create","array.from","equalityTrait.EqualityTraitSymbol","object.size","object.hasProperty","array.isArray","time.getUnixTime","math.floor","f.equalityDeep","encoding.createEncoder","encoding.toUint8Array","decoding.createDecoder","decoding.readVarUint","decoding.readVarString","isNaN","binary.BITS31","binary.BITS32","math.floor","parseInt","binary.BITS7","binary.BIT8","math.floor","string.encodeUtf8","string.utf8TextEncoder","math.min","math.max","error.create","binary.BITS7","binary.BIT8","number.MAX_SAFE_INTEGER","binary.BITS6","binary.BIT7","string.utf8TextDecoder","time.getUnixTime","decoding.readVarUint","decoding.readVarString","Y","decoding.readVarUint8Array","decoding.readVarUint","awarenessProtocol.encodeAwarenessUpdate","Y","DB_VERSION","idbAvailable","openDb","txPromise","Y","fromBase64","isBytes","anumber","abytes","aexists","aoutput","clean","createView","isLE","hasHexBuiltin","createHasher","HashMD","createView","U32_MASK64","_32n","fromBig","split","HashMD","K512","u64.split","SHA512_Kh","SHA512_Kl","sha256","sha256n","createHasher","u64.split","u64.rotrSH","u64.shrSH","u64.rotrSL","u64.shrSL","u64.rotrBH","u64.rotrBL","u64.add4L","u64.add4H","u64.add5L","u64.add5H","u64.add","u64.add3L","u64.add3H","_0n","_1n","bytesToHex_","abytes_","hexToBytes_","_0n","_1n","_2n","_3n","_5n","_8n","_0n","_1n","_0n","_1n","_2n","_8n","randomBytes","wcRandomBytes","_0n","_1n","_2n","HKDF_INFO","openDb","ed","nobleEd25519Curves","DB_VERSION","idbAvailable","openDb","txPromise","DB_VERSION","idbAvailable","openDb","DB_VERSION","idbAvailable","openDb","fromBase64","Y","Y"],"sources":["../src/awarenessStatesToArray.ts","../../../node_modules/lib0/math.js","../../../node_modules/lib0/binary.js","../../../node_modules/lib0/number.js","../../../node_modules/lib0/set.js","../../../node_modules/lib0/array.js","../../../node_modules/lib0/string.js","../../../node_modules/lib0/encoding.js","../../../node_modules/lib0/error.js","../../../node_modules/lib0/decoding.js","../../../node_modules/lib0/time.js","../../../node_modules/lib0/map.js","../../../node_modules/lib0/observable.js","../../../node_modules/lib0/trait/equality.js","../../../node_modules/lib0/object.js","../../../node_modules/lib0/function.js","../../../node_modules/y-protocols/awareness.js","../src/EventEmitter.ts","../src/types.ts","../node_modules/lib0/math.js","../node_modules/lib0/time.js","../node_modules/lib0/binary.js","../node_modules/lib0/number.js","../node_modules/lib0/string.js","../node_modules/lib0/error.js","../node_modules/lib0/encoding.js","../node_modules/lib0/decoding.js","../src/IncomingMessage.ts","../src/OutgoingMessage.ts","../src/OutgoingMessages/CloseMessage.ts","../src/AbracadabraWS.ts","../src/auth.ts","../../../node_modules/y-protocols/sync.js","../src/MessageReceiver.ts","../src/MessageSender.ts","../src/OutgoingMessages/AuthenticationMessage.ts","../src/OutgoingMessages/AwarenessMessage.ts","../src/OutgoingMessages/StatelessMessage.ts","../src/OutgoingMessages/SyncStepOneMessage.ts","../src/OutgoingMessages/UpdateMessage.ts","../src/AbracadabraBaseProvider.ts","../src/OfflineStore.ts","../src/OutgoingMessages/SubdocMessage.ts","../src/AbracadabraProvider.ts","../src/AbracadabraClient.ts","../src/CloseEvents.ts","../node_modules/@noble/hashes/esm/utils.js","../node_modules/@noble/hashes/esm/hmac.js","../node_modules/@noble/hashes/esm/hkdf.js","../node_modules/@noble/hashes/esm/_md.js","../node_modules/@noble/hashes/esm/_u64.js","../node_modules/@noble/hashes/esm/sha2.js","../node_modules/@noble/hashes/esm/sha256.js","../node_modules/@noble/curves/node_modules/@noble/hashes/utils.js","../node_modules/@noble/curves/node_modules/@noble/hashes/_md.js","../node_modules/@noble/curves/node_modules/@noble/hashes/_u64.js","../node_modules/@noble/curves/node_modules/@noble/hashes/sha2.js","../node_modules/@noble/curves/utils.js","../node_modules/@noble/curves/abstract/modular.js","../node_modules/@noble/curves/abstract/curve.js","../node_modules/@noble/curves/abstract/edwards.js","../node_modules/@noble/curves/abstract/hash-to-curve.js","../node_modules/@noble/curves/abstract/montgomery.js","../node_modules/@noble/curves/abstract/oprf.js","../node_modules/@noble/curves/ed25519.js","../src/CryptoIdentityKeystore.ts","../src/DocumentCache.ts","../src/SearchIndex.ts","../src/FileBlobStore.ts","../src/DocKeyManager.ts","../src/EncryptedY.ts","../src/E2EOfflineStore.ts","../src/E2EAbracadabraProvider.ts","../src/TreeTimestamps.ts","../src/BackgroundSyncPersistence.ts","../src/BackgroundSyncManager.ts"],"sourcesContent":["export const awarenessStatesToArray = (\n\tstates: Map<number, Record<string, any>>,\n) => {\n\treturn Array.from(states.entries()).map(([key, value]) => {\n\t\treturn {\n\t\t\tclientId: key,\n\t\t\t...value,\n\t\t};\n\t});\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 * Check whether n is negative, while considering the -0 edge case. While `-0 < 0` is false, this\n * function returns true for -0,-1,,.. and returns false for 0,1,2,...\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also distinguishes between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\nexport const HIGHEST_INT32 = binary.BITS31\nexport const HIGHEST_UINT32 = binary.BITS32\n\n/* c8 ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n\n/**\n * Count the number of \"1\" bits in an unsigned 32bit number.\n *\n * Super fun bitcount algorithm by Brian Kernighan.\n *\n * @param {number} n\n */\nexport const countBits = n => {\n n &= binary.BITS32\n let count = 0\n while (n) {\n n &= (n - 1)\n count++\n }\n return count\n}\n","/**\n * Utility module to work with sets.\n *\n * @module set\n */\n\nexport const create = () => new Set()\n\n/**\n * @template T\n * @param {Set<T>} set\n * @return {Array<T>}\n */\nexport const toArray = set => Array.from(set)\n\n/**\n * @template T\n * @param {Set<T>} set\n * @return {T|undefined}\n */\nexport const first = set => set.values().next().value\n\n/**\n * @template T\n * @param {Iterable<T>} entries\n * @return {Set<T>}\n */\nexport const from = entries => new Set(entries)\n","/**\n * Utility module to work with Arrays.\n *\n * @module array\n */\n\nimport * as set from './set.js'\n\n/**\n * Return the last element of an array. The element must exist\n *\n * @template L\n * @param {ArrayLike<L>} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array<C>}\n */\nexport const create = () => /** @type {Array<C>} */ ([])\n\n/**\n * @template D\n * @param {Array<D>} a\n * @return {Array<D>}\n */\nexport const copy = a => /** @type {Array<D>} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array<M>} dest\n * @param {Array<M>} src\n */\nexport const appendTo = (dest, src) => {\n for (let i = 0; i < src.length; i++) {\n dest.push(src[i])\n }\n}\n\n/**\n * Transforms something array-like to an actual Array.\n *\n * @function\n * @template T\n * @param {ArrayLike<T>|Iterable<T>} arraylike\n * @return {T}\n */\nexport const from = Array.from\n\n/**\n * True iff condition holds on every element in the Array.\n *\n * @function\n * @template {ArrayLike<any>} ARR\n *\n * @param {ARR} arr\n * @param {ARR extends ArrayLike<infer S> ? ((value:S, index:number, arr:ARR) => boolean) : any} f\n * @return {boolean}\n */\nexport const every = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (!f(arr[i], i, arr)) {\n return false\n }\n }\n return true\n}\n\n/**\n * True iff condition holds on some element in the Array.\n *\n * @function\n * @template {ArrayLike<any>} ARR\n *\n * @param {ARR} arr\n * @param {ARR extends ArrayLike<infer S> ? ((value:S, index:number, arr:ARR) => boolean) : never} f\n * @return {boolean}\n */\nexport const some = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (f(arr[i], i, arr)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @template ELEM\n *\n * @param {ArrayLike<ELEM>} a\n * @param {ArrayLike<ELEM>} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a.length === b.length && every(a, (item, index) => item === b[index])\n\n/**\n * @template ELEM\n * @param {Array<Array<ELEM>>} arr\n * @return {Array<ELEM>}\n */\nexport const flatten = arr => fold(arr, /** @type {Array<ELEM>} */ ([]), (acc, val) => acc.concat(val))\n\n/**\n * @template T\n * @param {number} len\n * @param {function(number, Array<T>):T} f\n * @return {Array<T>}\n */\nexport const unfold = (len, f) => {\n const array = new Array(len)\n for (let i = 0; i < len; i++) {\n array[i] = f(i, array)\n }\n return array\n}\n\n/**\n * @template T\n * @template RESULT\n * @param {Array<T>} arr\n * @param {RESULT} seed\n * @param {function(RESULT, T, number):RESULT} folder\n */\nexport const fold = (arr, seed, folder) => arr.reduce(folder, seed)\n\nexport const isArray = Array.isArray\n\n/**\n * @template T\n * @param {Array<T>} arr\n * @return {Array<T>}\n */\nexport const unique = arr => from(set.from(arr))\n\n/**\n * @template T\n * @template M\n * @param {ArrayLike<T>} arr\n * @param {function(T):M} mapper\n * @return {Array<T>}\n */\nexport const uniqueBy = (arr, mapper) => {\n /**\n * @type {Set<M>}\n */\n const happened = set.create()\n /**\n * @type {Array<T>}\n */\n const result = []\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i]\n const mapped = mapper(el)\n if (!happened.has(mapped)) {\n happened.add(mapped)\n result.push(el)\n }\n }\n return result\n}\n\n/**\n * @template {ArrayLike<any>} ARR\n * @template {function(ARR extends ArrayLike<infer T> ? T : never, number, ARR):any} MAPPER\n * @param {ARR} arr\n * @param {MAPPER} mapper\n * @return {Array<MAPPER extends function(...any): infer M ? M : never>}\n */\nexport const map = (arr, mapper) => {\n /**\n * @type {Array<any>}\n */\n const res = Array(arr.length)\n for (let i = 0; i < arr.length; i++) {\n res[i] = mapper(/** @type {any} */ (arr[i]), i, /** @type {any} */ (arr))\n }\n return /** @type {any} */ (res)\n}\n\n/**\n * This function bubble-sorts a single item to the correct position. The sort happens in-place and\n * might be useful to ensure that a single item is at the correct position in an otherwise sorted\n * array.\n *\n * @example\n * const arr = [3, 2, 5]\n * arr.sort((a, b) => a - b)\n * arr // => [2, 3, 5]\n * arr.splice(1, 0, 7)\n * array.bubbleSortItem(arr, 1, (a, b) => a - b)\n * arr // => [2, 3, 5, 7]\n *\n * @template T\n * @param {Array<T>} arr\n * @param {number} i\n * @param {(a:T,b:T) => number} compareFn\n */\nexport const bubblesortItem = (arr, i, compareFn) => {\n const n = arr[i]\n let j = i\n // try to sort to the right\n while (j + 1 < arr.length && compareFn(n, arr[j + 1]) > 0) {\n arr[j] = arr[j + 1]\n arr[++j] = n\n }\n if (i === j && j > 0) { // no change yet\n // sort to the left\n while (j > 0 && compareFn(arr[j - 1], n) > 0) {\n arr[j] = arr[j - 1]\n arr[--j] = n\n }\n }\n return j\n}\n","import * as array from './array.js'\n\n/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * The largest utf16 character.\n * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8)\n */\nexport const MAX_UTF16_CHARACTER = fromCharCode(65535)\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array<ArrayBuffer>}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* c8 ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array<ArrayBuffer>}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* c8 ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* c8 ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* c8 ignore start */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* c8 ignore next */\n utf8TextDecoder = null\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* c8 ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n\n/**\n * @param {string} source\n * @param {number} n\n */\nexport const repeat = (source, n) => array.unfold(n, () => source).join('')\n\n/**\n * Escape HTML characters &,<,>,',\" to their respective HTML entities &,<,>,',"\n *\n * @param {string} str\n */\nexport const escapeHTML = str =>\n str.replace(/[&<>'\"]/g, r => /** @type {string} */ ({\n '&': '&',\n '<': '<',\n '>': '>',\n \"'\": ''',\n '\"': '"'\n }[r]))\n\n/**\n * Reverse of `escapeHTML`\n *\n * @param {string} str\n */\nexport const unescapeHTML = str =>\n str.replace(/&|<|>|'|"/g, r => /** @type {string} */ ({\n '&': '&',\n '<': '<',\n '>': '>',\n ''': \"'\",\n '"': '\"'\n }[r]))\n","/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\nimport * as string from './string.js'\nimport * as array from './array.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array<Uint8Array>}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * @param {function(Encoder):void} f\n */\nexport const encode = (f) => {\n const encoder = createEncoder()\n f(encoder)\n return toUint8Array(encoder)\n}\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Check whether encoder is empty.\n *\n * @function\n * @param {Encoder} encoder\n * @return {boolean}\n */\nexport const hasContent = encoder => encoder.cpos > 0 || encoder.bufs.length > 0\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array<ArrayBuffer>} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nexport const verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer. Max encodable integer is 2^53.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num = math.floor(num / 64) // shift >>> 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n}\n\n/**\n * A cache to store strings temporarily\n */\nconst _strBuffer = new Uint8Array(30000)\nconst _maxStrBSize = _strBuffer.length / 3\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringNative = (encoder, str) => {\n if (str.length < _maxStrBSize) {\n // We can encode the string into the existing buffer\n /* c8 ignore next */\n const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0\n writeVarUint(encoder, written)\n for (let i = 0; i < written; i++) {\n write(encoder, _strBuffer[i])\n }\n } else {\n writeVarUint8Array(encoder, string.encodeUtf8(str))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringPolyfill = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\n/* c8 ignore next */\nexport const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill\n\n/**\n * Write a string terminated by a special byte sequence. This is not very performant and is\n * generally discouraged. However, the resulting byte arrays are lexiographically ordered which\n * makes this a nice feature for databases.\n *\n * The string will be encoded using utf8 and then terminated and escaped using writeTerminatingUint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const writeTerminatedString = (encoder, str) =>\n writeTerminatedUint8Array(encoder, string.encodeUtf8(str))\n\n/**\n * Write a terminating Uint8Array. Note that this is not performant and is generally\n * discouraged. There are few situations when this is needed.\n *\n * We use 0x0 as a terminating character. 0x1 serves as an escape character for 0x0 and 0x1.\n *\n * Example: [0,1,2] is encoded to [1,0,1,1,2,0]. 0x0, and 0x1 needed to be escaped using 0x1. Then\n * the result is terminated using the 0x0 character.\n *\n * This is basically how many systems implement null terminated strings. However, we use an escape\n * character 0x1 to avoid issues and potenial attacks on our database (if this is used as a key\n * encoder for NoSql databases).\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} buf The string that is to be encoded.\n */\nexport const writeTerminatedUint8Array = (encoder, buf) => {\n for (let i = 0; i < buf.length; i++) {\n const b = buf[i]\n if (b === 0 || b === 1) {\n write(encoder, 1)\n }\n write(encoder, buf[i])\n }\n write(encoder, 0)\n}\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * @typedef {Array<AnyEncodable>} AnyEncodableArray\n */\n\n/**\n * @typedef {undefined|null|number|bigint|boolean|string|{[k:string]:AnyEncodable}|AnyEncodableArray|Uint8Array} AnyEncodable\n */\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object<string,any> | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array<any> | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {AnyEncodable} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && math.abs(data) <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (array.isArray(data)) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array<string>}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n","/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* c8 ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n\n/**\n * @param {boolean} property\n * @return {asserts property is true}\n */\nexport const assert = property => { if (!property) throw create('Assert failed') }\n","/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as binary from './binary.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as string from './string.js'\nimport * as error from './error.js'\nimport * as encoding from './encoding.js'\n\nconst errorUnexpectedEndOfArray = error.create('Unexpected end of array')\nconst errorIntegerOutOfRange = error.create('Integer out of Range')\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n * @template {ArrayBufferLike} [Buf=ArrayBufferLike]\n */\nexport class Decoder {\n /**\n * @param {Uint8Array<Buf>} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array<Buf>}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Uint8Array<Buf>} uint8Array\n * @return {Decoder<Buf>}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Decoder<Buf>} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array<Buf>}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Decoder<Buf>} decoder\n * @return {Uint8Array<Buf>}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let mult = 1\n const len = decoder.arr.length\n while (decoder.pos < len) {\n const r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num\n mult *= 128 // next iteration, shift 7 \"more\" to the left\n if (r < binary.BIT8) {\n return num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let mult = 64\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n const len = decoder.arr.length\n while (decoder.pos < len) {\n r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult\n mult *= 128\n if (r < binary.BIT8) {\n return sign * num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * We don't test this function anymore as we use native decoding/encoding by default now.\n * Better not modify this anymore..\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\n/* c8 ignore start */\nexport const _readVarStringPolyfill = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n/* c8 ignore stop */\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n */\nexport const _readVarStringNative = decoder =>\n /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder))\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n *\n */\n/* c8 ignore next */\nexport const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill\n\n/**\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTerminatedUint8Array = decoder => {\n const encoder = encoding.createEncoder()\n let b\n while (true) {\n b = readUint8(decoder)\n if (b === 0) {\n return encoding.toUint8Array(encoder)\n }\n if (b === 1) {\n b = readUint8(decoder)\n }\n encoding.write(encoder, b)\n }\n}\n\n/**\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const readTerminatedString = decoder => string.decodeUtf8(readTerminatedUint8Array(decoder))\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array<function(Decoder):any>}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object<string,any>\n const len = readVarUint(decoder)\n /**\n * @type {Object<string,any>}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array<any>\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = math.floor(diff / 2) // shift >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n","/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* c8 ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n","/**\n * Utility module to work with key-value stores.\n *\n * @module map\n */\n\n/**\n * @template K\n * @template V\n * @typedef {Map<K,V>} GlobalMap\n */\n\n/**\n * Creates a new Map instance.\n *\n * @function\n * @return {Map<any, any>}\n *\n * @function\n */\nexport const create = () => new Map()\n\n/**\n * Copy a Map object into a fresh Map object.\n *\n * @function\n * @template K,V\n * @param {Map<K,V>} m\n * @return {Map<K,V>}\n */\nexport const copy = m => {\n const r = create()\n m.forEach((v, k) => { r.set(k, v) })\n return r\n}\n\n/**\n * Get map property. Create T if property is undefined and set T on map.\n *\n * ```js\n * const listeners = map.setIfUndefined(events, 'eventName', set.create)\n * listeners.add(listener)\n * ```\n *\n * @function\n * @template {Map<any, any>} MAP\n * @template {MAP extends Map<any,infer V> ? function():V : unknown} CF\n * @param {MAP} map\n * @param {MAP extends Map<infer K,any> ? K : unknown} key\n * @param {CF} createT\n * @return {ReturnType<CF>}\n */\nexport const setIfUndefined = (map, key, createT) => {\n let set = map.get(key)\n if (set === undefined) {\n map.set(key, set = createT())\n }\n return set\n}\n\n/**\n * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function.\n *\n * @function\n * @template K\n * @template V\n * @template R\n * @param {Map<K,V>} m\n * @param {function(V,K):R} f\n * @return {Array<R>}\n */\nexport const map = (m, f) => {\n const res = []\n for (const [key, value] of m) {\n res.push(f(value, key))\n }\n return res\n}\n\n/**\n * Tests whether any key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @todo should rename to some - similarly to Array.some\n *\n * @function\n * @template K\n * @template V\n * @param {Map<K,V>} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const any = (m, f) => {\n for (const [key, value] of m) {\n if (f(value, key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * Tests whether all key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @function\n * @template K\n * @template V\n * @param {Map<K,V>} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const all = (m, f) => {\n for (const [key, value] of m) {\n if (!f(value, key)) {\n return false\n }\n }\n return true\n}\n","/**\n * Observable class prototype.\n *\n * @module observable\n */\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as array from './array.js'\n\n/**\n * Handles named events.\n * @experimental\n *\n * This is basically a (better typed) duplicate of Observable, which will replace Observable in the\n * next release.\n *\n * @template {{[key in keyof EVENTS]: function(...any):void}} EVENTS\n */\nexport class ObservableV2 {\n constructor () {\n /**\n * Some desc.\n * @type {Map<string, Set<any>>}\n */\n this._observers = map.create()\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, /** @type {string} */ (name), set.create).add(f)\n return f\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, /** @type {any} */ (_f))\n f(...args)\n }\n this.on(name, /** @type {any} */ (_f))\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name The event name.\n * @param {Parameters<EVENTS[NAME]>} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n\n/* c8 ignore start */\n/**\n * Handles named events.\n *\n * @deprecated\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map<N, any>}\n */\n this._observers = map.create()\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, name, set.create).add(f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, _f)\n f(...args)\n }\n this.on(name, _f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @param {N} name The event name.\n * @param {Array<any>} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n/* c8 ignore end */\n","export const EqualityTraitSymbol = Symbol('Equality')\n\n/**\n * @typedef {{ [EqualityTraitSymbol]:(other:EqualityTrait)=>boolean }} EqualityTrait\n */\n\n/**\n *\n * Utility function to compare any two objects.\n *\n * Note that it is expected that the first parameter is more specific than the latter one.\n *\n * @example js\n * class X { [traits.EqualityTraitSymbol] (other) { return other === this } }\n * class X2 { [traits.EqualityTraitSymbol] (other) { return other === this }, x2 () { return 2 } }\n * // this is fine\n * traits.equals(new X2(), new X())\n * // this is not, because the left type is less specific than the right one\n * traits.equals(new X(), new X2())\n *\n * @template {EqualityTrait} T\n * @param {NoInfer<T>} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equals = (a, b) => a === b || !!a?.[EqualityTraitSymbol]?.(b) || false\n","import * as equalityTrait from './trait/equality.js'\n\n/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object<string,any>} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * @param {any} o\n * @return {o is { [k:string]:any }}\n */\nexport const isObject = o => typeof o === 'object'\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object<string,any>} obj\n */\nexport const keys = Object.keys\n\n/**\n * @template V\n * @param {{[key:string]: V}} obj\n * @return {Array<V>}\n */\nexport const values = Object.values\n\n/**\n * @template V\n * @param {{[k:string]:V}} obj\n * @param {function(V,string):any} f\n */\nexport const forEach = (obj, f) => {\n for (const key in obj) {\n f(obj[key], key)\n }\n}\n\n/**\n * @todo implement mapToArray & map\n *\n * @template R\n * @param {Object<string,any>} obj\n * @param {function(any,string):R} f\n * @return {Array<R>}\n */\nexport const map = (obj, f) => {\n const results = []\n for (const key in obj) {\n results.push(f(obj[key], key))\n }\n return results\n}\n\n/**\n * @deprecated use object.size instead\n * @param {Object<string,any>} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object<string,any>} obj\n * @return {number}\n */\nexport const size = obj => keys(obj).length\n\n/**\n * @template {{ [key:string|number|symbol]: any }} T\n * @param {T} obj\n * @param {(v:T[keyof T],k:keyof T)=>boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n for (const key in obj) {\n if (f(obj[key], key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {Object|null|undefined} obj\n */\nexport const isEmpty = obj => {\n // eslint-disable-next-line no-unreachable-loop\n for (const _k in obj) {\n return false\n }\n return true\n}\n\n/**\n * @template {{ [key:string|number|symbol]: any }} T\n * @param {T} obj\n * @param {(v:T[keyof T],k:keyof T)=>boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n for (const key in obj) {\n if (!f(obj[key], key)) {\n return false\n }\n }\n return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|number|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object<string,any>} a\n * @param {Object<string,any>} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (size(a) === size(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && equalityTrait.equals(b[key], val)))\n\n/**\n * Make an object immutable. This hurts performance and is usually not needed if you perform good\n * coding practices.\n */\nexport const freeze = Object.freeze\n\n/**\n * Make an object and all its children immutable.\n * This *really* hurts performance and is usually not needed if you perform good coding practices.\n *\n * @template {any} T\n * @param {T} o\n * @return {Readonly<T>}\n */\nexport const deepFreeze = (o) => {\n for (const key in o) {\n const c = o[key]\n if (typeof c === 'object' || typeof c === 'function') {\n deepFreeze(o[key])\n }\n }\n return freeze(o)\n}\n\n/**\n * Get object property. Create T if property is undefined and set T on object.\n *\n * @function\n * @template {object} KV\n * @template {keyof KV} [K=keyof KV]\n * @param {KV} o\n * @param {K} key\n * @param {() => KV[K]} createT\n * @return {KV[K]}\n */\nexport const setIfUndefined = (o, key, createT) => hasProperty(o, key) ? o[key] : (o[key] = createT())\n","/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\nimport * as equalityTrait from './trait/equality.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array<function>} fs\n * @param {Array<any>} args\n */\nexport const callAll = (fs, args, i = 0) => {\n try {\n for (; i < fs.length; i++) {\n fs[i](...args)\n }\n } finally {\n if (i < fs.length) {\n callAll(fs, args, i + 1)\n }\n }\n}\n\nexport const nop = () => {}\n\n/**\n * @template T\n * @param {function():T} f\n * @return {T}\n */\nexport const apply = f => f()\n\n/**\n * @template A\n *\n * @param {A} a\n * @return {A}\n */\nexport const id = a => a\n\n/**\n * @template T\n *\n * @param {T} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equalityStrict = (a, b) => a === b\n\n/**\n * @template T\n *\n * @param {Array<T>|object} a\n * @param {Array<T>|object} b\n * @return {boolean}\n */\nexport const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((array.isArray(a) && array.equalFlat(a, /** @type {Array<T>} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/* c8 ignore start */\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a === b) {\n return true\n }\n if (a == null || b == null || (a.constructor !== b.constructor && (a.constructor || Object) !== (b.constructor || Object))) {\n return false\n }\n if (a[equalityTrait.EqualityTraitSymbol] != null) {\n return a[equalityTrait.EqualityTraitSymbol](b)\n }\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n break\n }\n case Map: {\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n return false\n }\n }\n break\n }\n case undefined:\n case Object:\n if (object.size(a) !== object.size(b)) {\n return false\n }\n for (const key in a) {\n if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n return false\n }\n }\n break\n case Array:\n if (a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!equalityDeep(a[i], b[i])) {\n return false\n }\n }\n break\n default:\n return false\n }\n return true\n}\n\n/**\n * @template V\n * @template {V} OPTS\n *\n * @param {V} value\n * @param {Array<OPTS>} options\n */\n// @ts-ignore\nexport const isOneOf = (value, options) => options.includes(value)\n/* c8 ignore stop */\n\nexport const isArray = array.isArray\n\n/**\n * @param {any} s\n * @return {s is String}\n */\nexport const isString = (s) => s && s.constructor === String\n\n/**\n * @param {any} n\n * @return {n is Number}\n */\nexport const isNumber = n => n != null && n.constructor === Number\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {any} n\n * @param {TYPE} T\n * @return {n is InstanceType<TYPE>}\n */\nexport const is = (n, T) => n && n.constructor === T\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {TYPE} T\n */\nexport const isTemplate = (T) =>\n /**\n * @param {any} n\n * @return {n is InstanceType<TYPE>}\n **/\n n => n && n.constructor === T\n","/**\n * @module awareness-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as time from 'lib0/time'\nimport * as math from 'lib0/math'\nimport { Observable } from 'lib0/observable'\nimport * as f from 'lib0/function'\nimport * as Y from 'yjs' // eslint-disable-line\n\nexport const outdatedTimeout = 30000\n\n/**\n * @typedef {Object} MetaClientState\n * @property {number} MetaClientState.clock\n * @property {number} MetaClientState.lastUpdated unix timestamp\n */\n\n/**\n * The Awareness class implements a simple shared state protocol that can be used for non-persistent data like awareness information\n * (cursor, username, status, ..). Each client can update its own local state and listen to state changes of\n * remote clients. Every client may set a state of a remote peer to `null` to mark the client as offline.\n *\n * Each client is identified by a unique client id (something we borrow from `doc.clientID`). A client can override\n * its own state by propagating a message with an increasing timestamp (`clock`). If such a message is received, it is\n * applied if the known state of that client is older than the new state (`clock < newClock`). If a client thinks that\n * a remote client is offline, it may propagate a message with\n * `{ clock: currentClientClock, state: null, client: remoteClient }`. If such a\n * message is received, and the known clock of that client equals the received clock, it will override the state with `null`.\n *\n * Before a client disconnects, it should propagate a `null` state with an updated clock.\n *\n * Awareness states must be updated every 30 seconds. Otherwise the Awareness instance will delete the client state.\n *\n * @extends {Observable<string>}\n */\nexport class Awareness extends Observable {\n /**\n * @param {Y.Doc} doc\n */\n constructor (doc) {\n super()\n this.doc = doc\n /**\n * @type {number}\n */\n this.clientID = doc.clientID\n /**\n * Maps from client id to client state\n * @type {Map<number, Object<string, any>>}\n */\n this.states = new Map()\n /**\n * @type {Map<number, MetaClientState>}\n */\n this.meta = new Map()\n this._checkInterval = /** @type {any} */ (setInterval(() => {\n const now = time.getUnixTime()\n if (this.getLocalState() !== null && (outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ (this.meta.get(this.clientID)).lastUpdated)) {\n // renew local clock\n this.setLocalState(this.getLocalState())\n }\n /**\n * @type {Array<number>}\n */\n const remove = []\n this.meta.forEach((meta, clientid) => {\n if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) {\n remove.push(clientid)\n }\n })\n if (remove.length > 0) {\n removeAwarenessStates(this, remove, 'timeout')\n }\n }, math.floor(outdatedTimeout / 10)))\n doc.on('destroy', () => {\n this.destroy()\n })\n this.setLocalState({})\n }\n\n destroy () {\n this.emit('destroy', [this])\n this.setLocalState(null)\n super.destroy()\n clearInterval(this._checkInterval)\n }\n\n /**\n * @return {Object<string,any>|null}\n */\n getLocalState () {\n return this.states.get(this.clientID) || null\n }\n\n /**\n * @param {Object<string,any>|null} state\n */\n setLocalState (state) {\n const clientID = this.clientID\n const currLocalMeta = this.meta.get(clientID)\n const clock = currLocalMeta === undefined ? 0 : currLocalMeta.clock + 1\n const prevState = this.states.get(clientID)\n if (state === null) {\n this.states.delete(clientID)\n } else {\n this.states.set(clientID, state)\n }\n this.meta.set(clientID, {\n clock,\n lastUpdated: time.getUnixTime()\n })\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n if (state === null) {\n removed.push(clientID)\n } else if (prevState == null) {\n if (state != null) {\n added.push(clientID)\n }\n } else {\n updated.push(clientID)\n if (!f.equalityDeep(prevState, state)) {\n filteredUpdated.push(clientID)\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n this.emit('change', [{ added, updated: filteredUpdated, removed }, 'local'])\n }\n this.emit('update', [{ added, updated, removed }, 'local'])\n }\n\n /**\n * @param {string} field\n * @param {any} value\n */\n setLocalStateField (field, value) {\n const state = this.getLocalState()\n if (state !== null) {\n this.setLocalState({\n ...state,\n [field]: value\n })\n }\n }\n\n /**\n * @return {Map<number,Object<string,any>>}\n */\n getStates () {\n return this.states\n }\n}\n\n/**\n * Mark (remote) clients as inactive and remove them from the list of active peers.\n * This change will be propagated to remote clients.\n *\n * @param {Awareness} awareness\n * @param {Array<number>} clients\n * @param {any} origin\n */\nexport const removeAwarenessStates = (awareness, clients, origin) => {\n const removed = []\n for (let i = 0; i < clients.length; i++) {\n const clientID = clients[i]\n if (awareness.states.has(clientID)) {\n awareness.states.delete(clientID)\n if (clientID === awareness.clientID) {\n const curMeta = /** @type {MetaClientState} */ (awareness.meta.get(clientID))\n awareness.meta.set(clientID, {\n clock: curMeta.clock + 1,\n lastUpdated: time.getUnixTime()\n })\n }\n removed.push(clientID)\n }\n }\n if (removed.length > 0) {\n awareness.emit('change', [{ added: [], updated: [], removed }, origin])\n awareness.emit('update', [{ added: [], updated: [], removed }, origin])\n }\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Array<number>} clients\n * @return {Uint8Array}\n */\nexport const encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {\n const len = clients.length\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = clients[i]\n const state = states.get(clientID) || null\n const clock = /** @type {MetaClientState} */ (awareness.meta.get(clientID)).clock\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(state))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Modify the content of an awareness update before re-encoding it to an awareness update.\n *\n * This might be useful when you have a central server that wants to ensure that clients\n * cant hijack somebody elses identity.\n *\n * @param {Uint8Array} update\n * @param {function(any):any} modify\n * @return {Uint8Array}\n */\nexport const modifyAwarenessUpdate = (update, modify) => {\n const decoder = decoding.createDecoder(update)\n const encoder = encoding.createEncoder()\n const len = decoding.readVarUint(decoder)\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n const clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const modifiedState = modify(state)\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(modifiedState))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Uint8Array} update\n * @param {any} origin This will be added to the emitted change event\n */\nexport const applyAwarenessUpdate = (awareness, update, origin) => {\n const decoder = decoding.createDecoder(update)\n const timestamp = time.getUnixTime()\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n const len = decoding.readVarUint(decoder)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n let clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const clientMeta = awareness.meta.get(clientID)\n const prevState = awareness.states.get(clientID)\n const currClock = clientMeta === undefined ? 0 : clientMeta.clock\n if (currClock < clock || (currClock === clock && state === null && awareness.states.has(clientID))) {\n if (state === null) {\n // never let a remote client remove this local state\n if (clientID === awareness.clientID && awareness.getLocalState() != null) {\n // remote client removed the local state. Do not remote state. Broadcast a message indicating\n // that this client still exists by increasing the clock\n clock++\n } else {\n awareness.states.delete(clientID)\n }\n } else {\n awareness.states.set(clientID, state)\n }\n awareness.meta.set(clientID, {\n clock,\n lastUpdated: timestamp\n })\n if (clientMeta === undefined && state !== null) {\n added.push(clientID)\n } else if (clientMeta !== undefined && state === null) {\n removed.push(clientID)\n } else if (state !== null) {\n if (!f.equalityDeep(state, prevState)) {\n filteredUpdated.push(clientID)\n }\n updated.push(clientID)\n }\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n awareness.emit('change', [{\n added, updated: filteredUpdated, removed\n }, origin])\n }\n if (added.length > 0 || updated.length > 0 || removed.length > 0) {\n awareness.emit('update', [{\n added, updated, removed\n }, origin])\n }\n}\n","export default class EventEmitter {\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic callbacks: { [key: string]: Function[] } = {};\n\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic on(event: string, fn: Function): this {\n\t\tif (!this.callbacks[event]) {\n\t\t\tthis.callbacks[event] = [];\n\t\t}\n\n\t\tthis.callbacks[event].push(fn);\n\n\t\treturn this;\n\t}\n\n\tprotected emit(event: string, ...args: any): this {\n\t\tconst callbacks = this.callbacks[event];\n\n\t\tif (callbacks) {\n\t\t\tcallbacks.forEach((callback) => callback.apply(this, args));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic off(event: string, fn?: Function): this {\n\t\tconst callbacks = this.callbacks[event];\n\n\t\tif (callbacks) {\n\t\t\tif (fn) {\n\t\t\t\tthis.callbacks[event] = callbacks.filter((callback) => callback !== fn);\n\t\t\t} else {\n\t\t\t\tdelete this.callbacks[event];\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tremoveAllListeners(): void {\n\t\tthis.callbacks = {};\n\t}\n}\n","import type { Encoder } from \"lib0/encoding\";\nimport type { Event, MessageEvent } from \"ws\";\nimport type { Awareness } from \"y-protocols/awareness\";\nimport type * as Y from \"yjs\";\nimport type { CloseEvent } from \"./CloseEvents.ts\";\nimport type { IncomingMessage } from \"./IncomingMessage.ts\";\nimport type { OutgoingMessage } from \"./OutgoingMessage.ts\";\nimport type { AuthenticationMessage } from \"./OutgoingMessages/AuthenticationMessage.ts\";\nimport type { AwarenessMessage } from \"./OutgoingMessages/AwarenessMessage.ts\";\nimport type { QueryAwarenessMessage } from \"./OutgoingMessages/QueryAwarenessMessage.ts\";\nimport type { SyncStepOneMessage } from \"./OutgoingMessages/SyncStepOneMessage.ts\";\nimport type { SyncStepTwoMessage } from \"./OutgoingMessages/SyncStepTwoMessage.ts\";\nimport type { UpdateMessage } from \"./OutgoingMessages/UpdateMessage.ts\";\n\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 enum MessageType {\n Sync = 0,\n Awareness = 1,\n Auth = 2,\n QueryAwareness = 3,\n Subdoc = 4,\n Stateless = 5,\n CLOSE = 7,\n SyncStatus = 8,\n}\n\nexport enum WebSocketStatus {\n Connecting = \"connecting\",\n Connected = \"connected\",\n Disconnected = \"disconnected\",\n}\n\nexport type AuthorizedScope = \"service\" | \"admin\" | \"owner\" | \"editor\" | \"viewer\" | \"read-write\" | \"readonly\";\n\nexport interface OutgoingMessageInterface {\n encoder: Encoder;\n type?: MessageType;\n}\n\nexport interface OutgoingMessageArguments {\n documentName: string;\n token: string;\n document: Y.Doc;\n awareness: Awareness;\n clients: number[];\n states: Map<number, { [key: string]: any }>;\n update: any;\n payload: string;\n encoder: Encoder;\n}\n\nexport interface Constructable<T> {\n new (...args: any): T;\n}\n\nexport type ConstructableOutgoingMessage =\n | Constructable<AuthenticationMessage>\n | Constructable<AwarenessMessage>\n | Constructable<QueryAwarenessMessage>\n | Constructable<SyncStepOneMessage>\n | Constructable<SyncStepTwoMessage>\n | Constructable<UpdateMessage>;\n\nexport type onAuthenticationFailedParameters = {\n reason: string;\n};\n\nexport type onAuthenticatedParameters = {\n scope: AuthorizedScope;\n};\n\nexport type onOpenParameters = {\n event: Event;\n};\n\nexport type onMessageParameters = {\n event: MessageEvent;\n message: IncomingMessage;\n};\n\nexport type onOutgoingMessageParameters = {\n message: OutgoingMessage;\n};\n\nexport type onStatusParameters = {\n status: WebSocketStatus;\n};\n\nexport type onSyncedParameters = {\n state: boolean;\n};\n\nexport type onUnsyncedChangesParameters = {\n number: number;\n};\n\nexport type onDisconnectParameters = {\n event: CloseEvent;\n};\n\nexport type onCloseParameters = {\n event: CloseEvent;\n};\n\nexport type onAwarenessUpdateParameters = {\n states: StatesArray;\n};\n\nexport type onAwarenessChangeParameters = {\n states: StatesArray;\n};\n\nexport type onStatelessParameters = {\n payload: string;\n};\n\nexport type StatesArray = { clientId: number; [key: string | number]: any }[];\n\n// ── Abracadabra extensions ────────────────────────────────────────────────────\n\nexport type EffectiveRole = \"service\" | \"admin\" | \"owner\" | \"editor\" | \"viewer\" | null;\n\n/**\n * Ed25519 identity for passwordless crypto auth.\n *\n * The public key is the sole identifier sent to the server during the\n * challenge-response handshake. Username is decoupled from auth and is\n * managed separately as a mutable display name (see PATCH /users/me).\n */\nexport interface CryptoIdentity {\n /** base64url-encoded Ed25519 public key (32 bytes). Primary auth identifier. */\n publicKey: string;\n}\n\nexport interface SubdocRegisteredEvent {\n childId: string;\n parentId: string;\n}\n\nexport type onSubdocRegisteredParameters = SubdocRegisteredEvent;\n\nexport type onSubdocLoadedParameters = {\n childId: string;\n provider: import(\"./AbracadabraProvider.ts\").AbracadabraProvider;\n};\n\nexport interface AbracadabraOutgoingMessageArguments extends OutgoingMessageArguments {\n childDocumentName: string;\n}\n\n// ── REST API response types ──────────────────────────────────────────────────\n\nexport interface UserProfile {\n id: string;\n username: string;\n email: string | null;\n displayName: string | null;\n role: string;\n}\n\nexport interface DocumentMeta {\n id: string;\n parent_id: string | null;\n}\n\nexport interface UploadMeta {\n id: string;\n doc_id: string;\n filename: string;\n}\n\nexport interface UploadInfo {\n id: string;\n filename: string;\n mime_type: string;\n size: number;\n}\n\nexport interface PublicKeyInfo {\n id: string;\n publicKey: string;\n deviceName: string | null;\n revoked: boolean;\n}\n\nexport interface PermissionEntry {\n user_id: string;\n role: \"owner\" | \"editor\" | \"viewer\" | \"observer\";\n username: string;\n display_name: string | null;\n}\n\nexport interface HealthStatus {\n status: string;\n version: string;\n active_documents: number;\n}\n\nexport interface ServerInfo {\n /** Human-readable server name set by the operator. */\n name?: string;\n /** Server version string. */\n version?: string;\n /** Entry-point document ID advertised by the server, if configured. */\n index_doc_id?: string;\n}\n\n// ── Search ───────────────────────────────────────────────────────────────────\n\nexport interface SearchResult {\n docId: string;\n /** Number of matching trigrams — higher is better. */\n score: number;\n}\n\n// ── Invites ──────────────────────────────────────────────────────────────────\n\nexport interface InviteRow {\n code: string;\n createdBy: string | null;\n role: string;\n maxUses: number;\n useCount: number;\n expiresAt: number | null;\n revoked: boolean;\n createdAt: number;\n}\n\n// ── Upload queue ─────────────────────────────────────────────────────────────\n\nexport type UploadQueueStatus = \"pending\" | \"uploading\" | \"done\" | \"error\";\n\nexport interface UploadQueueEntry {\n /** Client-generated UUID. */\n id: string;\n docId: string;\n /** File or Blob to upload. File extends Blob and survives IDB as Blob. */\n file: Blob;\n /** Eagerly captured filename (from File.name or explicit arg). */\n filename: string;\n status: UploadQueueStatus;\n createdAt: number;\n error?: string;\n}\n\nexport interface DocEncryptionInfo {\n mode: \"none\" | \"cse\" | \"e2e\";\n effective_mode: \"none\" | \"cse\" | \"e2e\";\n inherited_from?: string;\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 * Check whether n is negative, while considering the -0 edge case. While `-0 < 0` is false, this\n * function returns true for -0,-1,,.. and returns false for 0,1,2,...\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also distinguishes between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* c8 ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\nexport const HIGHEST_INT32 = binary.BITS31\nexport const HIGHEST_UINT32 = binary.BITS32\n\n/* c8 ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n\n/**\n * Count the number of \"1\" bits in an unsigned 32bit number.\n *\n * Super fun bitcount algorithm by Brian Kernighan.\n *\n * @param {number} n\n */\nexport const countBits = n => {\n n &= binary.BITS32\n let count = 0\n while (n) {\n n &= (n - 1)\n count++\n }\n return count\n}\n","import * as array from './array.js'\n\n/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * The largest utf16 character.\n * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8)\n */\nexport const MAX_UTF16_CHARACTER = fromCharCode(65535)\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array<ArrayBuffer>}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* c8 ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array<ArrayBuffer>}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* c8 ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* c8 ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* c8 ignore start */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* c8 ignore next */\n utf8TextDecoder = null\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* c8 ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n\n/**\n * @param {string} source\n * @param {number} n\n */\nexport const repeat = (source, n) => array.unfold(n, () => source).join('')\n\n/**\n * Escape HTML characters &,<,>,',\" to their respective HTML entities &,<,>,',"\n *\n * @param {string} str\n */\nexport const escapeHTML = str =>\n str.replace(/[&<>'\"]/g, r => /** @type {string} */ ({\n '&': '&',\n '<': '<',\n '>': '>',\n \"'\": ''',\n '\"': '"'\n }[r]))\n\n/**\n * Reverse of `escapeHTML`\n *\n * @param {string} str\n */\nexport const unescapeHTML = str =>\n str.replace(/&|<|>|'|"/g, r => /** @type {string} */ ({\n '&': '&',\n '<': '<',\n '>': '>',\n ''': \"'\",\n '"': '\"'\n }[r]))\n","/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* c8 ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n\n/**\n * @param {boolean} property\n * @return {asserts property is true}\n */\nexport const assert = property => { if (!property) throw create('Assert failed') }\n","/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\nimport * as string from './string.js'\nimport * as array from './array.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array<Uint8Array>}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * @param {function(Encoder):void} f\n */\nexport const encode = (f) => {\n const encoder = createEncoder()\n f(encoder)\n return toUint8Array(encoder)\n}\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Check whether encoder is empty.\n *\n * @function\n * @param {Encoder} encoder\n * @return {boolean}\n */\nexport const hasContent = encoder => encoder.cpos > 0 || encoder.bufs.length > 0\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array<ArrayBuffer>} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nexport const verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer. Max encodable integer is 2^53.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num = math.floor(num / 64) // shift >>> 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n}\n\n/**\n * A cache to store strings temporarily\n */\nconst _strBuffer = new Uint8Array(30000)\nconst _maxStrBSize = _strBuffer.length / 3\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringNative = (encoder, str) => {\n if (str.length < _maxStrBSize) {\n // We can encode the string into the existing buffer\n /* c8 ignore next */\n const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0\n writeVarUint(encoder, written)\n for (let i = 0; i < written; i++) {\n write(encoder, _strBuffer[i])\n }\n } else {\n writeVarUint8Array(encoder, string.encodeUtf8(str))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringPolyfill = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\n/* c8 ignore next */\nexport const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill\n\n/**\n * Write a string terminated by a special byte sequence. This is not very performant and is\n * generally discouraged. However, the resulting byte arrays are lexiographically ordered which\n * makes this a nice feature for databases.\n *\n * The string will be encoded using utf8 and then terminated and escaped using writeTerminatingUint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const writeTerminatedString = (encoder, str) =>\n writeTerminatedUint8Array(encoder, string.encodeUtf8(str))\n\n/**\n * Write a terminating Uint8Array. Note that this is not performant and is generally\n * discouraged. There are few situations when this is needed.\n *\n * We use 0x0 as a terminating character. 0x1 serves as an escape character for 0x0 and 0x1.\n *\n * Example: [0,1,2] is encoded to [1,0,1,1,2,0]. 0x0, and 0x1 needed to be escaped using 0x1. Then\n * the result is terminated using the 0x0 character.\n *\n * This is basically how many systems implement null terminated strings. However, we use an escape\n * character 0x1 to avoid issues and potenial attacks on our database (if this is used as a key\n * encoder for NoSql databases).\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} buf The string that is to be encoded.\n */\nexport const writeTerminatedUint8Array = (encoder, buf) => {\n for (let i = 0; i < buf.length; i++) {\n const b = buf[i]\n if (b === 0 || b === 1) {\n write(encoder, 1)\n }\n write(encoder, buf[i])\n }\n write(encoder, 0)\n}\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * @typedef {Array<AnyEncodable>} AnyEncodableArray\n */\n\n/**\n * @typedef {undefined|null|number|bigint|boolean|string|{[k:string]:AnyEncodable}|AnyEncodableArray|Uint8Array} AnyEncodable\n */\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object<string,any> | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array<any> | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {AnyEncodable} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && math.abs(data) <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (array.isArray(data)) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array<string>}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n","/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as binary from './binary.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as string from './string.js'\nimport * as error from './error.js'\nimport * as encoding from './encoding.js'\n\nconst errorUnexpectedEndOfArray = error.create('Unexpected end of array')\nconst errorIntegerOutOfRange = error.create('Integer out of Range')\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n * @template {ArrayBufferLike} [Buf=ArrayBufferLike]\n */\nexport class Decoder {\n /**\n * @param {Uint8Array<Buf>} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array<Buf>}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Uint8Array<Buf>} uint8Array\n * @return {Decoder<Buf>}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Decoder<Buf>} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array<Buf>}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Decoder<Buf>} decoder\n * @return {Uint8Array<Buf>}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let mult = 1\n const len = decoder.arr.length\n while (decoder.pos < len) {\n const r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num\n mult *= 128 // next iteration, shift 7 \"more\" to the left\n if (r < binary.BIT8) {\n return num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let mult = 64\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n const len = decoder.arr.length\n while (decoder.pos < len) {\n r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult\n mult *= 128\n if (r < binary.BIT8) {\n return sign * num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * We don't test this function anymore as we use native decoding/encoding by default now.\n * Better not modify this anymore..\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\n/* c8 ignore start */\nexport const _readVarStringPolyfill = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n/* c8 ignore stop */\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n */\nexport const _readVarStringNative = decoder =>\n /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder))\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n *\n */\n/* c8 ignore next */\nexport const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill\n\n/**\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTerminatedUint8Array = decoder => {\n const encoder = encoding.createEncoder()\n let b\n while (true) {\n b = readUint8(decoder)\n if (b === 0) {\n return encoding.toUint8Array(encoder)\n }\n if (b === 1) {\n b = readUint8(decoder)\n }\n encoding.write(encoder, b)\n }\n}\n\n/**\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const readTerminatedString = decoder => string.decodeUtf8(readTerminatedUint8Array(decoder))\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array<function(Decoder):any>}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object<string,any>\n const len = readVarUint(decoder)\n /**\n * @type {Object<string,any>}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array<any>\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = math.floor(diff / 2) // shift >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n","import type { Decoder } from \"lib0/decoding\";\nimport {\n\tcreateDecoder,\n\tpeekVarString,\n\treadVarUint,\n\treadVarUint8Array,\n\treadVarString,\n} from \"lib0/decoding\";\nimport type { Encoder } from \"lib0/encoding\";\nimport {\n\tcreateEncoder,\n\twriteVarUint,\n\twriteVarUint8Array,\n\twriteVarString,\n\tlength,\n} from \"lib0/encoding\";\nimport type { MessageType } from \"./types.ts\";\n\nexport class IncomingMessage {\n\tdata: any;\n\n\tencoder: Encoder;\n\n\tdecoder: Decoder;\n\n\tconstructor(data: any) {\n\t\tthis.data = data;\n\t\tthis.encoder = createEncoder();\n\t\tthis.decoder = createDecoder(new Uint8Array(this.data));\n\t}\n\n\tpeekVarString(): string {\n\t\treturn peekVarString(this.decoder);\n\t}\n\n\treadVarUint(): MessageType {\n\t\treturn readVarUint(this.decoder);\n\t}\n\n\treadVarString(): string {\n\t\treturn readVarString(this.decoder);\n\t}\n\n\treadVarUint8Array() {\n\t\treturn readVarUint8Array(this.decoder);\n\t}\n\n\twriteVarUint(type: MessageType) {\n\t\treturn writeVarUint(this.encoder, type);\n\t}\n\n\twriteVarString(string: string) {\n\t\treturn writeVarString(this.encoder, string);\n\t}\n\n\twriteVarUint8Array(data: Uint8Array) {\n\t\treturn writeVarUint8Array(this.encoder, data);\n\t}\n\n\tlength() {\n\t\treturn length(this.encoder);\n\t}\n}\n","import type { Encoder } from \"lib0/encoding\";\nimport { createEncoder, toUint8Array } from \"lib0/encoding\";\nimport type {\n\tMessageType,\n\tOutgoingMessageArguments,\n\tOutgoingMessageInterface,\n} from \"./types.ts\";\n\nexport class OutgoingMessage implements OutgoingMessageInterface {\n\tencoder: Encoder;\n\n\ttype?: MessageType;\n\n\tconstructor() {\n\t\tthis.encoder = createEncoder();\n\t}\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\treturn args.encoder;\n\t}\n\n\ttoUint8Array() {\n\t\treturn toUint8Array(this.encoder);\n\t}\n}\n","import * as encoding from \"lib0/encoding\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class CloseMessage extends OutgoingMessage {\n\ttype = MessageType.CLOSE;\n\n\tdescription = \"Ask the server to close the connection\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tencoding.writeVarString(this.encoder, args.documentName!);\n\t\tencoding.writeVarUint(this.encoder, this.type);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { WsReadyStates } from \"./types.ts\";\nimport { retry } from \"@lifeomic/attempt\";\nimport * as time from \"lib0/time\";\nimport type { Event, MessageEvent } from \"ws\";\nimport EventEmitter from \"./EventEmitter.ts\";\nimport type { AbracadabraBaseProvider } from \"./AbracadabraBaseProvider.ts\";\nimport { IncomingMessage } from \"./IncomingMessage.ts\";\nimport { CloseMessage } from \"./OutgoingMessages/CloseMessage.ts\";\nimport {\n WebSocketStatus,\n type onAwarenessChangeParameters,\n type onAwarenessUpdateParameters,\n type onCloseParameters,\n type onDisconnectParameters,\n type onMessageParameters,\n type onOpenParameters,\n type onOutgoingMessageParameters,\n type onStatusParameters,\n} from \"./types.ts\";\n\nexport type AbracadabraWebSocketConn = WebSocket & { identifier: string };\n/** @deprecated Use AbracadabraWebSocketConn */\nexport type HocuspocusWebSocket = AbracadabraWebSocketConn;\n/** @deprecated Use AbracadabraWebSocketConn */\nexport type HocusPocusWebSocket = AbracadabraWebSocketConn;\n\nexport type AbracadabraWSConfiguration = Required<\n Pick<CompleteAbracadabraWSConfiguration, \"url\">\n> &\n Partial<CompleteAbracadabraWSConfiguration>;\n\n/** @deprecated Use AbracadabraWSConfiguration */\nexport type HocuspocusProviderWebsocketConfiguration = AbracadabraWSConfiguration;\n\nexport interface CompleteAbracadabraWSConfiguration {\n /**\n * Whether to connect automatically when creating the provider instance. Default=true\n */\n autoConnect: boolean;\n\n /**\n * URL of your @hocuspocus/server instance\n */\n url: string;\n\n /**\n * By default, trailing slashes are removed from the URL. Set this to true\n * to preserve trailing slashes if your server configuration requires them.\n */\n preserveTrailingSlash: boolean;\n\n /**\n * An optional WebSocket polyfill, for example for Node.js\n */\n WebSocketPolyfill: any;\n\n /**\n * Disconnect when no message is received for the defined amount of milliseconds.\n */\n messageReconnectTimeout: number;\n /**\n * The delay between each attempt in milliseconds. You can provide a factor to have the delay grow exponentially.\n */\n delay: number;\n /**\n * The initialDelay is the amount of time to wait before making the first attempt. This option should typically be 0 since you typically want the first attempt to happen immediately.\n */\n initialDelay: number;\n /**\n * The factor option is used to grow the delay exponentially.\n */\n factor: number;\n /**\n * The maximum number of attempts or 0 if there is no limit on number of attempts.\n */\n maxAttempts: number;\n /**\n * minDelay is used to set a lower bound of delay when jitter is enabled. This property has no effect if jitter is disabled.\n */\n minDelay: number;\n /**\n * The maxDelay option is used to set an upper bound for the delay when factor is enabled. A value of 0 can be provided if there should be no upper bound when calculating delay.\n */\n maxDelay: number;\n /**\n * If jitter is true then the calculated delay will be a random integer value between minDelay and the calculated delay for the current iteration.\n */\n jitter: boolean;\n /**\n * A timeout in milliseconds. If timeout is non-zero then a timer is set using setTimeout. If the timeout is triggered then future attempts will be aborted.\n */\n timeout: number;\n handleTimeout: (() => Promise<unknown>) | null;\n onOpen: (data: onOpenParameters) => void;\n onConnect: () => void;\n onMessage: (data: onMessageParameters) => void;\n onOutgoingMessage: (data: onOutgoingMessageParameters) => void;\n onStatus: (data: onStatusParameters) => void;\n onDisconnect: (data: onDisconnectParameters) => void;\n onClose: (data: onCloseParameters) => void;\n onDestroy: () => void;\n onAwarenessUpdate: (data: onAwarenessUpdateParameters) => void;\n onAwarenessChange: (data: onAwarenessChangeParameters) => void;\n\n /**\n * Map of attached providers keyed by documentName.\n */\n providerMap: Map<string, AbracadabraBaseProvider>;\n}\n\n/** @deprecated Use CompleteAbracadabraWSConfiguration */\nexport type CompleteHocuspocusProviderWebsocketConfiguration = CompleteAbracadabraWSConfiguration;\n\nexport class AbracadabraWS extends EventEmitter {\n private messageQueue: any[] = [];\n\n public configuration: CompleteAbracadabraWSConfiguration = {\n url: \"\",\n autoConnect: true,\n preserveTrailingSlash: false,\n // @ts-ignore\n document: undefined,\n WebSocketPolyfill: undefined,\n // TODO: this should depend on awareness.outdatedTime\n messageReconnectTimeout: 30000,\n // 1 second\n delay: 1000,\n // instant\n initialDelay: 0,\n // double the delay each time\n factor: 2,\n // unlimited retries\n maxAttempts: 0,\n // wait at least 1 second\n minDelay: 1000,\n // at least every 30 seconds\n maxDelay: 30000,\n // randomize\n jitter: true,\n // retry forever\n timeout: 0,\n onOpen: () => null,\n onConnect: () => null,\n onMessage: () => null,\n onOutgoingMessage: () => null,\n onStatus: () => null,\n onDisconnect: () => null,\n onClose: () => null,\n onDestroy: () => null,\n onAwarenessUpdate: () => null,\n onAwarenessChange: () => null,\n handleTimeout: null,\n providerMap: new Map(),\n };\n\n webSocket: AbracadabraWebSocketConn | null = null;\n\n webSocketHandlers: { [key: string]: any } = {};\n\n shouldConnect = true;\n\n status = WebSocketStatus.Disconnected;\n\n lastMessageReceived = 0;\n\n identifier = 0;\n\n intervals: any = {\n connectionChecker: null,\n };\n\n connectionAttempt: {\n resolve: (value?: any) => void;\n reject: (reason?: any) => void;\n } | null = null;\n\n constructor(configuration: AbracadabraWSConfiguration) {\n super();\n this.setConfiguration(configuration);\n\n this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill\n ? configuration.WebSocketPolyfill\n : WebSocket;\n\n this.on(\"open\", this.configuration.onOpen);\n this.on(\"open\", this.onOpen.bind(this));\n this.on(\"connect\", this.configuration.onConnect);\n this.on(\"message\", this.configuration.onMessage);\n this.on(\"outgoingMessage\", this.configuration.onOutgoingMessage);\n this.on(\"status\", this.configuration.onStatus);\n this.on(\"disconnect\", this.configuration.onDisconnect);\n this.on(\"close\", this.configuration.onClose);\n this.on(\"destroy\", this.configuration.onDestroy);\n this.on(\"awarenessUpdate\", this.configuration.onAwarenessUpdate);\n this.on(\"awarenessChange\", this.configuration.onAwarenessChange);\n\n this.on(\"close\", this.onClose.bind(this));\n this.on(\"message\", this.onMessage.bind(this));\n\n this.intervals.connectionChecker = setInterval(\n this.checkConnection.bind(this),\n this.configuration.messageReconnectTimeout / 10,\n );\n\n if (this.shouldConnect) {\n this.connect();\n }\n }\n\n receivedOnOpenPayload?: Event | undefined = undefined;\n\n async onOpen(event: Event) {\n this.status = WebSocketStatus.Connected;\n this.emit(\"status\", { status: WebSocketStatus.Connected });\n\n this.cancelWebsocketRetry = undefined;\n this.receivedOnOpenPayload = event;\n }\n\n attach(provider: AbracadabraBaseProvider) {\n this.configuration.providerMap.set(provider.configuration.name, provider);\n\n if (this.status === WebSocketStatus.Disconnected && this.shouldConnect) {\n this.connect();\n }\n\n if (this.receivedOnOpenPayload && this.status === WebSocketStatus.Connected) {\n provider.onOpen(this.receivedOnOpenPayload);\n }\n }\n\n detach(provider: AbracadabraBaseProvider) {\n if (this.configuration.providerMap.has(provider.configuration.name)) {\n provider.send(CloseMessage, {\n documentName: provider.configuration.name,\n });\n this.configuration.providerMap.delete(provider.configuration.name);\n }\n }\n\n public setConfiguration(\n configuration: Partial<AbracadabraWSConfiguration> = {},\n ): void {\n this.configuration = { ...this.configuration, ...configuration };\n\n if (!this.configuration.autoConnect) {\n this.shouldConnect = false;\n }\n }\n\n cancelWebsocketRetry?: () => void;\n\n async connect() {\n if (this.status === WebSocketStatus.Connected) {\n return;\n }\n\n // Always cancel any previously initiated connection retryer instances\n if (this.cancelWebsocketRetry) {\n this.cancelWebsocketRetry();\n this.cancelWebsocketRetry = undefined;\n }\n\n this.receivedOnOpenPayload = undefined;\n this.shouldConnect = true;\n\n const abortableRetry = () => {\n let cancelAttempt = false;\n\n const retryPromise = retry(this.createWebSocketConnection.bind(this), {\n delay: this.configuration.delay,\n initialDelay: this.configuration.initialDelay,\n factor: this.configuration.factor,\n maxAttempts: this.configuration.maxAttempts,\n minDelay: this.configuration.minDelay,\n maxDelay: this.configuration.maxDelay,\n jitter: this.configuration.jitter,\n timeout: this.configuration.timeout,\n handleTimeout: this.configuration.handleTimeout,\n beforeAttempt: (context) => {\n if (!this.shouldConnect || cancelAttempt) {\n context.abort();\n }\n },\n }).catch((error: any) => {\n // If we aborted the connection attempt then don't throw an error\n // ref: https://github.com/lifeomic/attempt/blob/master/src/index.ts#L136\n if (error && error.code !== \"ATTEMPT_ABORTED\") {\n throw error;\n }\n });\n\n return {\n retryPromise,\n cancelFunc: () => {\n cancelAttempt = true;\n },\n };\n };\n\n const { retryPromise, cancelFunc } = abortableRetry();\n this.cancelWebsocketRetry = cancelFunc;\n\n return retryPromise;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n attachWebSocketListeners(ws: AbracadabraWebSocketConn, reject: Function) {\n const { identifier } = ws;\n const onMessageHandler = (payload: any) => this.emit(\"message\", payload);\n const onCloseHandler = (payload: any) => this.emit(\"close\", { event: payload });\n const onOpenHandler = (payload: any) => this.emit(\"open\", payload);\n const onErrorHandler = (err: any) => {\n reject(err);\n };\n\n this.webSocketHandlers[identifier] = {\n message: onMessageHandler,\n close: onCloseHandler,\n open: onOpenHandler,\n error: onErrorHandler,\n };\n\n const handlers = this.webSocketHandlers[ws.identifier];\n\n Object.keys(handlers).forEach((name) => {\n ws.addEventListener(name, handlers[name]);\n });\n }\n\n cleanupWebSocket() {\n if (!this.webSocket) {\n return;\n }\n const { identifier } = this.webSocket;\n const handlers = this.webSocketHandlers[identifier];\n\n Object.keys(handlers).forEach((name) => {\n this.webSocket?.removeEventListener(name, handlers[name]);\n delete this.webSocketHandlers[identifier];\n });\n\n try {\n // Check if the WebSocket is still in CONNECTING state (0)\n // If so, calling close() might throw in some environments or be race-prone\n if (this.webSocket.readyState !== 0 && this.webSocket.readyState !== 3) {\n this.webSocket.close();\n }\n } catch (e) {\n // Ignore errors during close\n }\n\n this.webSocket = null;\n }\n\n createWebSocketConnection() {\n return new Promise((resolve, reject) => {\n if (this.webSocket) {\n this.messageQueue = [];\n this.cleanupWebSocket();\n }\n this.lastMessageReceived = 0;\n this.identifier += 1;\n\n // Init the WebSocket connection\n const ws = new this.configuration.WebSocketPolyfill(this.url);\n ws.binaryType = \"arraybuffer\";\n ws.identifier = this.identifier;\n\n this.attachWebSocketListeners(ws, reject);\n\n this.webSocket = ws;\n\n // Reset the status\n this.status = WebSocketStatus.Connecting;\n this.emit(\"status\", { status: WebSocketStatus.Connecting });\n\n // Store resolve/reject for later use\n this.connectionAttempt = {\n resolve,\n reject,\n };\n });\n }\n\n onMessage(event: MessageEvent) {\n this.resolveConnectionAttempt();\n\n this.lastMessageReceived = time.getUnixTime();\n\n const message = new IncomingMessage(event.data);\n const documentName = message.peekVarString();\n\n this.configuration.providerMap.get(documentName)?.onMessage(event);\n }\n\n resolveConnectionAttempt() {\n if (this.connectionAttempt) {\n this.connectionAttempt.resolve();\n this.connectionAttempt = null;\n\n this.status = WebSocketStatus.Connected;\n this.emit(\"status\", { status: WebSocketStatus.Connected });\n this.emit(\"connect\");\n this.messageQueue.forEach((message) => this.send(message));\n this.messageQueue = [];\n }\n }\n\n stopConnectionAttempt() {\n this.connectionAttempt = null;\n }\n\n rejectConnectionAttempt() {\n this.connectionAttempt?.reject();\n this.connectionAttempt = null;\n }\n\n closeTries = 0;\n\n checkConnection() {\n // Don't check the connection when it's not even established\n if (this.status !== WebSocketStatus.Connected) {\n return;\n }\n\n // Don't close the connection while waiting for the first message\n if (!this.lastMessageReceived) {\n return;\n }\n\n // Don't close the connection when a message was received recently\n if (\n this.configuration.messageReconnectTimeout >=\n time.getUnixTime() - this.lastMessageReceived\n ) {\n return;\n }\n\n // No message received in a long time, not even your own\n // Awareness updates, which are updated every 15 seconds\n // if awareness is enabled.\n this.closeTries += 1;\n // https://bugs.webkit.org/show_bug.cgi?id=247943\n if (this.closeTries > 2) {\n this.onClose({\n event: {\n code: 4408,\n reason: \"forced\",\n },\n });\n this.closeTries = 0;\n } else {\n this.webSocket?.close();\n this.messageQueue = [];\n }\n }\n\n get serverUrl() {\n if (this.configuration.preserveTrailingSlash) {\n return this.configuration.url;\n }\n\n // By default, ensure that the URL never ends with /\n let url = this.configuration.url;\n while (url[url.length - 1] === \"/\") {\n url = url.slice(0, url.length - 1);\n }\n\n return url;\n }\n\n get url() {\n return this.serverUrl;\n }\n\n disconnect() {\n this.shouldConnect = false;\n\n if (this.webSocket === null) {\n return;\n }\n\n try {\n this.webSocket.close();\n this.messageQueue = [];\n } catch (e) {\n console.error(e);\n }\n }\n\n send(message: any) {\n if (this.webSocket?.readyState === WsReadyStates.Open) {\n this.webSocket.send(message);\n } else {\n this.messageQueue.push(message);\n }\n }\n\n onClose({ event }: onCloseParameters) {\n this.closeTries = 0;\n this.cleanupWebSocket();\n\n if (this.connectionAttempt) {\n // That connection attempt failed.\n this.rejectConnectionAttempt();\n }\n\n // Let's update the connection status.\n this.status = WebSocketStatus.Disconnected;\n this.emit(\"status\", { status: WebSocketStatus.Disconnected });\n\n // Detect server-side rate-limit close (code 4429).\n const isRateLimited = (event as any)?.code === 4429;\n this.emit(\"disconnect\", { event });\n if (isRateLimited) {\n this.emit(\"rateLimited\");\n }\n\n // trigger connect if no retry is running and we want to have a connection\n if (!this.cancelWebsocketRetry && this.shouldConnect) {\n // Apply a much longer delay for rate-limited closes to let the server window reset.\n const delay = isRateLimited ? 60_000 : this.configuration.delay;\n setTimeout(() => {\n this.connect();\n }, delay);\n }\n }\n\n destroy() {\n this.emit(\"destroy\");\n\n clearInterval(this.intervals.connectionChecker);\n\n // If there is still a connection attempt outstanding then we should stop\n // it before calling disconnect, otherwise it will be rejected in the onClose\n // handler and trigger a retry\n this.stopConnectionAttempt();\n\n this.disconnect();\n\n this.removeAllListeners();\n\n this.cleanupWebSocket();\n }\n}\n\n/** @deprecated Use AbracadabraWS */\nexport const HocuspocusProviderWebsocket = AbracadabraWS;\n/** @deprecated Use AbracadabraWS */\nexport type HocuspocusProviderWebsocket = AbracadabraWS;\n","import * as encoding from \"lib0/encoding\";\nimport * as decoding from \"lib0/decoding\";\nimport type { AuthorizedScope } from \"./types.ts\";\n\nexport enum AuthMessageType {\n\tToken = 0,\n\tPermissionDenied = 1,\n\tAuthenticated = 2,\n}\n\nexport const writeAuthentication = (\n\tencoder: encoding.Encoder,\n\tauth: string,\n) => {\n\tencoding.writeVarUint(encoder, AuthMessageType.Token);\n\tencoding.writeVarString(encoder, auth);\n};\n\nexport const writePermissionDenied = (\n\tencoder: encoding.Encoder,\n\treason: string,\n) => {\n\tencoding.writeVarUint(encoder, AuthMessageType.PermissionDenied);\n\tencoding.writeVarString(encoder, reason);\n};\n\nexport const writeAuthenticated = (\n\tencoder: encoding.Encoder,\n\tscope: AuthorizedScope,\n) => {\n\tencoding.writeVarUint(encoder, AuthMessageType.Authenticated);\n\tencoding.writeVarString(encoder, scope);\n};\n\nexport const writeTokenSyncRequest = (\n\tencoder: encoding.Encoder,\n) => {\n\tencoding.writeVarUint(encoder, AuthMessageType.Token);\n};\n\nexport const readAuthMessage = (\n\tdecoder: decoding.Decoder,\n\tsendToken: () => void,\n\tpermissionDeniedHandler: (reason: string) => void,\n\tauthenticatedHandler: (scope: string) => void,\n) => {\n\tswitch (decoding.readVarUint(decoder)) {\n\t\tcase AuthMessageType.Token: {\n\t\t\tsendToken();\n\t\t\tbreak;\n\t\t}\n\t\tcase AuthMessageType.PermissionDenied: {\n\t\t\tpermissionDeniedHandler(decoding.readVarString(decoder));\n\t\t\tbreak;\n\t\t}\n\t\tcase AuthMessageType.Authenticated: {\n\t\t\tauthenticatedHandler(decoding.readVarString(decoder));\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t}\n};\n","/**\n * @module sync-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as Y from 'yjs'\n\n/**\n * @typedef {Map<number, number>} StateMap\n */\n\n/**\n * Core Yjs defines two message types:\n * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.\n * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it\n * received all information from the remote client.\n *\n * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection\n * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both\n * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.\n *\n * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.\n * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies\n * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the\n * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can\n * easily be implemented on top of http and websockets. 2. The server should only reply to requests, and not initiate them.\n * Therefore it is necessary that the client initiates the sync.\n *\n * Construction of a message:\n * [messageType : varUint, message definition..]\n *\n * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!\n *\n * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)\n */\n\nexport const messageYjsSyncStep1 = 0\nexport const messageYjsSyncStep2 = 1\nexport const messageYjsUpdate = 2\n\n/**\n * Create a sync step 1 message based on the state of the current shared document.\n *\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n */\nexport const writeSyncStep1 = (encoder, doc) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep1)\n const sv = Y.encodeStateVector(doc)\n encoding.writeVarUint8Array(encoder, sv)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n * @param {Uint8Array} [encodedStateVector]\n */\nexport const writeSyncStep2 = (encoder, doc, encodedStateVector) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep2)\n encoding.writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector))\n}\n\n/**\n * Read SyncStep1 message and reply with SyncStep2.\n *\n * @param {decoding.Decoder} decoder The reply to the received message\n * @param {encoding.Encoder} encoder The received message\n * @param {Y.Doc} doc\n */\nexport const readSyncStep1 = (decoder, encoder, doc) =>\n writeSyncStep2(encoder, doc, decoding.readVarUint8Array(decoder))\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n * @param {(error:Error)=>any} [errorHandler]\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin, errorHandler) => {\n try {\n Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n } catch (error) {\n if (errorHandler != null) errorHandler(/** @type {Error} */ (error))\n // This catches errors that are thrown by event handlers\n console.error('Caught error while handling a Yjs update', error)\n }\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Uint8Array} update\n */\nexport const writeUpdate = (encoder, update) => {\n encoding.writeVarUint(encoder, messageYjsUpdate)\n encoding.writeVarUint8Array(encoder, update)\n}\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n * @param {(error:Error)=>any} [errorHandler]\n */\nexport const readUpdate = readSyncStep2\n\n/**\n * @param {decoding.Decoder} decoder A message received from another client\n * @param {encoding.Encoder} encoder The reply message. Does not need to be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n * @param {(error:Error)=>any} [errorHandler] Optional error handler that catches errors when reading Yjs messages.\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin, errorHandler) => {\n const messageType = decoding.readVarUint(decoder)\n switch (messageType) {\n case messageYjsSyncStep1:\n readSyncStep1(decoder, encoder, doc)\n break\n case messageYjsSyncStep2:\n readSyncStep2(decoder, doc, transactionOrigin, errorHandler)\n break\n case messageYjsUpdate:\n readUpdate(decoder, doc, transactionOrigin, errorHandler)\n break\n default:\n throw new Error('Unknown message type')\n }\n return messageType\n}\n","import { readAuthMessage } from \"./auth.ts\";\nimport { readVarInt, readVarString } from \"lib0/decoding\";\nimport type { CloseEvent } from \"ws\";\nimport * as awarenessProtocol from \"y-protocols/awareness\";\nimport { messageYjsSyncStep2, readSyncMessage } from \"y-protocols/sync\";\nimport type { AbracadabraBaseProvider } from \"./AbracadabraBaseProvider.ts\";\nimport type { IncomingMessage } from \"./IncomingMessage.ts\";\nimport { OutgoingMessage } from \"./OutgoingMessage.ts\";\nimport { MessageType } from \"./types.ts\";\n\nexport class MessageReceiver {\n message: IncomingMessage;\n\n constructor(message: IncomingMessage) {\n this.message = message;\n }\n\n public apply(provider: AbracadabraBaseProvider, emitSynced: boolean) {\n const { message } = this;\n const type = message.readVarUint();\n\n const emptyMessageLength = message.length();\n\n switch (type) {\n case MessageType.Sync:\n this.applySyncMessage(provider, emitSynced);\n break;\n\n case MessageType.Awareness:\n this.applyAwarenessMessage(provider);\n break;\n\n case MessageType.Auth:\n this.applyAuthMessage(provider);\n break;\n\n case MessageType.QueryAwareness:\n this.applyQueryAwarenessMessage(provider);\n break;\n\n case MessageType.Stateless:\n provider.receiveStateless(readVarString(message.decoder));\n break;\n\n case MessageType.SyncStatus:\n this.applySyncStatusMessage(provider, readVarInt(message.decoder) === 1);\n break;\n\n case MessageType.CLOSE:\n // eslint-disable-next-line no-case-declarations\n const event: CloseEvent = {\n code: 1000,\n reason: readVarString(message.decoder),\n // @ts-ignore\n target: provider.configuration.websocketProvider.webSocket!,\n type: \"close\",\n };\n provider.onClose();\n provider.configuration.onClose({ event });\n provider.forwardClose({ event });\n break;\n\n default:\n throw new Error(`Can’t apply message of unknown type: ${type}`);\n }\n\n // Reply\n if (message.length() > emptyMessageLength + 1) {\n // length of documentName (considered in emptyMessageLength plus length of yjs sync type, set in applySyncMessage)\n // @ts-ignore\n provider.send(OutgoingMessage, { encoder: message.encoder });\n }\n }\n\n private applySyncMessage(provider: AbracadabraBaseProvider, emitSynced: boolean) {\n const { message } = this;\n\n message.writeVarUint(MessageType.Sync);\n\n // Apply update\n const syncMessageType = readSyncMessage(\n message.decoder,\n message.encoder,\n provider.document,\n provider,\n );\n\n // Synced once we receive Step2\n if (emitSynced && syncMessageType === messageYjsSyncStep2) {\n provider.synced = true;\n }\n }\n\n applySyncStatusMessage(provider: AbracadabraBaseProvider, applied: boolean) {\n if (applied) {\n provider.decrementUnsyncedChanges();\n }\n }\n\n private applyAwarenessMessage(provider: AbracadabraBaseProvider) {\n if (!provider.awareness) return;\n\n const { message } = this;\n\n awarenessProtocol.applyAwarenessUpdate(\n provider.awareness,\n message.readVarUint8Array(),\n provider,\n );\n }\n\n private applyAuthMessage(provider: AbracadabraBaseProvider) {\n const { message } = this;\n\n readAuthMessage(\n message.decoder,\n provider.sendToken.bind(provider),\n provider.permissionDeniedHandler.bind(provider),\n provider.authenticatedHandler.bind(provider),\n );\n }\n\n private applyQueryAwarenessMessage(provider: AbracadabraBaseProvider) {\n if (!provider.awareness) return;\n\n const { message } = this;\n\n message.writeVarUint(MessageType.Awareness);\n message.writeVarUint8Array(\n awarenessProtocol.encodeAwarenessUpdate(\n provider.awareness,\n Array.from(provider.awareness.getStates().keys()),\n ),\n );\n }\n}\n","import type { Encoder } from \"lib0/encoding\";\nimport { toUint8Array } from \"lib0/encoding\";\nimport type { ConstructableOutgoingMessage } from \"./types.ts\";\n\nexport class MessageSender {\n\tencoder: Encoder;\n\n\tmessage: any;\n\n\tconstructor(Message: ConstructableOutgoingMessage, args: any = {}) {\n\t\tthis.message = new Message();\n\t\tthis.encoder = this.message.get(args);\n\t}\n\n\tcreate() {\n\t\treturn toUint8Array(this.encoder);\n\t}\n\n\tsend(webSocket: any) {\n\t\twebSocket?.send(this.create());\n\t}\n}\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport { writeAuthentication } from \"../auth.ts\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class AuthenticationMessage extends OutgoingMessage {\n type = MessageType.Auth;\n\n description = \"Authentication\";\n\n get(args: Partial<OutgoingMessageArguments>) {\n if (typeof args.token === \"undefined\") {\n throw new Error(\"The authentication message requires `token` as an argument.\");\n }\n\n writeVarString(this.encoder, args.documentName!);\n writeVarUint(this.encoder, this.type);\n writeAuthentication(this.encoder, args.token);\n\n return this.encoder;\n }\n}\n","import * as encoding from \"lib0/encoding\";\nimport { encodeAwarenessUpdate } from \"y-protocols/awareness\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class AwarenessMessage extends OutgoingMessage {\n\ttype = MessageType.Awareness;\n\n\tdescription = \"Awareness states update\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tif (typeof args.awareness === \"undefined\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"The awareness message requires awareness as an argument\",\n\t\t\t);\n\t\t}\n\n\t\tif (typeof args.clients === \"undefined\") {\n\t\t\tthrow new Error(\"The awareness message requires clients as an argument\");\n\t\t}\n\n\t\tencoding.writeVarString(this.encoder, args.documentName!);\n\t\tencoding.writeVarUint(this.encoder, this.type);\n\n\t\tlet awarenessUpdate;\n\t\tif (args.states === undefined) {\n\t\t\tawarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients);\n\t\t} else {\n\t\t\tawarenessUpdate = encodeAwarenessUpdate(\n\t\t\t\targs.awareness,\n\t\t\t\targs.clients,\n\t\t\t\targs.states,\n\t\t\t);\n\t\t}\n\n\t\tencoding.writeVarUint8Array(this.encoder, awarenessUpdate);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class StatelessMessage extends OutgoingMessage {\n\ttype = MessageType.Stateless;\n\n\tdescription = \"A stateless message\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\twriteVarString(this.encoder, args.documentName!);\n\t\twriteVarUint(this.encoder, this.type);\n\t\twriteVarString(this.encoder, args.payload ?? \"\");\n\n\t\treturn this.encoder;\n\t}\n}\n","import * as encoding from \"lib0/encoding\";\nimport * as syncProtocol from \"y-protocols/sync\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class SyncStepOneMessage extends OutgoingMessage {\n\ttype = MessageType.Sync;\n\n\tdescription = \"First sync step\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tif (typeof args.document === \"undefined\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"The sync step one message requires document as an argument\",\n\t\t\t);\n\t\t}\n\n\t\tencoding.writeVarString(this.encoder, args.documentName!);\n\t\tencoding.writeVarUint(this.encoder, this.type);\n\t\tsyncProtocol.writeSyncStep1(this.encoder, args.document);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport { writeUpdate } from \"y-protocols/sync\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class UpdateMessage extends OutgoingMessage {\n\ttype = MessageType.Sync;\n\n\tdescription = \"A document update\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\twriteVarString(this.encoder, args.documentName!);\n\t\twriteVarUint(this.encoder, this.type);\n\n\t\twriteUpdate(this.encoder, args.update);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { awarenessStatesToArray } from \"./awarenessStatesToArray.ts\";\nimport type { Event, MessageEvent } from \"ws\";\nimport { Awareness, removeAwarenessStates } from \"y-protocols/awareness\";\nimport * as Y from \"yjs\";\nimport EventEmitter from \"./EventEmitter.ts\";\nimport type { CompleteAbracadabraWSConfiguration } from \"./AbracadabraWS.ts\";\nimport { AbracadabraWS } from \"./AbracadabraWS.ts\";\nimport { IncomingMessage } from \"./IncomingMessage.ts\";\nimport { MessageReceiver } from \"./MessageReceiver.ts\";\nimport { MessageSender } from \"./MessageSender.ts\";\nimport { AuthenticationMessage } from \"./OutgoingMessages/AuthenticationMessage.ts\";\nimport { AwarenessMessage } from \"./OutgoingMessages/AwarenessMessage.ts\";\nimport { StatelessMessage } from \"./OutgoingMessages/StatelessMessage.ts\";\nimport { SyncStepOneMessage } from \"./OutgoingMessages/SyncStepOneMessage.ts\";\nimport { UpdateMessage } from \"./OutgoingMessages/UpdateMessage.ts\";\nimport type {\n AuthorizedScope,\n ConstructableOutgoingMessage,\n onAuthenticatedParameters,\n onAuthenticationFailedParameters,\n onAwarenessChangeParameters,\n onAwarenessUpdateParameters,\n onCloseParameters,\n onDisconnectParameters,\n onMessageParameters,\n onOpenParameters,\n onOutgoingMessageParameters,\n onStatelessParameters,\n onStatusParameters,\n onSyncedParameters,\n onUnsyncedChangesParameters,\n} from \"./types.ts\";\n\nexport type AbracadabraBaseProviderConfiguration = Required<\n Pick<CompleteAbracadabraBaseProviderConfiguration, \"name\">\n> &\n Partial<CompleteAbracadabraBaseProviderConfiguration> &\n (\n | (Required<Pick<CompleteAbracadabraWSConfiguration, \"url\">> &\n Partial<Pick<CompleteAbracadabraWSConfiguration, \"preserveTrailingSlash\">>)\n | Required<Pick<CompleteAbracadabraBaseProviderConfiguration, \"websocketProvider\">>\n );\n\n/** @deprecated Use AbracadabraBaseProviderConfiguration */\nexport type HocuspocusProviderConfiguration = AbracadabraBaseProviderConfiguration;\n\nexport interface CompleteAbracadabraBaseProviderConfiguration {\n /**\n * The identifier/name of your document\n */\n name: string;\n /**\n * The actual Y.js document\n */\n document: Y.Doc;\n\n /**\n * An Awareness instance to keep the presence state of all clients.\n *\n * You can disable sharing awareness information by passing `null`.\n * Note that having no awareness information shared across all connections will break our ping checks\n * and thus trigger reconnects. You should always have at least one Provider with enabled awareness per\n * socket connection, or ensure that the Provider receives messages before running into `AbracadabraWS.messageReconnectTimeout`.\n */\n awareness: Awareness | null;\n\n /**\n * A token that's sent to the backend for authentication purposes.\n */\n token: string | (() => string) | (() => Promise<string>) | null;\n\n /**\n * Abracadabra websocket provider\n */\n websocketProvider: AbracadabraWS;\n\n /**\n * Force syncing the document in the defined interval.\n */\n forceSyncInterval: false | number;\n\n onAuthenticated: (data: onAuthenticatedParameters) => void;\n onAuthenticationFailed: (data: onAuthenticationFailedParameters) => void;\n onRateLimited: () => void;\n onOpen: (data: onOpenParameters) => void;\n onConnect: () => void;\n onStatus: (data: onStatusParameters) => void;\n onMessage: (data: onMessageParameters) => void;\n onOutgoingMessage: (data: onOutgoingMessageParameters) => void;\n onSynced: (data: onSyncedParameters) => void;\n onDisconnect: (data: onDisconnectParameters) => void;\n onClose: (data: onCloseParameters) => void;\n onDestroy: () => void;\n onAwarenessUpdate: (data: onAwarenessUpdateParameters) => void;\n onAwarenessChange: (data: onAwarenessChangeParameters) => void;\n onStateless: (data: onStatelessParameters) => void;\n onUnsyncedChanges: (data: onUnsyncedChangesParameters) => void;\n}\n\n/** @deprecated Use CompleteAbracadabraBaseProviderConfiguration */\nexport type CompleteHocuspocusProviderConfiguration = CompleteAbracadabraBaseProviderConfiguration;\n\nexport class AwarenessError extends Error {\n code = 1001;\n}\n\nexport class AbracadabraBaseProvider extends EventEmitter {\n public configuration: CompleteAbracadabraBaseProviderConfiguration = {\n name: \"\",\n // @ts-ignore\n document: undefined,\n // @ts-ignore\n awareness: undefined,\n token: null,\n forceSyncInterval: false,\n onAuthenticated: () => null,\n onAuthenticationFailed: () => null,\n onRateLimited: () => null,\n onOpen: () => null,\n onConnect: () => null,\n onMessage: () => null,\n onOutgoingMessage: () => null,\n onSynced: () => null,\n onStatus: () => null,\n onDisconnect: () => null,\n onClose: () => null,\n onDestroy: () => null,\n onAwarenessUpdate: () => null,\n onAwarenessChange: () => null,\n onStateless: () => null,\n onUnsyncedChanges: () => null,\n };\n\n isSynced = false;\n\n unsyncedChanges = 0;\n\n isAuthenticated = false;\n\n authorizedScope: AuthorizedScope | undefined = undefined;\n\n // @internal\n manageSocket = false;\n\n private _isAttached = false;\n\n intervals: any = {\n forceSync: null,\n };\n\n constructor(configuration: AbracadabraBaseProviderConfiguration) {\n super();\n this.setConfiguration(configuration);\n\n this.configuration.document = configuration.document ? configuration.document : new Y.Doc();\n this.configuration.awareness =\n configuration.awareness !== undefined\n ? configuration.awareness\n : new Awareness(this.document);\n\n this.on(\"open\", this.configuration.onOpen);\n this.on(\"message\", this.configuration.onMessage);\n this.on(\"outgoingMessage\", this.configuration.onOutgoingMessage);\n this.on(\"synced\", this.configuration.onSynced);\n this.on(\"destroy\", this.configuration.onDestroy);\n this.on(\"awarenessUpdate\", this.configuration.onAwarenessUpdate);\n this.on(\"awarenessChange\", this.configuration.onAwarenessChange);\n this.on(\"stateless\", this.configuration.onStateless);\n this.on(\"unsyncedChanges\", this.configuration.onUnsyncedChanges);\n\n this.on(\"authenticated\", this.configuration.onAuthenticated);\n this.on(\"authenticationFailed\", this.configuration.onAuthenticationFailed);\n this.on(\"rateLimited\", this.configuration.onRateLimited);\n\n this.awareness?.on(\"update\", () => {\n this.emit(\"awarenessUpdate\", {\n states: awarenessStatesToArray(this.awareness!.getStates()),\n });\n });\n\n this.awareness?.on(\"change\", () => {\n this.emit(\"awarenessChange\", {\n states: awarenessStatesToArray(this.awareness!.getStates()),\n });\n });\n\n this.document.on(\"update\", this.boundDocumentUpdateHandler);\n this.awareness?.on(\"update\", this.boundAwarenessUpdateHandler);\n\n this.registerEventListeners();\n\n if (\n this.configuration.forceSyncInterval &&\n typeof this.configuration.forceSyncInterval === \"number\"\n ) {\n this.intervals.forceSync = setInterval(\n this.forceSync.bind(this),\n this.configuration.forceSyncInterval,\n );\n }\n\n if (this.manageSocket) {\n this.attach();\n }\n }\n\n boundDocumentUpdateHandler = this.documentUpdateHandler.bind(this);\n\n boundAwarenessUpdateHandler = this.awarenessUpdateHandler.bind(this);\n\n boundPageHide = this.pageHide.bind(this);\n\n boundOnOpen = this.onOpen.bind(this);\n\n boundOnClose = this.onClose.bind(this);\n\n forwardConnect = () => this.emit(\"connect\");\n\n forwardStatus = (e: onStatusParameters) => this.emit(\"status\", e);\n\n forwardClose = (e: onCloseParameters) => this.emit(\"close\", e);\n\n forwardDisconnect = (e: onDisconnectParameters) => this.emit(\"disconnect\", e);\n\n forwardDestroy = () => this.emit(\"destroy\");\n\n forwardRateLimited = () => this.emit(\"rateLimited\");\n\n public setConfiguration(configuration: Partial<AbracadabraBaseProviderConfiguration> = {}): void {\n if (!configuration.websocketProvider) {\n this.manageSocket = true;\n this.configuration.websocketProvider = new AbracadabraWS(\n configuration as CompleteAbracadabraWSConfiguration,\n );\n }\n\n this.configuration = { ...this.configuration, ...configuration };\n }\n\n get document() {\n return this.configuration.document;\n }\n\n public get isAttached() {\n return this._isAttached;\n }\n\n get awareness() {\n return this.configuration.awareness;\n }\n\n get hasUnsyncedChanges(): boolean {\n return this.unsyncedChanges > 0;\n }\n\n private resetUnsyncedChanges() {\n this.unsyncedChanges = 1;\n this.emit(\"unsyncedChanges\", { number: this.unsyncedChanges });\n }\n\n incrementUnsyncedChanges() {\n this.unsyncedChanges += 1;\n this.emit(\"unsyncedChanges\", { number: this.unsyncedChanges });\n }\n\n decrementUnsyncedChanges() {\n if (this.unsyncedChanges > 0) {\n this.unsyncedChanges -= 1;\n }\n\n if (this.unsyncedChanges === 0) {\n this.synced = true;\n }\n\n this.emit(\"unsyncedChanges\", { number: this.unsyncedChanges });\n }\n\n forceSync() {\n this.resetUnsyncedChanges();\n\n this.send(SyncStepOneMessage, {\n document: this.document,\n documentName: this.configuration.name,\n });\n }\n\n pageHide() {\n if (this.awareness) {\n removeAwarenessStates(this.awareness, [this.document.clientID], \"page hide\");\n }\n }\n\n registerEventListeners() {\n if (typeof window === \"undefined\" || !(\"addEventListener\" in window)) {\n return;\n }\n\n window.addEventListener(\"pagehide\", this.boundPageHide);\n }\n\n sendStateless(payload: string) {\n this.send(StatelessMessage, {\n documentName: this.configuration.name,\n payload,\n });\n }\n\n async sendToken() {\n let token: string | null;\n try {\n token = await this.getToken();\n } catch (error) {\n this.permissionDeniedHandler(`Failed to get token during sendToken(): ${error}`);\n return;\n }\n\n this.send(AuthenticationMessage, {\n token: token ?? \"\",\n documentName: this.configuration.name,\n });\n }\n\n documentUpdateHandler(update: Uint8Array, origin: any) {\n if (origin === this) {\n return;\n }\n\n this.incrementUnsyncedChanges();\n this.send(UpdateMessage, { update, documentName: this.configuration.name });\n }\n\n awarenessUpdateHandler({ added, updated, removed }: any, origin: any) {\n const changedClients = added.concat(updated).concat(removed);\n\n this.send(AwarenessMessage, {\n awareness: this.awareness,\n clients: changedClients,\n documentName: this.configuration.name,\n });\n }\n\n /**\n * Indicates whether a first handshake with the server has been established\n *\n * Note: this does not mean all updates from the client have been persisted to the backend. For this,\n * use `hasUnsyncedChanges`.\n */\n get synced(): boolean {\n return this.isSynced;\n }\n\n set synced(state) {\n if (this.isSynced === state) {\n return;\n }\n\n this.isSynced = state;\n\n if (state) {\n this.emit(\"synced\", { state });\n }\n }\n\n receiveStateless(payload: string) {\n this.emit(\"stateless\", { payload });\n }\n\n // not needed, but provides backward compatibility with e.g. lexical/yjs\n async connect() {\n if (this.manageSocket) {\n return this.configuration.websocketProvider.connect();\n }\n\n console.warn(\n \"AbracadabraBaseProvider::connect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.\",\n );\n }\n\n disconnect() {\n if (this.manageSocket) {\n return this.configuration.websocketProvider.disconnect();\n }\n\n console.warn(\n \"AbracadabraBaseProvider::disconnect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.\",\n );\n }\n\n async onOpen(event: Event) {\n this.isAuthenticated = false;\n\n this.emit(\"open\", { event });\n await this.sendToken();\n this.startSync();\n }\n\n async getToken() {\n if (typeof this.configuration.token === \"function\") {\n const token = await this.configuration.token();\n return token;\n }\n\n return this.configuration.token;\n }\n\n startSync() {\n this.resetUnsyncedChanges();\n\n this.send(SyncStepOneMessage, {\n document: this.document,\n documentName: this.configuration.name,\n });\n\n if (this.awareness && this.awareness.getLocalState() !== null) {\n this.send(AwarenessMessage, {\n awareness: this.awareness,\n clients: [this.document.clientID],\n documentName: this.configuration.name,\n });\n }\n }\n\n send(message: ConstructableOutgoingMessage, args: any) {\n if (!this._isAttached) return;\n\n const messageSender = new MessageSender(message, args);\n\n this.emit(\"outgoingMessage\", { message: messageSender.message });\n messageSender.send(this.configuration.websocketProvider);\n }\n\n onMessage(event: MessageEvent) {\n const message = new IncomingMessage(event.data);\n\n const documentName = message.readVarString();\n\n message.writeVarString(documentName);\n\n this.emit(\"message\", { event, message: new IncomingMessage(event.data) });\n\n new MessageReceiver(message).apply(this, true);\n }\n\n onClose() {\n this.isAuthenticated = false;\n this.synced = false;\n\n // update awareness (all users except local left)\n if (this.awareness) {\n removeAwarenessStates(\n this.awareness,\n Array.from(this.awareness.getStates().keys()).filter(\n (client) => client !== this.document.clientID,\n ),\n this,\n );\n }\n }\n\n destroy() {\n this.emit(\"destroy\");\n\n if (this.intervals.forceSync) {\n clearInterval(this.intervals.forceSync);\n }\n\n if (this.awareness) {\n removeAwarenessStates(this.awareness, [this.document.clientID], \"provider destroy\");\n this.awareness.off(\"update\", this.boundAwarenessUpdateHandler);\n this.awareness.destroy();\n }\n\n this.document.off(\"update\", this.boundDocumentUpdateHandler);\n\n this.removeAllListeners();\n\n this.detach();\n\n if (this.manageSocket) {\n this.configuration.websocketProvider.destroy();\n }\n\n if (typeof window === \"undefined\" || !(\"removeEventListener\" in window)) {\n return;\n }\n\n window.removeEventListener(\"pagehide\", this.boundPageHide);\n }\n\n detach() {\n this.configuration.websocketProvider.off(\"connect\", this.configuration.onConnect);\n this.configuration.websocketProvider.off(\"connect\", this.forwardConnect);\n\n this.configuration.websocketProvider.off(\"status\", this.forwardStatus);\n this.configuration.websocketProvider.off(\"status\", this.configuration.onStatus);\n\n this.configuration.websocketProvider.off(\"open\", this.boundOnOpen);\n this.configuration.websocketProvider.off(\"close\", this.boundOnClose);\n this.configuration.websocketProvider.off(\"close\", this.configuration.onClose);\n this.configuration.websocketProvider.off(\"close\", this.forwardClose);\n this.configuration.websocketProvider.off(\"disconnect\", this.configuration.onDisconnect);\n this.configuration.websocketProvider.off(\"disconnect\", this.forwardDisconnect);\n this.configuration.websocketProvider.off(\"destroy\", this.configuration.onDestroy);\n this.configuration.websocketProvider.off(\"destroy\", this.forwardDestroy);\n\n this.configuration.websocketProvider.off(\"rateLimited\", this.forwardRateLimited);\n\n this.configuration.websocketProvider.detach(this);\n\n this._isAttached = false;\n }\n\n attach() {\n if (this._isAttached) return;\n\n this.configuration.websocketProvider.on(\"connect\", this.configuration.onConnect);\n this.configuration.websocketProvider.on(\"connect\", this.forwardConnect);\n\n this.configuration.websocketProvider.on(\"status\", this.configuration.onStatus);\n this.configuration.websocketProvider.on(\"status\", this.forwardStatus);\n\n this.configuration.websocketProvider.on(\"open\", this.boundOnOpen);\n\n this.configuration.websocketProvider.on(\"close\", this.boundOnClose);\n this.configuration.websocketProvider.on(\"close\", this.configuration.onClose);\n this.configuration.websocketProvider.on(\"close\", this.forwardClose);\n\n this.configuration.websocketProvider.on(\"disconnect\", this.configuration.onDisconnect);\n this.configuration.websocketProvider.on(\"disconnect\", this.forwardDisconnect);\n\n this.configuration.websocketProvider.on(\"destroy\", this.configuration.onDestroy);\n this.configuration.websocketProvider.on(\"destroy\", this.forwardDestroy);\n\n this.configuration.websocketProvider.on(\"rateLimited\", this.forwardRateLimited);\n\n this.configuration.websocketProvider.attach(this);\n\n this._isAttached = true;\n }\n\n permissionDeniedHandler(reason: string) {\n this.emit(\"authenticationFailed\", { reason });\n this.isAuthenticated = false;\n }\n\n authenticatedHandler(scope: string) {\n this.isAuthenticated = true;\n this.authorizedScope = scope as AuthorizedScope;\n\n this.emit(\"authenticated\", { scope });\n }\n\n setAwarenessField(key: string, value: any) {\n if (!this.awareness) {\n throw new AwarenessError(\n `Cannot set awareness field \"${key}\" to ${JSON.stringify(value)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`,\n );\n }\n this.awareness.setLocalStateField(key, value);\n }\n}\n\n/** @deprecated Use AbracadabraBaseProvider */\nexport const HocuspocusProvider = AbracadabraBaseProvider;\n/** @deprecated Use AbracadabraBaseProvider */\nexport type HocuspocusProvider = AbracadabraBaseProvider;\n","/**\n * IndexedDB-backed offline store for a single Abracadabra document.\n *\n * Responsibilities:\n * - Persist CRDT updates locally so they survive page refreshes / network loss.\n * - Store the last-known state vector for fast reconnect diffs.\n * - Store a permission snapshot so the UI can gate writes without a network round-trip.\n * - Queue subdoc registration events created while offline.\n * - Store a full document snapshot so the app can load content without a server connection.\n *\n * Falls back to a silent no-op when IndexedDB is unavailable (e.g. SSR / Node.js).\n *\n * Database key is scoped by server origin to prevent cross-server data contamination\n * when the same docId is used on multiple servers.\n */\n\nexport interface PendingSubdoc {\n\tchildId: string;\n\tparentId: string;\n\tcreatedAt: number;\n}\n\nconst DB_VERSION = 2;\n\nfunction idbAvailable(): boolean {\n\treturn typeof globalThis !== \"undefined\" && \"indexedDB\" in globalThis;\n}\n\nfunction openDb(storeKey: string): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = globalThis.indexedDB.open(`abracadabra:${storeKey}`, DB_VERSION);\n\n\t\treq.onupgradeneeded = (event) => {\n\t\t\tconst db = (event.target as IDBOpenDBRequest).result;\n\n\t\t\tif (!db.objectStoreNames.contains(\"updates\")) {\n\t\t\t\tdb.createObjectStore(\"updates\", { autoIncrement: true });\n\t\t\t}\n\t\t\tif (!db.objectStoreNames.contains(\"meta\")) {\n\t\t\t\tdb.createObjectStore(\"meta\");\n\t\t\t}\n\t\t\tif (!db.objectStoreNames.contains(\"subdoc_queue\")) {\n\t\t\t\tdb.createObjectStore(\"subdoc_queue\", { keyPath: \"childId\" });\n\t\t\t}\n\t\t\t// v2: full document snapshot store\n\t\t\tif (!db.objectStoreNames.contains(\"doc_state\")) {\n\t\t\t\tdb.createObjectStore(\"doc_state\");\n\t\t\t}\n\t\t};\n\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nfunction txPromise<T>(\n\tstore: IDBObjectStore,\n\trequest: IDBRequest<T>,\n): Promise<T> {\n\treturn new Promise((resolve, reject) => {\n\t\trequest.onsuccess = () => resolve(request.result);\n\t\trequest.onerror = () => reject(request.error);\n\t});\n}\n\nexport class OfflineStore {\n\tprivate storeKey: string;\n\tprivate db: IDBDatabase | null = null;\n\n\t/**\n\t * @param docId The document UUID.\n\t * @param serverOrigin Hostname of the server (e.g. \"abra.cou.sh\").\n\t * When provided the IndexedDB database is namespaced\n\t * per-server, preventing cross-server data contamination.\n\t */\n\tconstructor(docId: string, serverOrigin?: string) {\n\t\tthis.storeKey = serverOrigin ? `${serverOrigin}/${docId}` : docId;\n\t}\n\n\tprivate dbPromise: Promise<IDBDatabase | null> | null = null;\n\n\tprivate getDb(): Promise<IDBDatabase | null> {\n\t\tif (!idbAvailable()) return Promise.resolve(null);\n\t\tif (!this.dbPromise) {\n\t\t\t// Cache the promise so concurrent callers share a single open operation.\n\t\t\tthis.dbPromise = openDb(this.storeKey).catch(() => null).then(db => {\n\t\t\t\tthis.db = db;\n\t\t\t\treturn db;\n\t\t\t});\n\t\t}\n\t\treturn this.dbPromise;\n\t}\n\n\t// ── Pending (unsynced) updates ────────────────────────────────────────────\n\n\tasync persistUpdate(update: Uint8Array): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"updates\", \"readwrite\");\n\t\tconst store = tx.objectStore(\"updates\");\n\t\tawait txPromise(store, store.add(update));\n\t}\n\n\tasync getPendingUpdates(): Promise<Uint8Array[]> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"updates\", \"readonly\");\n\t\t\tconst store = tx.objectStore(\"updates\");\n\t\t\tconst req = store.getAll();\n\t\t\treq.onsuccess = () => resolve(req.result as Uint8Array[]);\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\tasync clearPendingUpdates(): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"updates\", \"readwrite\");\n\t\tawait txPromise(tx.objectStore(\"updates\"), tx.objectStore(\"updates\").clear());\n\t}\n\n\t// ── Full document snapshot ────────────────────────────────────────────────\n\n\t/**\n\t * Persist a full Y.js state snapshot (Y.encodeStateAsUpdate output).\n\t * Replaces any previously stored snapshot.\n\t */\n\tasync saveDocSnapshot(snapshot: Uint8Array): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"doc_state\", \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(\"doc_state\"),\n\t\t\ttx.objectStore(\"doc_state\").put(snapshot, \"snapshot\"),\n\t\t);\n\t}\n\n\t/**\n\t * Retrieve the stored full document snapshot, or null if none exists.\n\t */\n\tasync getDocSnapshot(): Promise<Uint8Array | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(\"doc_state\", \"readonly\");\n\t\tconst result = await txPromise<Uint8Array | undefined>(\n\t\t\ttx.objectStore(\"doc_state\"),\n\t\t\ttx.objectStore(\"doc_state\").get(\"snapshot\"),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\t// ── State vector ─────────────────────────────────────────────────────────\n\n\tasync getStateVector(): Promise<Uint8Array | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(\"meta\", \"readonly\");\n\t\tconst result = await txPromise<Uint8Array | undefined>(\n\t\t\ttx.objectStore(\"meta\"),\n\t\t\ttx.objectStore(\"meta\").get(\"sv\"),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\tasync saveStateVector(sv: Uint8Array): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"meta\", \"readwrite\");\n\t\tawait txPromise(tx.objectStore(\"meta\"), tx.objectStore(\"meta\").put(sv, \"sv\"));\n\t}\n\n\t// ── Permission snapshot ──────────────────────────────────────────────────\n\n\tasync getPermissionSnapshot(): Promise<string | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(\"meta\", \"readonly\");\n\t\tconst result = await txPromise<string | undefined>(\n\t\t\ttx.objectStore(\"meta\"),\n\t\t\ttx.objectStore(\"meta\").get(\"role\"),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\tasync savePermissionSnapshot(role: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"meta\", \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(\"meta\"),\n\t\t\ttx.objectStore(\"meta\").put(role, \"role\"),\n\t\t);\n\t}\n\n\t// ── Subdoc registration queue ─────────────────────────────────────────────\n\n\tasync queueSubdoc(entry: PendingSubdoc): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"subdoc_queue\", \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(\"subdoc_queue\"),\n\t\t\ttx.objectStore(\"subdoc_queue\").put(entry),\n\t\t);\n\t}\n\n\tasync getPendingSubdocs(): Promise<PendingSubdoc[]> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"subdoc_queue\", \"readonly\");\n\t\t\tconst req = tx.objectStore(\"subdoc_queue\").getAll();\n\t\t\treq.onsuccess = () => resolve(req.result as PendingSubdoc[]);\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\tasync removeSubdocFromQueue(childId: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"subdoc_queue\", \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(\"subdoc_queue\"),\n\t\t\ttx.objectStore(\"subdoc_queue\").delete(childId),\n\t\t);\n\t}\n\n\t// ── Generic meta accessors ────────────────────────────────────────────────\n\n\tasync getMeta(key: string): Promise<string | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(\"meta\", \"readonly\");\n\t\tconst result = await txPromise<string | undefined>(\n\t\t\ttx.objectStore(\"meta\"),\n\t\t\ttx.objectStore(\"meta\").get(key),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\tasync setMeta(key: string, value: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"meta\", \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(\"meta\"),\n\t\t\ttx.objectStore(\"meta\").put(value, key),\n\t\t);\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\tdestroy() {\n\t\tthis.db?.close();\n\t\tthis.db = null;\n\t}\n}\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\n/**\n * Registers a new subdocument with the Abracadabra server.\n *\n * Wire format (consumed by handle_subdoc in sync.rs):\n * [ParentDocName: VarString] [MSG_SUBDOC(4): VarUint] [childDocumentName: VarString]\n *\n * The server responds with a MSG_STATELESS JSON frame:\n * { type: \"subdoc_registered\", child_id, parent_id }\n * which AbracadabraProvider intercepts in receiveStateless().\n */\nexport class SubdocMessage extends OutgoingMessage {\n\ttype = MessageType.Subdoc;\n\n\tdescription = \"SubdocRegistration\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tif (!args.documentName) {\n\t\t\tthrow new Error(\"SubdocMessage requires `documentName` (parent id).\");\n\t\t}\n\t\tif (!args.childDocumentName) {\n\t\t\tthrow new Error(\"SubdocMessage requires `childDocumentName`.\");\n\t\t}\n\n\t\twriteVarString(this.encoder, args.documentName);\n\t\twriteVarUint(this.encoder, this.type);\n\t\twriteVarString(this.encoder, args.childDocumentName);\n\n\t\treturn this.encoder;\n\t}\n}\n","import * as Y from \"yjs\";\nimport { AbracadabraBaseProvider } from \"./AbracadabraBaseProvider.ts\";\nimport type { AbracadabraBaseProviderConfiguration } from \"./AbracadabraBaseProvider.ts\";\nimport type { AbracadabraWS } from \"./AbracadabraWS.ts\";\nimport { OfflineStore } from \"./OfflineStore.ts\";\nimport { SubdocMessage } from \"./OutgoingMessages/SubdocMessage.ts\";\nimport { UpdateMessage } from \"./OutgoingMessages/UpdateMessage.ts\";\nimport type {\n\tCryptoIdentity,\n\tEffectiveRole,\n\tonSubdocRegisteredParameters,\n\tonSubdocLoadedParameters,\n} from \"./types.ts\";\nimport { AuthenticationMessage } from \"./OutgoingMessages/AuthenticationMessage.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport type { DocKeyManager } from \"./DocKeyManager.ts\";\nimport type { CryptoIdentityKeystore } from \"./CryptoIdentityKeystore.ts\";\n\nexport interface AbracadabraProviderConfiguration\n\textends Omit<AbracadabraBaseProviderConfiguration, \"url\" | \"websocketProvider\"> {\n\t/**\n\t * Subdocument loading strategy.\n\t * - \"lazy\" (default) – child providers are created only when explicitly requested.\n\t * - \"eager\" – all children returned by the server on connect are loaded automatically.\n\t */\n\tsubdocLoading?: \"lazy\" | \"eager\";\n\n\t/** Called when the server confirms a subdoc registration. */\n\tonSubdocRegistered?: (data: onSubdocRegisteredParameters) => void;\n\n\t/** Called when a child AbracadabraProvider has been created and attached. */\n\tonSubdocLoaded?: (data: onSubdocLoadedParameters) => void;\n\n\t/**\n\t * Disable the IndexedDB offline store. Useful for server-side rendering\n\t * or testing environments that lack IndexedDB.\n\t */\n\tdisableOfflineStore?: boolean;\n\n\t/**\n\t * Identity for passwordless crypto auth (Model B multi-key).\n\t * Mutually exclusive with token.\n\t */\n\tcryptoIdentity?: CryptoIdentity | (() => Promise<CryptoIdentity>);\n\n\t/**\n\t * Signs a base64url challenge and returns a base64url signature.\n\t * Required when cryptoIdentity is set.\n\t */\n\tsignChallenge?: (challenge: string) => Promise<string>;\n\n\t/**\n\t * AbracadabraClient instance for REST API access.\n\t * When provided, the provider automatically derives the WebSocket URL\n\t * and token from the client (unless explicitly overridden).\n\t */\n\tclient?: AbracadabraClient;\n\n\t/** WebSocket URL. Derived from client.wsUrl if client is provided. */\n\turl?: string;\n\n\t/** DocKeyManager for E2E/CSE encryption key management. */\n\tdocKeyManager?: DocKeyManager;\n\t/** Keystore for X25519 key derivation. */\n\tkeystore?: CryptoIdentityKeystore;\n\n\t/** Shared WebSocket connection (use when multiplexing multiple root documents). */\n\twebsocketProvider?: AbracadabraWS;\n}\n\n/** Validate that a string is a UUID acceptable by the server's DocId parser. */\nfunction isValidDocId(id: string): boolean {\n\treturn /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id);\n}\n\n/**\n * AbracadabraProvider extends AbracadabraBaseProvider with:\n *\n * 1. Subdocument lifecycle – intercepts Y.Doc subdoc events and syncs them\n * with the server via MSG_SUBDOC (4) frames. Child documents get their\n * own AbracadabraProvider instances sharing the same WebSocket connection.\n *\n * 2. Offline-first – persists CRDT updates to IndexedDB so they survive\n * page reloads and network outages. On startup, the last saved document\n * snapshot is applied immediately so the UI is usable without a server\n * connection. On reconnect, pending updates are flushed and a fresh\n * snapshot is saved.\n *\n * 3. Server-scoped storage – the IndexedDB database is keyed by server\n * hostname + docId, preventing cross-server data contamination when the\n * same docId is used on multiple servers.\n *\n * 4. Permission snapshotting – stores the resolved role locally so the UI\n * can gate write operations without a network round-trip. Role is\n * refreshed from the server on every reconnect.\n */\nexport class AbracadabraProvider extends AbracadabraBaseProvider {\n\tpublic effectiveRole: EffectiveRole = null;\n\n\tprivate _client: AbracadabraClient | null;\n\tprivate offlineStore: OfflineStore | null;\n\tprivate childProviders = new Map<string, AbracadabraProvider>();\n\tprivate pendingLoads = new Map<string, Promise<AbracadabraProvider>>();\n\tprivate subdocLoading: \"lazy\" | \"eager\";\n\n\tprivate abracadabraConfig: AbracadabraProviderConfiguration;\n\n\tprivate readonly boundHandleYSubdocsChange = this.handleYSubdocsChange.bind(this);\n\n\t/**\n\t * Resolves once the document has been pre-populated from the local\n\t * IndexedDB snapshot (if one exists). Await this before rendering UI\n\t * that depends on the document content — it resolves immediately when\n\t * the offline store is disabled or when no snapshot has been saved yet.\n\t */\n\tpublic readonly ready: Promise<void>;\n\n\tconstructor(configuration: AbracadabraProviderConfiguration) {\n\t\t// Derive URL and token from client when not explicitly set.\n\t\tconst resolved = { ...configuration } as AbracadabraBaseProviderConfiguration;\n\t\tconst client = configuration.client ?? null;\n\n\t\tif (client) {\n\t\t\tif (!resolved.url && !resolved.websocketProvider) {\n\t\t\t\t(resolved as any).url = client.wsUrl;\n\t\t\t}\n\t\t\tif (resolved.token === undefined && !configuration.cryptoIdentity) {\n\t\t\t\tresolved.token = () => client.token ?? \"\";\n\t\t\t}\n\t\t}\n\n\t\tsuper(resolved);\n\t\tthis._client = client;\n\t\tthis.abracadabraConfig = configuration;\n\t\tthis.subdocLoading = configuration.subdocLoading ?? \"lazy\";\n\n\t\tconst serverOrigin = AbracadabraProvider.deriveServerOrigin(configuration, client);\n\t\tthis.offlineStore = configuration.disableOfflineStore\n\t\t\t? null\n\t\t\t: new OfflineStore(configuration.name, serverOrigin);\n\n\t\tthis.on(\n\t\t\t\"subdocRegistered\",\n\t\t\tconfiguration.onSubdocRegistered ?? (() => null),\n\t\t);\n\t\tthis.on(\"subdocLoaded\", configuration.onSubdocLoaded ?? (() => null));\n\n\t\t// Intercept Y.Doc subdoc lifecycle events.\n\t\tthis.document.on(\"subdocs\", this.boundHandleYSubdocsChange);\n\n\t\t// Flush offline updates once we're back online and synced.\n\t\tthis.on(\"synced\", () => this.flushPendingUpdates());\n\n\t\t// Restore permission snapshot while offline.\n\t\tthis.restorePermissionSnapshot();\n\n\t\t// Pre-populate the Y.Doc from the local snapshot so the UI works offline.\n\t\tthis.ready = this._initFromOfflineStore();\n\t}\n\n\t// ── Server origin derivation ──────────────────────────────────────────────\n\n\t/**\n\t * Extract the server hostname from the provider configuration.\n\t * Used to namespace the IndexedDB key so docs from different servers\n\t * never share the same database.\n\t */\n\tprotected static deriveServerOrigin(\n\t\tconfig: AbracadabraProviderConfiguration,\n\t\tclient: AbracadabraClient | null,\n\t): string | undefined {\n\t\ttry {\n\t\t\tconst url =\n\t\t\t\tconfig.url ??\n\t\t\t\t(config.websocketProvider as AbracadabraWS | undefined)?.url ??\n\t\t\t\tclient?.wsUrl;\n\t\t\tif (url) return new URL(url).hostname;\n\t\t} catch {\n\t\t\t// Malformed URL — fall back to no scoping\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// ── Offline-first initialisation ──────────────────────────────────────────\n\n\t/**\n\t * Load the stored document snapshot (and any pending local edits) from\n\t * IndexedDB and apply them to the Y.Doc so the UI can render without a\n\t * server connection.\n\t *\n\t * Uses `this.offlineStore` as the Y.js update origin so that\n\t * `documentUpdateHandler` ignores these replayed updates and does not\n\t * attempt to re-persist or re-send them.\n\t */\n\tprivate async _initFromOfflineStore(): Promise<void> {\n\t\tif (!this.offlineStore) return;\n\n\t\t// Fetch snapshot and pending updates in parallel — each call opens the\n\t\t// IDB database, so running them concurrently roughly halves the latency.\n\t\tconst [snapshot, pending] = await Promise.all([\n\t\t\tthis.offlineStore.getDocSnapshot().catch(() => null),\n\t\t\tthis.offlineStore.getPendingUpdates().catch(() => []),\n\t\t]);\n\n\t\tif (snapshot) {\n\t\t\tY.applyUpdate(this.document, snapshot, this.offlineStore);\n\t\t}\n\t\tfor (const update of pending) {\n\t\t\tY.applyUpdate(this.document, update, this.offlineStore);\n\t\t}\n\t}\n\n\t// ── Auth / permission snapshot ────────────────────────────────────────────\n\n\toverride authenticatedHandler(scope: string) {\n\t\tsuper.authenticatedHandler(scope);\n\n\t\tconst roleMap: Record<string, import(\"./types.ts\").EffectiveRole> = {\n\t\t\tservice: \"service\",\n\t\t\tadmin: \"admin\",\n\t\t\towner: \"owner\",\n\t\t\teditor: \"editor\",\n\t\t\tviewer: \"viewer\",\n\t\t\t\"read-write\": \"editor\",\n\t\t\treadonly: \"viewer\",\n\t\t};\n\t\tthis.effectiveRole = roleMap[scope] ?? \"viewer\";\n\n\t\tthis.offlineStore?.savePermissionSnapshot(this.effectiveRole);\n\t}\n\n\t/**\n\t * Override sendToken to send a pubkey-only identity declaration instead of a\n\t * JWT when cryptoIdentity is configured.\n\t *\n\t * The public key is the sole identifier in the crypto auth handshake.\n\t * Username is decoupled from auth; it lives on the server as an immutable\n\t * internal field and is never sent in the challenge-response frames.\n\t */\n\toverride async sendToken() {\n\t\tconst { cryptoIdentity } = this.abracadabraConfig;\n\t\tif (cryptoIdentity) {\n\t\t\tconst id =\n\t\t\t\ttypeof cryptoIdentity === \"function\"\n\t\t\t\t\t? await cryptoIdentity()\n\t\t\t\t\t: cryptoIdentity;\n\t\t\tconst json = JSON.stringify({\n\t\t\t\ttype: \"identity\",\n\t\t\t\tpublicKey: id.publicKey,\n\t\t\t});\n\t\t\tthis.send(AuthenticationMessage, {\n\t\t\t\ttoken: json,\n\t\t\t\tdocumentName: this.configuration.name,\n\t\t\t});\n\t\t} else {\n\t\t\tawait super.sendToken();\n\t\t}\n\t}\n\n\t/** Handle an auth_challenge message from the server. */\n\tprivate async handleAuthChallenge(\n\t\tchallenge: string,\n\t\texpiresAt: number,\n\t): Promise<void> {\n\t\tconst { signChallenge, cryptoIdentity } = this.abracadabraConfig;\n\t\tif (!signChallenge || !cryptoIdentity) {\n\t\t\tthis.permissionDeniedHandler(\"No signChallenge callback configured\");\n\t\t\treturn;\n\t\t}\n\t\tif (Date.now() > expiresAt * 1000) {\n\t\t\tthis.permissionDeniedHandler(\"Challenge expired\");\n\t\t\treturn;\n\t\t}\n\t\tconst id =\n\t\t\ttypeof cryptoIdentity === \"function\"\n\t\t\t\t? await cryptoIdentity()\n\t\t\t\t: cryptoIdentity;\n\t\tconst signature = await signChallenge(challenge);\n\t\t// Proof frame sends only publicKey — username is fully decoupled from auth.\n\t\tconst proof = JSON.stringify({\n\t\t\ttype: \"proof\",\n\t\t\tpublicKey: id.publicKey,\n\t\t\tsignature,\n\t\t\tchallenge,\n\t\t});\n\t\tthis.send(AuthenticationMessage, {\n\t\t\ttoken: proof,\n\t\t\tdocumentName: this.configuration.name,\n\t\t});\n\t}\n\n\tprivate async restorePermissionSnapshot() {\n\t\tif (!this.offlineStore) return;\n\t\tconst role = await this.offlineStore.getPermissionSnapshot();\n\t\tif (role && !this.effectiveRole) {\n\t\t\tthis.effectiveRole = role as EffectiveRole;\n\t\t}\n\t}\n\n\tget canWrite(): boolean {\n\t\treturn this.effectiveRole != null && this.effectiveRole !== \"viewer\";\n\t}\n\n\t/** The AbracadabraClient instance for REST API access, if configured. */\n\tget client(): AbracadabraClient | null {\n\t\treturn this._client;\n\t}\n\n\t/** The OfflineStore instance, or null if offline storage is disabled. */\n\tget store(): OfflineStore | null {\n\t\treturn this.offlineStore;\n\t}\n\n\t// ── Stateless message interception ────────────────────────────────────────\n\n\t/**\n\t * Called when a MSG_STATELESS frame arrives from the server.\n\t * Abracadabra uses stateless frames to deliver subdoc confirmations\n\t * ({ type: \"subdoc_registered\", child_id, parent_id }).\n\t */\n\toverride receiveStateless(payload: string) {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(payload);\n\t\t} catch {\n\t\t\tsuper.receiveStateless(payload);\n\t\t\treturn;\n\t\t}\n\n\t\tconst msg = parsed as {\n\t\t\ttype?: string;\n\t\t\tchild_id?: string;\n\t\t\tparent_id?: string;\n\t\t\tchallenge?: string;\n\t\t\texpiresAt?: number;\n\t\t};\n\n\t\t// Intercept auth_challenge before subdoc handling.\n\t\tif (msg.type === \"auth_challenge\" && msg.challenge && msg.expiresAt) {\n\t\t\tthis.handleAuthChallenge(msg.challenge, msg.expiresAt).catch(() => null);\n\t\t\treturn;\n\t\t}\n\n\t\tif (msg.type === \"subdoc_registered\" && msg.child_id && msg.parent_id) {\n\t\t\tconst event: onSubdocRegisteredParameters = {\n\t\t\t\tchildId: msg.child_id,\n\t\t\t\tparentId: msg.parent_id,\n\t\t\t};\n\t\t\tthis.emit(\"subdocRegistered\", event);\n\n\t\t\t// Remove from the offline queue now the server confirmed.\n\t\t\tthis.offlineStore?.removeSubdocFromQueue(msg.child_id);\n\n\t\t\t// Eager mode: auto-load the confirmed child.\n\t\t\tif (this.subdocLoading === \"eager\") {\n\t\t\t\tthis.loadChild(msg.child_id);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Unknown stateless payload – pass through to base class.\n\t\tsuper.receiveStateless(payload);\n\t}\n\n\t// ── Subdocument support ───────────────────────────────────────────────────\n\n\t/**\n\t * Y.Doc emits 'subdocs' whenever subdocuments are added, removed, or loaded.\n\t * We intercept additions to register them with the Abracadabra server.\n\t */\n\tprivate handleYSubdocsChange({\n\t\tadded,\n\t\tremoved,\n\t}: {\n\t\tadded: Set<Y.Doc>;\n\t\tremoved: Set<Y.Doc>;\n\t\tloaded: Set<Y.Doc>;\n\t}) {\n\t\tfor (const subdoc of added) {\n\t\t\tif (!isValidDocId(subdoc.guid)) continue;\n\t\t\tthis.registerSubdoc(subdoc);\n\t\t}\n\t\tfor (const subdoc of removed) {\n\t\t\tthis.unloadChild(subdoc.guid);\n\t\t}\n\t}\n\n\t/**\n\t * Send a subdoc registration frame to the server.\n\t * If offline the event is queued in IndexedDB and replayed on reconnect.\n\t */\n\tprivate registerSubdoc(subdoc: Y.Doc) {\n\t\tconst childId = subdoc.guid;\n\n\t\tif (this.isConnected) {\n\t\t\tthis.send(SubdocMessage, {\n\t\t\t\tdocumentName: this.configuration.name,\n\t\t\t\tchildDocumentName: childId,\n\t\t\t} as any);\n\t\t} else {\n\t\t\t// Queue for later replay when we reconnect.\n\t\t\tthis.offlineStore?.queueSubdoc({\n\t\t\t\tchildId,\n\t\t\t\tparentId: this.configuration.name,\n\t\t\t\tcreatedAt: Date.now(),\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Create (or return cached) a child AbracadabraProvider for a given\n\t * child document id. Each child opens its own WebSocket connection because\n\t * the server is document-scoped (one WebSocket ↔ one document).\n\t */\n\tloadChild(childId: string): Promise<AbracadabraProvider> {\n\t\tif (!isValidDocId(childId)) {\n\t\t\treturn Promise.reject(\n\t\t\t\tnew Error(\n\t\t\t\t\t`loadChild: \"${childId}\" is not a valid document ID (must be a UUID). ` +\n\t\t\t\t\t`If this node was created with an older version of the app, delete it and recreate it.`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\tif (this.childProviders.has(childId)) {\n\t\t\treturn Promise.resolve(this.childProviders.get(childId)!);\n\t\t}\n\n\t\t// Deduplicate concurrent calls: return the same Promise so both callers\n\t\t// get the exact same AbracadabraProvider instance.\n\t\tif (this.pendingLoads.has(childId)) {\n\t\t\treturn this.pendingLoads.get(childId)!;\n\t\t}\n\n\t\tconst load = this._doLoadChild(childId);\n\t\tthis.pendingLoads.set(childId, load);\n\t\tload.finally(() => this.pendingLoads.delete(childId));\n\t\treturn load;\n\t}\n\n\tprivate async _doLoadChild(childId: string): Promise<AbracadabraProvider> {\n\t\tconst childDoc = new Y.Doc({ guid: childId });\n\n\t\t// Fire-and-forget: tell the server this child belongs to the parent.\n\t\t// The child provider's own WebSocket handshake (TCP + TLS + auth) is\n\t\t// slow enough that the server will have processed the registration\n\t\t// before the child's first SyncStep1 arrives. In the rare race the\n\t\t// child's built-in reconnect logic retries automatically.\n\t\tthis.registerSubdoc(childDoc);\n\n\t\t// Each child gets its own WebSocket connection. Omitting\n\t\t// websocketProvider lets AbracadabraBaseProvider create one automatically\n\t\t// (manageSocket = true), so we do NOT call attach() manually.\n\t\tconst childProvider = new AbracadabraProvider({\n\t\t\tname: childId,\n\t\t\tdocument: childDoc,\n\t\t\turl: this.abracadabraConfig.url ?? this.configuration.websocketProvider?.url,\n\t\t\ttoken: this.configuration.token,\n\t\t\tsubdocLoading: this.subdocLoading,\n\t\t\tdisableOfflineStore: this.abracadabraConfig.disableOfflineStore,\n\t\t\tclient: this._client ?? undefined,\n\t\t\tcryptoIdentity: this.abracadabraConfig.cryptoIdentity,\n\t\t\tsignChallenge: this.abracadabraConfig.signChallenge,\n\t\t\tdocKeyManager: this.abracadabraConfig.docKeyManager,\n\t\t\tkeystore: this.abracadabraConfig.keystore,\n\t\t});\n\n\t\tthis.childProviders.set(childId, childProvider);\n\n\t\tthis.emit(\"subdocLoaded\", { childId, provider: childProvider });\n\n\t\treturn childProvider;\n\t}\n\n\tprivate unloadChild(childId: string) {\n\t\tconst provider = this.childProviders.get(childId);\n\t\tif (provider) {\n\t\t\tprovider.destroy();\n\t\t\tthis.childProviders.delete(childId);\n\t\t}\n\t}\n\n\t/** Return all currently-loaded child providers. */\n\tget children(): Map<string, AbracadabraProvider> {\n\t\treturn this.childProviders;\n\t}\n\n\t// ── Offline-first update persistence ─────────────────────────────────────\n\n\t/**\n\t * Override to persist every local update to IndexedDB before sending it\n\t * over the wire, ensuring no work is lost during connection outages.\n\t *\n\t * Updates applied by the server (origin === this) and updates replayed\n\t * from the offline store (origin === this.offlineStore) are both skipped\n\t * to avoid loops.\n\t */\n\toverride documentUpdateHandler(update: Uint8Array, origin: unknown) {\n\t\tif (origin === this) return;\n\t\t// Only skip when the store exists AND origin matches it.\n\t\t// Without the null-guard, a null offlineStore would match any update\n\t\t// with origin=null (the default for user transactions), silently\n\t\t// dropping all local writes when disableOfflineStore is true.\n\t\tif (this.offlineStore !== null && origin === this.offlineStore) return;\n\n\t\t// Persist locally first (fire-and-forget; errors are non-fatal).\n\t\tthis.offlineStore?.persistUpdate(update).catch(() => null);\n\n\t\tsuper.documentUpdateHandler(update, origin);\n\t}\n\n\t/**\n\t * After reconnect + sync:\n\t * 1. Flush any updates that were generated while offline.\n\t * 2. Flush any queued subdoc registrations.\n\t * 3. Save a fresh full document snapshot for the next offline session.\n\t *\n\t * Uses a local `store` reference captured at the start so that a concurrent\n\t * `destroy()` call setting `offlineStore = null` does not cause null-ref\n\t * errors across async await boundaries.\n\t */\n\tprivate async flushPendingUpdates() {\n\t\tconst store = this.offlineStore;\n\t\tif (!store) return;\n\n\t\tconst updates = await store.getPendingUpdates();\n\t\tif (updates.length > 0) {\n\t\t\tfor (const update of updates) {\n\t\t\t\tthis.send(UpdateMessage, {\n\t\t\t\t\tupdate,\n\t\t\t\t\tdocumentName: this.configuration.name,\n\t\t\t\t});\n\t\t\t}\n\t\t\tawait store.clearPendingUpdates();\n\t\t}\n\n\t\tconst pendingSubdocs = await store.getPendingSubdocs();\n\t\tfor (const { childId } of pendingSubdocs) {\n\t\t\tthis.send(SubdocMessage, {\n\t\t\t\tdocumentName: this.configuration.name,\n\t\t\t\tchildDocumentName: childId,\n\t\t\t} as any);\n\t\t}\n\n\t\t// Snapshot the current merged state so the next offline load sees it.\n\t\tconst snapshot = Y.encodeStateAsUpdate(this.document);\n\t\tawait store.saveDocSnapshot(snapshot).catch(() => null);\n\t}\n\n\tget isConnected(): boolean {\n\t\treturn (\n\t\t\t(this.configuration.websocketProvider as AbracadabraWS)\n\t\t\t\t.status === \"connected\"\n\t\t);\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\toverride destroy() {\n\t\tthis.document.off(\"subdocs\", this.boundHandleYSubdocsChange);\n\n\t\tfor (const provider of this.childProviders.values()) {\n\t\t\tprovider.destroy();\n\t\t}\n\t\tthis.childProviders.clear();\n\n\t\tthis.offlineStore?.destroy();\n\t\tthis.offlineStore = null;\n\n\t\tsuper.destroy();\n\t}\n}\n","import type {\n\tUserProfile,\n\tDocumentMeta,\n\tUploadMeta,\n\tUploadInfo,\n\tPublicKeyInfo,\n\tPermissionEntry,\n\tHealthStatus,\n\tServerInfo,\n\tInviteRow,\n} from \"./types.ts\";\nimport type { DocEncryptionInfo } from \"./types.ts\";\nimport type { DocumentCache } from \"./DocumentCache.ts\";\n\nfunction fromBase64(b64: string): Uint8Array {\n\treturn Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n}\n\nexport interface AbracadabraClientConfig {\n\t/** Server base URL (http or https). WebSocket URL is derived automatically. */\n\turl: string;\n\t/** Initial JWT token. If omitted and persistAuth is true, loads from storage. */\n\ttoken?: string;\n\t/** Persist JWT to localStorage for stay-logged-in. Default: true in browser. */\n\tpersistAuth?: boolean;\n\t/** localStorage key for token persistence. Default: \"abracadabra:auth\". */\n\tstorageKey?: string;\n\t/** Custom fetch implementation (useful for Node.js or testing). */\n\tfetch?: typeof globalThis.fetch;\n\t/**\n\t * Optional metadata cache. When provided, read methods (getDoc, listChildren,\n\t * getMe, listPermissions, listUploads) check the cache before hitting the\n\t * network. Write methods (deleteDoc, upload, deleteUpload) invalidate affected\n\t * cache entries automatically.\n\t */\n\tcache?: DocumentCache;\n}\n\nexport class AbracadabraClient {\n\tprivate _token: string | null;\n\tprivate readonly baseUrl: string;\n\tprivate readonly persistAuth: boolean;\n\tprivate readonly storageKey: string;\n\tprivate readonly _fetch: typeof globalThis.fetch;\n\treadonly cache: DocumentCache | null;\n\n\tconstructor(config: AbracadabraClientConfig) {\n\t\tthis.baseUrl = config.url.replace(/\\/+$/, \"\");\n\t\tthis.persistAuth = config.persistAuth ?? typeof localStorage !== \"undefined\";\n\t\tthis.storageKey = config.storageKey ?? \"abracadabra:auth\";\n\t\tthis._fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n\t\tthis.cache = config.cache ?? null;\n\n\t\t// Load token: explicit > persisted > null\n\t\tthis._token = config.token ?? this.loadPersistedToken() ?? null;\n\t}\n\n\t// ── Token management ─────────────────────────────────────────────────────\n\n\tget token(): string | null {\n\t\treturn this._token;\n\t}\n\n\tset token(value: string | null) {\n\t\tthis._token = value;\n\t\tif (this.persistAuth) {\n\t\t\tif (value) {\n\t\t\t\tthis.persistToken(value);\n\t\t\t} else {\n\t\t\t\tthis.clearPersistedToken();\n\t\t\t}\n\t\t}\n\t}\n\n\tget isAuthenticated(): boolean {\n\t\treturn this._token !== null;\n\t}\n\n\t/** Derives ws:// or wss:// URL from the http(s) base URL. */\n\tget wsUrl(): string {\n\t\treturn this.baseUrl\n\t\t\t.replace(/^https:\\/\\//, \"wss://\")\n\t\t\t.replace(/^http:\\/\\//, \"ws://\") + \"/ws\";\n\t}\n\n\t// ── Auth ─────────────────────────────────────────────────────────────────\n\n\t/** Register a new user with password. */\n\tasync register(opts: {\n\t\tusername: string;\n\t\tpassword: string;\n\t\temail?: string;\n\t\tdisplayName?: string;\n\t\tinviteCode?: string;\n\t}): Promise<UserProfile> {\n\t\treturn this.request<UserProfile>(\"POST\", \"/auth/register\", {\n\t\t\tbody: opts,\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t/**\n\t * Register a new user with an Ed25519 public key (crypto auth).\n\t * Username is optional — if omitted, a short identifier is derived from the key.\n\t */\n\tasync registerWithKey(opts: {\n\t\tpublicKey: string;\n\t\tusername?: string;\n\t\tdeviceName?: string;\n\t\tdisplayName?: string;\n\t\temail?: string;\n\t\tinviteCode?: string;\n\t}): Promise<UserProfile> {\n\t\tconst username = opts.username ?? `user-${opts.publicKey.slice(0, 8)}`;\n\t\treturn this.request<UserProfile>(\"POST\", \"/auth/register\", {\n\t\t\tbody: {\n\t\t\t\tusername,\n\t\t\t\tidentityPublicKey: opts.publicKey,\n\t\t\t\tdeviceName: opts.deviceName,\n\t\t\t\tdisplayName: opts.displayName,\n\t\t\t\temail: opts.email,\n\t\t\t\tinviteCode: opts.inviteCode,\n\t\t\t},\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t/** Login with username + password. Auto-persists returned token. */\n\tasync login(opts: { username: string; password: string }): Promise<string> {\n\t\tconst res = await this.request<{ token: string }>(\"POST\", \"/auth/login\", {\n\t\t\tbody: opts,\n\t\t\tauth: false,\n\t\t});\n\t\tthis.token = res.token;\n\t\treturn res.token;\n\t}\n\n\t/** Request an Ed25519 crypto auth challenge for the given public key. */\n\tasync challenge(publicKey: string): Promise<{ challenge: string; expiresAt: number }> {\n\t\treturn this.request(\"POST\", \"/auth/challenge\", {\n\t\t\tbody: { publicKey },\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t/** Verify an Ed25519 signature to complete crypto auth. Auto-persists token. */\n\tasync verify(opts: {\n\t\tpublicKey: string;\n\t\tsignature: string;\n\t\tchallenge: string;\n\t}): Promise<string> {\n\t\tconst res = await this.request<{ token: string }>(\"POST\", \"/auth/verify\", {\n\t\t\tbody: opts,\n\t\t\tauth: false,\n\t\t});\n\t\tthis.token = res.token;\n\t\treturn res.token;\n\t}\n\n\t/**\n\t * Full crypto auth flow: challenge → sign → verify.\n\t * Convenience method combining challenge() + external signing + verify().\n\t */\n\tasync loginWithKey(\n\t\tpublicKey: string,\n\t\tsignChallenge: (challenge: string) => Promise<string>,\n\t): Promise<string> {\n\t\tconst { challenge } = await this.challenge(publicKey);\n\t\tconst signature = await signChallenge(challenge);\n\t\treturn this.verify({ publicKey, signature, challenge });\n\t}\n\n\t/** Add a new Ed25519 public key to the current user (multi-device). */\n\tasync addKey(opts: { publicKey: string; deviceName?: string; x25519Key?: string }): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/keys\", { body: { publicKey: opts.publicKey, deviceName: opts.deviceName, x25519Key: opts.x25519Key } });\n\t}\n\n\t/** List all registered public keys for the current user. */\n\tasync listKeys(): Promise<PublicKeyInfo[]> {\n\t\tconst res = await this.request<{ keys: PublicKeyInfo[] }>(\"GET\", \"/auth/keys\");\n\t\treturn res.keys;\n\t}\n\n\t/** Revoke a public key by its ID. */\n\tasync revokeKey(keyId: string): Promise<void> {\n\t\tawait this.request(\"DELETE\", `/auth/keys/${encodeURIComponent(keyId)}`);\n\t}\n\n\t// ── Encryption ───────────────────────────────────────────────────────────\n\n\t/** Get encryption info for a document. */\n\tasync getDocEncryption(docId: string): Promise<DocEncryptionInfo> {\n\t\treturn this.request<DocEncryptionInfo>(\"GET\", `/docs/${encodeURIComponent(docId)}/encryption`);\n\t}\n\n\t/** Set the encryption mode for a document (no downgrade). */\n\tasync setDocEncryption(docId: string, mode: \"none\" | \"cse\" | \"e2e\"): Promise<void> {\n\t\tawait this.request(\"PATCH\", `/docs/${encodeURIComponent(docId)}/encryption`, { body: { mode } });\n\t}\n\n\t/** Get the caller's key envelope for a document (for decrypting the DocKey). */\n\tasync getMyKeyEnvelope(docId: string): Promise<{ encrypted_key: string; key_epoch: number } | null> {\n\t\ttry {\n\t\t\treturn await this.request<{ encrypted_key: string; key_epoch: number }>(\n\t\t\t\t\"GET\",\n\t\t\t\t`/docs/${encodeURIComponent(docId)}/key-envelope`,\n\t\t\t);\n\t\t} catch (e: unknown) {\n\t\t\tif (typeof e === \"object\" && e !== null && \"status\" in e && (e as { status: number }).status === 404) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t/** Upload key envelopes for a document (Owner only). */\n\tasync uploadKeyEnvelopes(\n\t\tdocId: string,\n\t\topts: { key_epoch: number; envelopes: { recipient_key_id: string; encrypted_key: string }[] },\n\t): Promise<void> {\n\t\tawait this.request(\"POST\", `/docs/${encodeURIComponent(docId)}/key-envelopes`, { body: opts });\n\t}\n\n\t/** Get the X25519 public key for a user. */\n\tasync getUserX25519Key(userId: string): Promise<string | null> {\n\t\ttry {\n\t\t\tconst res = await this.request<{ x25519_key: string }>(\n\t\t\t\t\"GET\",\n\t\t\t\t`/users/${encodeURIComponent(userId)}/x25519-key`,\n\t\t\t);\n\t\t\treturn res.x25519_key;\n\t\t} catch (e: unknown) {\n\t\t\tif (typeof e === \"object\" && e !== null && \"status\" in e && (e as { status: number }).status === 404) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t/** List all non-revoked keys for a user (Owner/Admin or self). */\n\tasync listUserKeys(userId: string): Promise<{ id: string; publicKey: string; x25519Key: string | null }[]> {\n\t\tconst res = await this.request<{ keys: { id: string; publicKey: string; x25519Key: string | null }[] }>(\n\t\t\t\"GET\",\n\t\t\t`/users/${encodeURIComponent(userId)}/keys`,\n\t\t);\n\t\treturn res.keys;\n\t}\n\n\t/** Fetch encrypted E2E update blobs since a given sequence number. */\n\tasync getE2EUpdatesSince(docId: string, sinceSeq: number): Promise<{ seq: number; data: Uint8Array }[]> {\n\t\tconst res = await this.request<{ updates: { seq: number; data: string }[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/e2e-updates?since_seq=${sinceSeq}`,\n\t\t);\n\t\treturn res.updates.map((u) => ({\n\t\t\tseq: u.seq,\n\t\t\tdata: fromBase64(u.data),\n\t\t}));\n\t}\n\n\t/** Clear token from memory and storage. */\n\tlogout(): void {\n\t\tthis.token = null;\n\t}\n\n\t// ── User ─────────────────────────────────────────────────────────────────\n\n\t/** Get the current user's profile. */\n\tasync getMe(): Promise<UserProfile> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getCurrentProfile();\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst profile = await this.request<UserProfile>(\"GET\", \"/users/me\");\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setCurrentProfile(profile).catch(() => null);\n\t\t}\n\t\treturn profile;\n\t}\n\n\t/** Update the current user's display name. */\n\tasync updateMe(opts: { displayName?: string }): Promise<void> {\n\t\tawait this.request(\"PATCH\", \"/users/me\", { body: opts });\n\t}\n\n\t// ── Documents ────────────────────────────────────────────────────────────\n\n\t/** Create a new root document. Returns its metadata. */\n\tasync createDoc(opts?: { id?: string }): Promise<DocumentMeta> {\n\t\treturn this.request<DocumentMeta>(\"POST\", \"/docs\", { body: opts ?? {} });\n\t}\n\n\t/** Get document metadata. */\n\tasync getDoc(docId: string): Promise<DocumentMeta> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getDoc(docId);\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst meta = await this.request<DocumentMeta>(\"GET\", `/docs/${encodeURIComponent(docId)}`);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setDoc(meta).catch(() => null);\n\t\t}\n\t\treturn meta;\n\t}\n\n\t/** Delete a document (requires Owner role). Cascades to children and uploads. */\n\tasync deleteDoc(docId: string): Promise<void> {\n\t\tawait this.request(\"DELETE\", `/docs/${encodeURIComponent(docId)}`);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.invalidateDoc(docId).catch(() => null);\n\t\t}\n\t}\n\n\t/** List immediate child documents. */\n\tasync listChildren(docId: string): Promise<string[]> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getChildren(docId);\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst res = await this.request<{ children: string[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/children`,\n\t\t);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setChildren(docId, res.children).catch(() => null);\n\t\t}\n\t\treturn res.children;\n\t}\n\n\t/** Create a child document under a parent (requires write permission). */\n\tasync createChild(docId: string, opts?: { child_id?: string }): Promise<DocumentMeta> {\n\t\treturn this.request<DocumentMeta>(\n\t\t\t\"POST\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/children`,\n\t\t\t{ body: opts ?? {} },\n\t\t);\n\t}\n\n\t// ── Permissions ──────────────────────────────────────────────────────────\n\n\t/** List all permissions for a document (requires read access). */\n\tasync listPermissions(docId: string): Promise<PermissionEntry[]> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getPermissions(docId);\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst res = await this.request<{ permissions: PermissionEntry[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/permissions`,\n\t\t);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setPermissions(docId, res.permissions).catch(() => null);\n\t\t}\n\t\treturn res.permissions;\n\t}\n\n\t/** Grant or change a user's role on a document (requires Owner). */\n\tasync setPermission(\n\t\tdocId: string,\n\t\topts: { user_id: string; role: \"owner\" | \"editor\" | \"viewer\" | \"observer\" },\n\t): Promise<void> {\n\t\tawait this.request(\n\t\t\t\"POST\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/permissions`,\n\t\t\t{ body: opts },\n\t\t);\n\t}\n\n\t/** Revoke a user's permission on a document (requires Owner). */\n\tasync removePermission(docId: string, opts: { user_id: string }): Promise<void> {\n\t\tawait this.request(\n\t\t\t\"DELETE\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/permissions`,\n\t\t\t{ body: opts },\n\t\t);\n\t}\n\n\t// ── Uploads ──────────────────────────────────────────────────────────────\n\n\t/** Upload a file to a document (requires write permission). */\n\tasync upload(\n\t\tdocId: string,\n\t\tfile: File | Blob,\n\t\tfilename?: string,\n\t): Promise<UploadMeta> {\n\t\tconst formData = new FormData();\n\t\tformData.append(\"file\", file, filename);\n\n\t\tconst headers: Record<string, string> = {};\n\t\tif (this._token) {\n\t\t\theaders[\"Authorization\"] = `Bearer ${this._token}`;\n\t\t}\n\n\t\tconst res = await this._fetch(\n\t\t\t`${this.baseUrl}/docs/${encodeURIComponent(docId)}/uploads`,\n\t\t\t{ method: \"POST\", headers, body: formData },\n\t\t);\n\t\tif (!res.ok) {\n\t\t\tthrow await this.toError(res);\n\t\t}\n\t\tconst meta = await res.json() as UploadMeta;\n\t\tif (this.cache) {\n\t\t\tawait this.cache.invalidateUploads(docId).catch(() => null);\n\t\t}\n\t\treturn meta;\n\t}\n\n\t/** List all uploads for a document. */\n\tasync listUploads(docId: string): Promise<UploadInfo[]> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getUploads(docId);\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst res = await this.request<{ uploads: UploadInfo[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/uploads`,\n\t\t);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setUploads(docId, res.uploads).catch(() => null);\n\t\t}\n\t\treturn res.uploads;\n\t}\n\n\t/** Download an upload as a Blob. */\n\tasync getUpload(docId: string, uploadId: string): Promise<Blob> {\n\t\tconst headers: Record<string, string> = {};\n\t\tif (this._token) {\n\t\t\theaders[\"Authorization\"] = `Bearer ${this._token}`;\n\t\t}\n\n\t\tconst res = await this._fetch(\n\t\t\t`${this.baseUrl}/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}`,\n\t\t\t{ method: \"GET\", headers },\n\t\t);\n\t\tif (!res.ok) {\n\t\t\tthrow await this.toError(res);\n\t\t}\n\t\treturn res.blob();\n\t}\n\n\t/** Delete an upload (requires uploader or document Owner). */\n\tasync deleteUpload(docId: string, uploadId: string): Promise<void> {\n\t\tawait this.request(\n\t\t\t\"DELETE\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}`,\n\t\t);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.invalidateUploads(docId).catch(() => null);\n\t\t}\n\t}\n\n\t// ── Invites ──────────────────────────────────────────────────────────────\n\n\t/** Create an invite code (requires permission per server config). */\n\tasync createInvite(opts?: { role?: string; maxUses?: number; expiresIn?: number }): Promise<InviteRow> {\n\t\treturn this.request<InviteRow>(\"POST\", \"/invites\", { body: opts ?? {} });\n\t}\n\n\t/** List invite codes visible to the current user. */\n\tasync listInvites(): Promise<InviteRow[]> {\n\t\tconst res = await this.request<{ invites: InviteRow[] }>(\"GET\", \"/invites\");\n\t\treturn res.invites;\n\t}\n\n\t/** Revoke an invite by its code. */\n\tasync revokeInvite(code: string): Promise<void> {\n\t\tawait this.request(\"DELETE\", `/invites/${encodeURIComponent(code)}`);\n\t}\n\n\t/** Redeem an invite code for the currently authenticated user. */\n\tasync redeemInvite(code: string): Promise<void> {\n\t\tawait this.request(\"POST\", \"/invites/redeem\", { body: { code } });\n\t}\n\n\t// ── System ───────────────────────────────────────────────────────────────\n\n\t/** Health check — no auth required. */\n\tasync health(): Promise<HealthStatus> {\n\t\treturn this.request<HealthStatus>(\"GET\", \"/health\", { auth: false });\n\t}\n\n\t/**\n\t * Fetch server metadata including the optional `index_doc_id` entry point.\n\t * No auth required.\n\t */\n\tasync serverInfo(): Promise<ServerInfo> {\n\t\treturn this.request<ServerInfo>(\"GET\", \"/info\", { auth: false });\n\t}\n\n\t// ── Internals ────────────────────────────────────────────────────────────\n\n\tprivate async request<T = void>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\topts?: { body?: unknown; auth?: boolean },\n\t): Promise<T> {\n\t\tconst auth = opts?.auth ?? true;\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (auth && this._token) {\n\t\t\theaders[\"Authorization\"] = `Bearer ${this._token}`;\n\t\t}\n\n\t\tconst init: RequestInit = { method, headers };\n\n\t\tif (opts?.body !== undefined) {\n\t\t\theaders[\"Content-Type\"] = \"application/json\";\n\t\t\tinit.body = JSON.stringify(opts.body);\n\t\t}\n\n\t\tconst res = await this._fetch(`${this.baseUrl}${path}`, init);\n\n\t\tif (!res.ok) {\n\t\t\tthrow await this.toError(res);\n\t\t}\n\n\t\t// 204 No Content\n\t\tif (res.status === 204) {\n\t\t\treturn undefined as T;\n\t\t}\n\n\t\treturn res.json() as Promise<T>;\n\t}\n\n\tprivate async toError(res: Response): Promise<Error> {\n\t\tlet message: string;\n\t\ttry {\n\t\t\tconst body = await res.json() as { error?: string };\n\t\t\tmessage = body.error ?? res.statusText;\n\t\t} catch {\n\t\t\tmessage = res.statusText;\n\t\t}\n\t\tconst err = new Error(message);\n\t\t(err as any).status = res.status;\n\t\treturn err;\n\t}\n\n\tprivate loadPersistedToken(): string | null {\n\t\ttry {\n\t\t\treturn localStorage.getItem(this.storageKey);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate persistToken(token: string): void {\n\t\ttry {\n\t\t\tlocalStorage.setItem(this.storageKey, token);\n\t\t} catch {\n\t\t\t// localStorage unavailable (SSR / Node.js)\n\t\t}\n\t}\n\n\tprivate clearPersistedToken(): void {\n\t\ttry {\n\t\t\tlocalStorage.removeItem(this.storageKey);\n\t\t} catch {\n\t\t\t// localStorage unavailable\n\t\t}\n\t}\n}\n","export interface CloseEvent {\n\tcode: number;\n\treason: string;\n}\n\n/**\n * The server is terminating the connection because a data frame was received\n * that is too large.\n * See: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code\n */\nexport const MessageTooBig: CloseEvent = {\n\tcode: 1009,\n\treason: \"Message Too Big\",\n};\n\n/**\n * The server successfully processed the request, asks that the requester reset\n * its document view, and is not returning any content.\n */\nexport const ResetConnection: CloseEvent = {\n\tcode: 4205,\n\treason: \"Reset Connection\",\n};\n\n/**\n * Similar to Forbidden, but specifically for use when authentication is required and has\n * failed or has not yet been provided.\n */\nexport const Unauthorized: CloseEvent = {\n\tcode: 4401,\n\treason: \"Unauthorized\",\n};\n\n/**\n * The request contained valid data and was understood by the server, but the server\n * is refusing action.\n */\nexport const Forbidden: CloseEvent = {\n\tcode: 4403,\n\treason: \"Forbidden\",\n};\n\n/**\n * The server timed out waiting for the request.\n */\nexport const ConnectionTimeout: CloseEvent = {\n\tcode: 4408,\n\treason: \"Connection Timeout\",\n};\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, Hash, toBytes } from \"./utils.js\";\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n ahash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n abytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/**\n * HKDF (RFC 5869): extract + expand in one step.\n * See https://soatok.blog/2021/11/17/understanding-hkdf/.\n * @module\n */\nimport { hmac } from \"./hmac.js\";\nimport { ahash, anumber, clean, toBytes } from \"./utils.js\";\n/**\n * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n */\nexport function extract(hash, ikm, salt) {\n ahash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen);\n return hmac(hash, toBytes(salt), toBytes(ikm));\n}\nconst HKDF_COUNTER = /* @__PURE__ */ Uint8Array.from([0]);\nconst EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();\n/**\n * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`\n * @param hash - hash function that would be used (e.g. sha256)\n * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes\n */\nexport function expand(hash, prk, info, length = 32) {\n ahash(hash);\n anumber(length);\n const olen = hash.outputLen;\n if (length > 255 * olen)\n throw new Error('Length should be <= 255*HashLen');\n const blocks = Math.ceil(length / olen);\n if (info === undefined)\n info = EMPTY_BUFFER;\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * olen);\n // Re-use HMAC instance between blocks\n const HMAC = hmac.create(hash, prk);\n const HMACTmp = HMAC._cloneInto();\n const T = new Uint8Array(HMAC.outputLen);\n for (let counter = 0; counter < blocks; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)\n .update(info)\n .update(HKDF_COUNTER)\n .digestInto(T);\n okm.set(T, olen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n clean(T, HKDF_COUNTER);\n return okm.slice(0, length);\n}\n/**\n * HKDF (RFC 5869): derive keys from an initial input.\n * Combines hkdf_extract + hkdf_expand in one step\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes\n * @example\n * import { hkdf } from '@noble/hashes/hkdf';\n * import { sha256 } from '@noble/hashes/sha2';\n * import { randomBytes } from '@noble/hashes/utils';\n * const inputKey = randomBytes(32);\n * const salt = randomBytes(32);\n * const info = 'application-key';\n * const hk1 = hkdf(sha256, inputKey, salt, info, 32);\n */\nexport const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);\n//# sourceMappingURL=hkdf.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\nexport class SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = SHA224_IV[0] | 0;\n this.B = SHA224_IV[1] | 0;\n this.C = SHA224_IV[2] | 0;\n this.D = SHA224_IV[3] | 0;\n this.E = SHA224_IV[4] | 0;\n this.F = SHA224_IV[5] | 0;\n this.G = SHA224_IV[6] | 0;\n this.H = SHA224_IV[7] | 0;\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = SHA512_IV[0] | 0;\n this.Al = SHA512_IV[1] | 0;\n this.Bh = SHA512_IV[2] | 0;\n this.Bl = SHA512_IV[3] | 0;\n this.Ch = SHA512_IV[4] | 0;\n this.Cl = SHA512_IV[5] | 0;\n this.Dh = SHA512_IV[6] | 0;\n this.Dl = SHA512_IV[7] | 0;\n this.Eh = SHA512_IV[8] | 0;\n this.El = SHA512_IV[9] | 0;\n this.Fh = SHA512_IV[10] | 0;\n this.Fl = SHA512_IV[11] | 0;\n this.Gh = SHA512_IV[12] | 0;\n this.Gl = SHA512_IV[13] | 0;\n this.Hh = SHA512_IV[14] | 0;\n this.Hl = SHA512_IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = SHA384_IV[0] | 0;\n this.Al = SHA384_IV[1] | 0;\n this.Bh = SHA384_IV[2] | 0;\n this.Bl = SHA384_IV[3] | 0;\n this.Ch = SHA384_IV[4] | 0;\n this.Cl = SHA384_IV[5] | 0;\n this.Dh = SHA384_IV[6] | 0;\n this.Dl = SHA384_IV[7] | 0;\n this.Eh = SHA384_IV[8] | 0;\n this.El = SHA384_IV[9] | 0;\n this.Fh = SHA384_IV[10] | 0;\n this.Fl = SHA384_IV[11] | 0;\n this.Gh = SHA384_IV[12] | 0;\n this.Gl = SHA384_IV[13] | 0;\n this.Hh = SHA384_IV[14] | 0;\n this.Hl = SHA384_IV[15] | 0;\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport { SHA224 as SHA224n, sha224 as sha224n, SHA256 as SHA256n, sha256 as sha256n, } from \"./sha2.js\";\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256 = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256 = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224 = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224 = sha224n;\n//# sourceMappingURL=sha256.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n, title = '') {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(value, length, title = '') {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/** Merges default options and passed options. */\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** Creates function with outputLen, blockLen, create properties from a class constructor. */\nexport function createHasher(hashCons, info = {}) {\n const hashC = (msg, opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */\nexport const oidNist = (suffix) => ({\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView } from \"./utils.js\";\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD {\n blockLen;\n outputLen;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to ||= new this.constructor();\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://www.rfc-editor.org/rfc/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal 32-byte base SHA2 hash class. */\nclass SHA2_32B extends HashMD {\n constructor(outputLen) {\n super(64, outputLen, 8, false);\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA2-256 hash class. */\nexport class _SHA256 extends SHA2_32B {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n/** Internal SHA2-224 hash class. */\nexport class _SHA224 extends SHA2_32B {\n A = SHA224_IV[0] | 0;\n B = SHA224_IV[1] | 0;\n C = SHA224_IV[2] | 0;\n D = SHA224_IV[3] | 0;\n E = SHA224_IV[4] | 0;\n F = SHA224_IV[5] | 0;\n G = SHA224_IV[6] | 0;\n H = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal 64-byte base SHA2 hash class. */\nclass SHA2_64B extends HashMD {\n constructor(outputLen) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/** Internal SHA2-512 hash class. */\nexport class _SHA512 extends SHA2_64B {\n Ah = SHA512_IV[0] | 0;\n Al = SHA512_IV[1] | 0;\n Bh = SHA512_IV[2] | 0;\n Bl = SHA512_IV[3] | 0;\n Ch = SHA512_IV[4] | 0;\n Cl = SHA512_IV[5] | 0;\n Dh = SHA512_IV[6] | 0;\n Dl = SHA512_IV[7] | 0;\n Eh = SHA512_IV[8] | 0;\n El = SHA512_IV[9] | 0;\n Fh = SHA512_IV[10] | 0;\n Fl = SHA512_IV[11] | 0;\n Gh = SHA512_IV[12] | 0;\n Gl = SHA512_IV[13] | 0;\n Hh = SHA512_IV[14] | 0;\n Hl = SHA512_IV[15] | 0;\n constructor() {\n super(64);\n }\n}\n/** Internal SHA2-384 hash class. */\nexport class _SHA384 extends SHA2_64B {\n Ah = SHA384_IV[0] | 0;\n Al = SHA384_IV[1] | 0;\n Bh = SHA384_IV[2] | 0;\n Bl = SHA384_IV[3] | 0;\n Ch = SHA384_IV[4] | 0;\n Cl = SHA384_IV[5] | 0;\n Dh = SHA384_IV[6] | 0;\n Dl = SHA384_IV[7] | 0;\n Eh = SHA384_IV[8] | 0;\n El = SHA384_IV[9] | 0;\n Fh = SHA384_IV[10] | 0;\n Fl = SHA384_IV[11] | 0;\n Gh = SHA384_IV[12] | 0;\n Gl = SHA384_IV[13] | 0;\n Hh = SHA384_IV[14] | 0;\n Hl = SHA384_IV[15] | 0;\n constructor() {\n super(48);\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA2-512/224 hash class. */\nexport class _SHA512_224 extends SHA2_64B {\n Ah = T224_IV[0] | 0;\n Al = T224_IV[1] | 0;\n Bh = T224_IV[2] | 0;\n Bl = T224_IV[3] | 0;\n Ch = T224_IV[4] | 0;\n Cl = T224_IV[5] | 0;\n Dh = T224_IV[6] | 0;\n Dl = T224_IV[7] | 0;\n Eh = T224_IV[8] | 0;\n El = T224_IV[9] | 0;\n Fh = T224_IV[10] | 0;\n Fl = T224_IV[11] | 0;\n Gh = T224_IV[12] | 0;\n Gl = T224_IV[13] | 0;\n Hh = T224_IV[14] | 0;\n Hl = T224_IV[15] | 0;\n constructor() {\n super(28);\n }\n}\n/** Internal SHA2-512/256 hash class. */\nexport class _SHA512_256 extends SHA2_64B {\n Ah = T256_IV[0] | 0;\n Al = T256_IV[1] | 0;\n Bh = T256_IV[2] | 0;\n Bl = T256_IV[3] | 0;\n Ch = T256_IV[4] | 0;\n Cl = T256_IV[5] | 0;\n Dh = T256_IV[6] | 0;\n Dl = T256_IV[7] | 0;\n Eh = T256_IV[8] | 0;\n El = T256_IV[9] | 0;\n Fh = T256_IV[10] | 0;\n Fl = T256_IV[11] | 0;\n Gh = T256_IV[12] | 0;\n Gl = T256_IV[13] | 0;\n Hh = T256_IV[14] | 0;\n Hl = T256_IV[15] | 0;\n constructor() {\n super(32);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n//# sourceMappingURL=sha2.js.map","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes as abytes_, anumber, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, } from '@noble/hashes/utils.js';\nexport { abytes, anumber, bytesToHex, concatBytes, hexToBytes, isBytes, randomBytes, } from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n// Used in weierstrass, der\nfunction abignumber(n) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n))\n throw new Error('positive bigint expected, got ' + n);\n }\n else\n anumber(n);\n return n;\n}\nexport function asafenumber(value, title = '') {\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected safe integer, got type=' + typeof value);\n }\n}\nexport function numberToHexUnpadded(num) {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n anumber(len);\n n = abignumber(n);\n const res = hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n if (res.length !== len)\n throw new Error('number too large');\n return res;\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes_(numberToHexUnpadded(abignumber(n)));\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes) {\n return Uint8Array.from(bytes);\n}\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n */\nexport function asciiToBytes(ascii) {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_1n << BigInt(n)) - _1n;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n anumber(hashLen, 'hashLen');\n anumber(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n const u8n = (len) => new Uint8Array(len); // creates Uint8Array\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...msgs) => hmacFn(k, concatBytes_(v, ...msgs)); // hmac(k)(v, ...values)\n const reseed = (seed = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= _maxDrbgIters)\n throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\nexport function validateObject(object, fields = {}, optFields = {}) {\n if (!object || typeof object !== 'object')\n throw new Error('expected valid options object');\n function checkField(fieldName, expectedType, isOpt) {\n const val = object[fieldName];\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn) {\n const map = new WeakMap();\n return (arg, ...args) => {\n const val = map.get(arg);\n if (val !== undefined)\n return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n//# sourceMappingURL=utils.js.map","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes, anumber, bytesToNumberBE, bytesToNumberLE, numberToBytesBE, numberToBytesLE, validateObject, } from \"../utils.js\";\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _16n = /* @__PURE__ */ BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num, power, modulo) {\n return FpPow(Field(modulo), num, power);\n}\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n if (modulo <= _0n)\n throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\nfunction assertIsSquare(Fp, root, n) {\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n}\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp, n) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\nfunction sqrt5mod8(Fp, n) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n assertIsSquare(Fp, root, n);\n return root;\n}\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P) {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return (Fp, n) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n)\n throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000)\n throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1)\n return sqrt3mod4;\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n if (Fp.is0(n))\n return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1)\n throw new Error('Cannot find square root');\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t))\n return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M)\n throw new Error('Cannot find square root');\n }\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P) {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n)\n return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n)\n return sqrt5mod8;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n)\n return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(Fp, num, power) {\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return Fp.ONE;\n if (power === _1n)\n return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp, nums, passZero = false) {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num))\n return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num))\n return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n// TODO: remove\nexport function FpDiv(Fp, lhs, rhs) {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n */\nexport function FpLegendre(Fp, n) {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no)\n throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp, n) {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined)\n anumber(nBitLength);\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\nclass _Field {\n ORDER;\n BITS;\n BYTES;\n isLE;\n ZERO = _0n;\n ONE = _1n;\n _lengths;\n _sqrt; // cached sqrt\n _mod;\n constructor(ORDER, opts = {}) {\n if (ORDER <= _0n)\n throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n if (typeof opts.BITS === 'number')\n _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function')\n this.sqrt = opts.sqrt;\n if (typeof opts.isLE === 'boolean')\n this.isLE = opts.isLE;\n if (opts.allowedLengths)\n this._lengths = opts.allowedLengths?.slice();\n if (typeof opts.modFromBytes === 'boolean')\n this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048)\n throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n this._sqrt = undefined;\n Object.preventExtensions(this);\n }\n create(num) {\n return mod(num, this.ORDER);\n }\n isValid(num) {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num) {\n return (num & _1n) === _1n;\n }\n neg(num) {\n return mod(-num, this.ORDER);\n }\n eql(lhs, rhs) {\n return lhs === rhs;\n }\n sqr(num) {\n return mod(num * num, this.ORDER);\n }\n add(lhs, rhs) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs, rhs) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs, rhs) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num, power) {\n return FpPow(this, num, power);\n }\n div(lhs, rhs) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n // Same as above, but doesn't normalize\n sqrN(num) {\n return num * num;\n }\n addN(lhs, rhs) {\n return lhs + rhs;\n }\n subN(lhs, rhs) {\n return lhs - rhs;\n }\n mulN(lhs, rhs) {\n return lhs * rhs;\n }\n inv(num) {\n return invert(num, this.ORDER);\n }\n sqrt(num) {\n // Caching _sqrt speeds up sqrt9mod16 by 5x and tonneli-shanks by 10%\n if (!this._sqrt)\n this._sqrt = FpSqrt(this.ORDER);\n return this._sqrt(this, num);\n }\n toBytes(num) {\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes)\n scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst) {\n return FpInvertBatch(this, lst);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a, b, condition) {\n return condition ? b : a;\n }\n}\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, opts = {}) {\n return new _Field(ORDER, opts);\n}\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.Point.Fn.ORDER)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n abytes(key);\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask } from \"../utils.js\";\nimport { Field, FpInvertBatch, validateField } from \"./modular.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport function negateCt(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\n}\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\nexport function normalizeZ(c, points) {\n const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\nfunction validateW(W, bits) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\nfunction calcWOpts(W, scalarBits) {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\nfunction calcOffsets(n, window, wOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\nfunction validateMSMPoints(points, c) {\n if (!Array.isArray(points))\n throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars, field) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error('invalid scalar at index ' + i);\n });\n}\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\nfunction getW(P) {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\nfunction assert0(n) {\n if (n !== _0n)\n throw new Error('invalid wNAF');\n}\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF {\n BASE;\n ZERO;\n Fn;\n bits;\n // Parametrized with a given Point class (not individual point)\n constructor(Point, bits) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n // non-const time multiplication ladder\n _unsafeLadder(elm, n, p = this.ZERO) {\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(point, W) {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points = [];\n let p = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n))\n throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n }\n else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n }\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n)\n break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n }\n else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n getPrecomputes(W, point, transform) {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W);\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function')\n comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n cached(point, scalar, transform) {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n unsafe(point, scalar, transform, prev) {\n const W = getW(point);\n if (W === 1)\n return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P, W) {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n hasCache(elm) {\n return getW(elm) !== 1;\n }\n}\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe(Point, point, k1, k2) {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n p1 = p1.add(acc);\n if (k2 & _1n)\n p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka secret keys / bigints)\n */\nexport function pippenger(c, points, scalars) {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength)\n throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12)\n windowSize = wbits - 3;\n else if (wbits > 4)\n windowSize = wbits - 2;\n else if (wbits > 0)\n windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe(c, points, windowSize) {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n const fieldN = c.Fn;\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero)\n for (let j = 0; j < windowSize; j++)\n res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr)\n continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\nfunction createField(order, field, isLE) {\n if (field) {\n if (field.ORDER !== order)\n throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n }\n else {\n return Field(order, { isLE });\n }\n}\n/** Validates CURVE opts and creates fields */\nexport function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {\n if (FpFnLE === undefined)\n FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object')\n throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h']) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b];\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\nexport function createKeygen(randomSecretKey, getPublicKey) {\n return function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n };\n}\n//# sourceMappingURL=curve.js.map","/**\n * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abool, abytes, aInRange, bytesToHex, bytesToNumberLE, concatBytes, copyBytes, hexToBytes, isBytes, memoized, notImplemented, validateObject, randomBytes as wcRandomBytes, } from \"../utils.js\";\nimport { createCurveFields, createKeygen, normalizeZ, wNAF, } from \"./curve.js\";\nimport {} from \"./modular.js\";\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\nfunction isEdValidXY(Fp, CURVE, x, y) {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\nexport function edwards(params, extraOpts = {}) {\n const validated = createCurveFields('edwards', params, extraOpts, extraOpts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE;\n const { h: cofactor } = CURVE;\n validateObject(extraOpts, {}, { uvRatio: 'function' });\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);\n const modP = (n) => Fp.create(n); // Function overrides\n // sqrt(u/v)\n const uvRatio = extraOpts.uvRatio ||\n ((u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n // Validate whether the passed curve params are valid.\n // equation ax² + y² = 1 + dx²y² should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title, n, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n function aedpoint(other) {\n if (!(other instanceof Point))\n throw new Error('EdwardsPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p, iz) => {\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? _8n : Fp.inv(Z); // 8 was chosen arbitrarily\n const x = modP(X * iz);\n const y = modP(Y * iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: _0n, y: _1n };\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return { x, y };\n });\n const assertValidMemo = memoized((p) => {\n const { a, d } = CURVE;\n if (p.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { X, Y, Z, T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n return true;\n });\n // Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n // base / generator point\n static BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n // zero / infinity / identity point\n static ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n // math field\n static Fp = Fp;\n // scalar field\n static Fn = Fn;\n X;\n Y;\n Z;\n T;\n constructor(X, Y, Z, T) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n acoord('x', x);\n acoord('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes, zip215 = false) {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('point.y', y, _0n, max);\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('bad point: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('bad point: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromHex(hex, zip215 = false) {\n return Point.fromBytes(hexToBytes(hex), zip215);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n precompute(windowSize = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy)\n this.multiply(_2n); // random number\n return this;\n }\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity() {\n assertValidMemo(this);\n }\n // Compare one point to another.\n equals(other) {\n aedpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { a } = CURVE;\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n aedpoint(other);\n const { a, d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n // Constant-time multiplication.\n multiply(scalar) {\n // 1 <= scalar < L\n if (!Fn.isValidNot0(scalar))\n throw new Error('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));\n return normalizeZ(Point, [p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n // Accepts optional accumulator to merge with multiply (important for sparse scalars)\n multiplyUnsafe(scalar, acc = Point.ZERO) {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar))\n throw new Error('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n)\n return Point.ZERO;\n if (this.is0() || scalar === _1n)\n return this;\n return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.multiplyUnsafe(cofactor).is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.unsafe(this, CURVE.n).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ) {\n return toAffineMemo(this, invertedZ);\n }\n clearCofactor() {\n if (cofactor === _1n)\n return this;\n return this.multiplyUnsafe(cofactor);\n }\n toBytes() {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;\n return bytes;\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const wnaf = new wNAF(Point, Fn.BITS);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points.\n */\nexport class PrimeEdwardsPoint {\n static BASE;\n static ZERO;\n static Fp;\n static Fn;\n ep;\n constructor(ep) {\n this.ep = ep;\n }\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes) {\n notImplemented();\n }\n static fromHex(_hex) {\n notImplemented();\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n // Common implementations\n clearCofactor() {\n // no-op for prime-order groups\n return this;\n }\n assertValidity() {\n this.ep.assertValidity();\n }\n toAffine(invertedZ) {\n return this.ep.toAffine(invertedZ);\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return this.toHex();\n }\n isTorsionFree() {\n return true;\n }\n isSmallOrder() {\n return false;\n }\n add(other) {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n subtract(other) {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return this.init(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return this.init(this.ep.double());\n }\n negate() {\n return this.init(this.ep.negate());\n }\n precompute(windowSize, isLazy) {\n return this.init(this.ep.precompute(windowSize, isLazy));\n }\n}\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n */\nexport function eddsa(Point, cHash, eddsaOpts = {}) {\n if (typeof cHash !== 'function')\n throw new Error('\"hash\" function param is required');\n validateObject(eddsaOpts, {}, {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n mapToCurve: 'function',\n });\n const { prehash } = eddsaOpts;\n const { BASE, Fp, Fn } = Point;\n const randomBytes = eddsaOpts.randomBytes || wcRandomBytes;\n const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);\n const domain = eddsaOpts.domain ||\n ((data, ctx, phflag) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n // Little-endian SHA512 with modulo n\n function modN_LE(hash) {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key) {\n const len = lengths.secretKey;\n abytes(key, lengths.secretKey, 'secretKey');\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = abytes(cHash(key), 2 * len, 'hashedSecretKey');\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n return { head, prefix, scalar };\n }\n /** Convenience method that creates public key from scalar. RFC8032 5.1.5 */\n function getExtendedPublicKey(secretKey) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes();\n return { head, prefix, scalar, point, pointBytes };\n }\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey) {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {\n const msg = concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, abytes(context, undefined, 'context'), !!prehash)));\n }\n /** Signs message with secret key. RFC8032 5.1.6 */\n function sign(msg, secretKey, options = {}) {\n msg = abytes(msg, undefined, 'message');\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s))\n throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result');\n }\n // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\n const verifyOpts = { zip215: true };\n /**\n * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n * An extended group equation is checked.\n */\n function verify(sig, msg, publicKey, options = verifyOpts) {\n const { context, zip215 } = options;\n const len = lengths.signature;\n sig = abytes(sig, len, 'signature');\n msg = abytes(msg, undefined, 'message');\n publicKey = abytes(publicKey, lengths.publicKey, 'publicKey');\n if (zip215 !== undefined)\n abool(zip215, 'zip215');\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder())\n return false; // zip215 allows public keys of small order\n const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed = randomBytes(lengths.seed)) {\n return abytes(seed, lengths.seed, 'seed');\n }\n function isValidSecretKey(key) {\n return isBytes(key) && key.length === Fn.BYTES;\n }\n function isValidPublicKey(key, zip215) {\n try {\n return !!Point.fromBytes(key, zip215);\n }\n catch (error) {\n return false;\n }\n }\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /**\n * Converts ed public key to x public key. Uses formula:\n * - ed25519:\n * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * - ed448:\n * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n */\n toMontgomery(publicKey) {\n const { y } = Point.fromBytes(publicKey);\n const size = lengths.publicKey;\n const is25519 = size === 32;\n if (!is25519 && size !== 57)\n throw new Error('only defined for 25519 and 448');\n const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);\n return Fp.toBytes(u);\n },\n toMontgomerySecret(secretKey) {\n const size = lengths.secretKey;\n abytes(secretKey, size);\n const hashed = cHash(secretKey.subarray(0, size));\n return adjustScalarBytes(hashed).subarray(0, size);\n },\n };\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n });\n}\n//# sourceMappingURL=edwards.js.map","import { abytes, asafenumber, asciiToBytes, bytesToNumberBE, concatBytes, isBytes, validateObject, } from \"../utils.js\";\nimport { FpInvertBatch, mod } from \"./modular.js\";\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = bytesToNumberBE;\n// Integer to Octet Stream (numberToBytesBE)\nfunction i2osp(value, length) {\n asafenumber(value);\n asafenumber(length);\n if (value < 0 || value >= 1 << (8 * length))\n throw new Error('invalid I2OSP input: ' + value);\n const res = Array.from({ length }).fill(0);\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res);\n}\nfunction strxor(a, b) {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr;\n}\n// User can always use utf8 if they want, by passing Uint8Array.\n// If string is passed, we treat it as ASCII: other formats are likely a mistake.\nfunction normDST(DST) {\n if (!isBytes(DST) && typeof DST !== 'string')\n throw new Error('DST must be Uint8Array or ascii string');\n return typeof DST === 'string' ? asciiToBytes(DST) : DST;\n}\n/**\n * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.\n * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).\n */\nexport function expand_message_xmd(msg, DST, lenInBytes, H) {\n abytes(msg);\n asafenumber(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255)\n DST = H(concatBytes(asciiToBytes('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (lenInBytes > 65535 || ell > 255)\n throw new Error('expand_message_xmd: invalid lenInBytes');\n const DST_prime = concatBytes(DST, i2osp(DST.length, 1));\n const Z_pad = i2osp(0, r_in_bytes);\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array(ell);\n const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));\n for (let i = 1; i <= ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H(concatBytes(...args));\n }\n const pseudo_random_bytes = concatBytes(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n/**\n * Produces a uniformly random byte string using an extendable-output function (XOF) H.\n * 1. The collision resistance of H MUST be at least k bits.\n * 2. H MUST be an XOF that has been proved indifferentiable from\n * a random oracle under a reasonable cryptographic assumption.\n * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).\n */\nexport function expand_message_xof(msg, DST, lenInBytes, k, H) {\n abytes(msg);\n asafenumber(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update(asciiToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest());\n}\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).\n * @param msg a byte string containing the message to hash\n * @param count the number of elements of F to output\n * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above\n * @returns [u_0, ..., u_(count - 1)], a list of field elements.\n */\nexport function hash_to_field(msg, count, options) {\n validateObject(options, {\n p: 'bigint',\n m: 'number',\n k: 'number',\n hash: 'function',\n });\n const { p, k, m, hash, expand, DST } = options;\n asafenumber(hash.outputLen, 'valid hash');\n abytes(msg);\n asafenumber(count);\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n }\n else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n }\n else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n }\n else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = mod(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\nexport function isogenyMap(field, map) {\n // Make same order as in spec\n const coeff = map.map((i) => Array.from(i).reverse());\n return (x, y) => {\n const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));\n // 6.6.3\n // Exceptional cases of iso_map are inputs that cause the denominator of\n // either rational function to evaluate to zero; such cases MUST return\n // the identity point on E.\n const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);\n x = field.mul(xn, xd_inv); // xNum / xDen\n y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)\n return { x, y };\n };\n}\nexport const _DST_scalar = asciiToBytes('HashToScalar-');\n/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */\nexport function createHasher(Point, mapToCurve, defaults) {\n if (typeof mapToCurve !== 'function')\n throw new Error('mapToCurve() must be defined');\n function map(num) {\n return Point.fromAffine(mapToCurve(num));\n }\n function clear(initial) {\n const P = initial.clearCofactor();\n if (P.equals(Point.ZERO))\n return Point.ZERO; // zero will throw in assert\n P.assertValidity();\n return P;\n }\n return {\n defaults: Object.freeze(defaults),\n Point,\n hashToCurve(msg, options) {\n const opts = Object.assign({}, defaults, options);\n const u = hash_to_field(msg, 2, opts);\n const u0 = map(u[0]);\n const u1 = map(u[1]);\n return clear(u0.add(u1));\n },\n encodeToCurve(msg, options) {\n const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};\n const opts = Object.assign({}, defaults, optsDst, options);\n const u = hash_to_field(msg, 1, opts);\n const u0 = map(u[0]);\n return clear(u0);\n },\n /** See {@link H2CHasher} */\n mapToCurve(scalars) {\n // Curves with m=1 accept only single scalar\n if (defaults.m === 1) {\n if (typeof scalars !== 'bigint')\n throw new Error('expected bigint (m=1)');\n return clear(map([scalars]));\n }\n if (!Array.isArray(scalars))\n throw new Error('expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint')\n throw new Error('expected array of bigints');\n return clear(map(scalars));\n },\n // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393\n // RFC 9380, draft-irtf-cfrg-bbs-signatures-08\n hashToScalar(msg, options) {\n // @ts-ignore\n const N = Point.Fn.ORDER;\n const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);\n return hash_to_field(msg, 1, opts)[0][0];\n },\n };\n}\n//# sourceMappingURL=hash-to-curve.js.map","/**\n * Montgomery curve methods. It's not really whole montgomery curve,\n * just bunch of very specific methods for X25519 / X448 from\n * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes, aInRange, bytesToNumberLE, copyBytes, numberToBytesLE, randomBytes, validateObject, } from \"../utils.js\";\nimport { createKeygen } from \"./curve.js\";\nimport { mod } from \"./modular.js\";\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nfunction validateOpts(curve) {\n validateObject(curve, {\n adjustScalarBytes: 'function',\n powPminus2: 'function',\n });\n return Object.freeze({ ...curve });\n}\nexport function montgomery(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = CURVE;\n const is25519 = type === 'x25519';\n if (!is25519 && type !== 'x448')\n throw new Error('invalid type');\n const randomBytes_ = rand || randomBytes;\n const montgomeryBits = is25519 ? 255 : 448;\n const fieldLen = is25519 ? 32 : 56;\n const Gu = is25519 ? BigInt(9) : BigInt(5);\n // RFC 7748 #5:\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 and\n // (156326 - 2) / 4 = 39081 for curve448/X448\n // const a = is25519 ? 156326n : 486662n;\n const a24 = is25519 ? BigInt(121665) : BigInt(39081);\n // RFC: x25519 \"the resulting integer is of the form 2^254 plus\n // eight times a value between 0 and 2^251 - 1 (inclusive)\"\n // x448: \"2^447 plus four times a value between 0 and 2^445 - 1 (inclusive)\"\n const minScalar = is25519 ? _2n ** BigInt(254) : _2n ** BigInt(447);\n const maxAdded = is25519\n ? BigInt(8) * _2n ** BigInt(251) - _1n\n : BigInt(4) * _2n ** BigInt(445) - _1n;\n const maxScalar = minScalar + maxAdded + _1n; // (inclusive)\n const modP = (n) => mod(n, P);\n const GuBytes = encodeU(Gu);\n function encodeU(u) {\n return numberToBytesLE(modP(u), fieldLen);\n }\n function decodeU(u) {\n const _u = copyBytes(abytes(u, fieldLen, 'uCoordinate'));\n // RFC: When receiving such an array, implementations of X25519\n // (but not X448) MUST mask the most significant bit in the final byte.\n if (is25519)\n _u[31] &= 127; // 0b0111_1111\n // RFC: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime. The non-canonical\n // values are 2^255 - 19 through 2^255 - 1 for X25519 and 2^448 - 2^224\n // - 1 through 2^448 - 1 for X448.\n return modP(bytesToNumberLE(_u));\n }\n function decodeScalar(scalar) {\n return bytesToNumberLE(adjustScalarBytes(copyBytes(abytes(scalar, fieldLen, 'scalar'))));\n }\n function scalarMult(scalar, u) {\n const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));\n // Some public keys are useless, of low-order. Curve author doesn't think\n // it needs to be validated, but we do it nonetheless.\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n)\n throw new Error('invalid private or public key received');\n return encodeU(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n function scalarMultBase(scalar) {\n return scalarMult(scalar, GuBytes);\n }\n const getPublicKey = scalarMultBase;\n const getSharedSecret = scalarMult;\n // cswap from RFC7748 \"example code\"\n function cswap(swap, x_2, x_3) {\n // dummy = mask(swap) AND (x_2 XOR x_3)\n // Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n // and x_3, computed, e.g., as mask(swap) = 0 - swap.\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy); // x_2 = x_2 XOR dummy\n x_3 = modP(x_3 + dummy); // x_3 = x_3 XOR dummy\n return { x_2, x_3 };\n }\n /**\n * Montgomery x-only multiplication ladder.\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(u, scalar) {\n aInRange('u', u, _0n, P);\n aInRange('scalar', scalar, minScalar, maxScalar);\n const k = scalar;\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n ({ x_2, x_3 } = cswap(swap, x_2, x_3));\n ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));\n swap = k_t;\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n ({ x_2, x_3 } = cswap(swap, x_2, x_3));\n ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));\n const z2 = powPminus2(z_2); // `Fp.pow(x, P - _2n)` is much slower equivalent\n return modP(x_2 * z2); // Return x_2 * (z_2^(p - 2))\n }\n const lengths = {\n secretKey: fieldLen,\n publicKey: fieldLen,\n seed: fieldLen,\n };\n const randomSecretKey = (seed = randomBytes_(fieldLen)) => {\n abytes(seed, lengths.seed, 'seed');\n return seed;\n };\n const utils = { randomSecretKey };\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getSharedSecret,\n getPublicKey,\n scalarMult,\n scalarMultBase,\n utils,\n GuBytes: GuBytes.slice(),\n lengths,\n });\n}\n//# sourceMappingURL=montgomery.js.map","/**\n * RFC 9497: Oblivious Pseudorandom Functions (OPRFs) Using Prime-Order Groups.\n * https://www.rfc-editor.org/rfc/rfc9497\n *\n\nOPRF allows to interactively create an `Output = PRF(Input, serverSecretKey)`:\n\n- Server cannot calculate Output by itself: it doesn't know Input\n- Client cannot calculate Output by itself: it doesn't know server secretKey\n- An attacker interception the communication can't restore Input/Output/serverSecretKey and can't\n link Input to some value.\n\n## Issues\n\n- Low-entropy inputs (e.g. password '123') enable brute-forced dictionary attacks by the server\n (solveable by domain separation in POPRF)\n- High-level protocol needs to be constructed on top, because OPRF is low-level\n\n## Use cases\n\n1. **Password-Authenticated Key Exchange (PAKE):** Enables secure password login (e.g., OPAQUE)\n without revealing the password to the server.\n2. **Private Set Intersection (PSI):** Allows two parties to compute the intersection of their\n private sets without revealing non-intersecting elements.\n3. **Anonymous Credential Systems:** Supports issuance of anonymous, unlinkable credentials\n (e.g., Privacy Pass) using blind OPRF evaluation.\n4. **Private Information Retrieval (PIR):** Helps users query databases without revealing which\n item they accessed.\n5. **Encrypted Search / Secure Indexing:** Enables keyword search over encrypted data while keeping\n queries private.\n6. **Spam Prevention and Rate-Limiting:** Issues anonymous tokens to prevent abuse\n (e.g., CAPTCHA bypass) without compromising user privacy.\n\n## Modes\n\n- OPRF: simple mode, client doesn't need to know server public key\n- VOPRF: verifable mode, allows client to verify that server used secret key corresponding to known public key\n- POPRF: partially oblivious mode, VOPRF + domain separation\n\nThere is also non-interactive mode (Evaluate) that supports creating Output in non-interactive mode with knowledge of secret key.\n\nFlow:\n- (once) Server generates secret and public keys, distributes public keys to clients\n - deterministically: `deriveKeyPair` or just random: `generateKeyPair`\n- Client blinds input: `blind(secretInput)`\n- Server evaluates blinded input: `blindEvaluate` generated by client, sends result to client\n- Client creates output using result of evaluation via 'finalize'\n\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes, asciiToBytes, bytesToNumberBE, bytesToNumberLE, concatBytes, numberToBytesBE, randomBytes, validateObject, } from \"../utils.js\";\nimport { pippenger } from \"./curve.js\";\nimport { _DST_scalar } from \"./hash-to-curve.js\";\nimport { getMinHashLength, mapHashToField } from \"./modular.js\";\n// welcome to generic hell\nexport function createORPF(opts) {\n validateObject(opts, {\n name: 'string',\n hash: 'function',\n hashToScalar: 'function',\n hashToGroup: 'function',\n });\n // TODO\n // Point: 'point',\n const { name, Point, hash } = opts;\n const { Fn } = Point;\n const hashToGroup = (msg, ctx) => opts.hashToGroup(msg, {\n DST: concatBytes(asciiToBytes('HashToGroup-'), ctx),\n });\n const hashToScalarPrefixed = (msg, ctx) => opts.hashToScalar(msg, { DST: concatBytes(_DST_scalar, ctx) });\n const randomScalar = (rng = randomBytes) => {\n const t = mapHashToField(rng(getMinHashLength(Fn.ORDER)), Fn.ORDER, Fn.isLE);\n // We cannot use Fn.fromBytes here, because field\n // can have different number of bytes (like ed448)\n return Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t);\n };\n const msm = (points, scalars) => pippenger(Point, points, scalars);\n const getCtx = (mode) => concatBytes(asciiToBytes('OPRFV1-'), new Uint8Array([mode]), asciiToBytes('-' + name));\n const ctxOPRF = getCtx(0x00);\n const ctxVOPRF = getCtx(0x01);\n const ctxPOPRF = getCtx(0x02);\n function encode(...args) {\n const res = [];\n for (const a of args) {\n if (typeof a === 'number')\n res.push(numberToBytesBE(a, 2));\n else if (typeof a === 'string')\n res.push(asciiToBytes(a));\n else {\n abytes(a);\n res.push(numberToBytesBE(a.length, 2), a);\n }\n }\n // No wipe here, since will modify actual bytes\n return concatBytes(...res);\n }\n const hashInput = (...bytes) => hash(encode(...bytes, 'Finalize'));\n function getTranscripts(B, C, D, ctx) {\n const Bm = B.toBytes();\n const seed = hash(encode(Bm, concatBytes(asciiToBytes('Seed-'), ctx)));\n const res = [];\n for (let i = 0; i < C.length; i++) {\n const Ci = C[i].toBytes();\n const Di = D[i].toBytes();\n const di = hashToScalarPrefixed(encode(seed, i, Ci, Di, 'Composite'), ctx);\n res.push(di);\n }\n return res;\n }\n function computeComposites(B, C, D, ctx) {\n const T = getTranscripts(B, C, D, ctx);\n const M = msm(C, T);\n const Z = msm(D, T);\n return { M, Z };\n }\n function computeCompositesFast(k, B, C, D, ctx) {\n const T = getTranscripts(B, C, D, ctx);\n const M = msm(C, T);\n const Z = M.multiply(k);\n return { M, Z };\n }\n function challengeTranscript(B, M, Z, t2, t3, ctx) {\n const [Bm, a0, a1, a2, a3] = [B, M, Z, t2, t3].map((i) => i.toBytes());\n return hashToScalarPrefixed(encode(Bm, a0, a1, a2, a3, 'Challenge'), ctx);\n }\n function generateProof(ctx, k, B, C, D, rng) {\n const { M, Z } = computeCompositesFast(k, B, C, D, ctx);\n const r = randomScalar(rng);\n const t2 = Point.BASE.multiply(r);\n const t3 = M.multiply(r);\n const c = challengeTranscript(B, M, Z, t2, t3, ctx);\n const s = Fn.sub(r, Fn.mul(c, k)); // r - c*k\n return concatBytes(...[c, s].map((i) => Fn.toBytes(i)));\n }\n function verifyProof(ctx, B, C, D, proof) {\n abytes(proof, 2 * Fn.BYTES);\n const { M, Z } = computeComposites(B, C, D, ctx);\n const [c, s] = [proof.subarray(0, Fn.BYTES), proof.subarray(Fn.BYTES)].map((f) => Fn.fromBytes(f));\n const t2 = Point.BASE.multiply(s).add(B.multiply(c)); // s*G + c*B\n const t3 = M.multiply(s).add(Z.multiply(c)); // s*M + c*Z\n const expectedC = challengeTranscript(B, M, Z, t2, t3, ctx);\n if (!Fn.eql(c, expectedC))\n throw new Error('proof verification failed');\n }\n function generateKeyPair() {\n const skS = randomScalar();\n const pkS = Point.BASE.multiply(skS);\n return { secretKey: Fn.toBytes(skS), publicKey: pkS.toBytes() };\n }\n function deriveKeyPair(ctx, seed, info) {\n const dst = concatBytes(asciiToBytes('DeriveKeyPair'), ctx);\n const msg = concatBytes(seed, encode(info), Uint8Array.of(0));\n for (let counter = 0; counter <= 255; counter++) {\n msg[msg.length - 1] = counter;\n const skS = opts.hashToScalar(msg, { DST: dst });\n if (Fn.is0(skS))\n continue; // should not happen\n return { secretKey: Fn.toBytes(skS), publicKey: Point.BASE.multiply(skS).toBytes() };\n }\n throw new Error('Cannot derive key');\n }\n function blind(ctx, input, rng = randomBytes) {\n const blind = randomScalar(rng);\n const inputPoint = hashToGroup(input, ctx);\n if (inputPoint.equals(Point.ZERO))\n throw new Error('Input point at infinity');\n const blinded = inputPoint.multiply(blind);\n return { blind: Fn.toBytes(blind), blinded: blinded.toBytes() };\n }\n function evaluate(ctx, secretKey, input) {\n const skS = Fn.fromBytes(secretKey);\n const inputPoint = hashToGroup(input, ctx);\n if (inputPoint.equals(Point.ZERO))\n throw new Error('Input point at infinity');\n const unblinded = inputPoint.multiply(skS).toBytes();\n return hashInput(input, unblinded);\n }\n const oprf = {\n generateKeyPair,\n deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxOPRF, seed, keyInfo),\n blind: (input, rng = randomBytes) => blind(ctxOPRF, input, rng),\n blindEvaluate(secretKey, blindedPoint) {\n const skS = Fn.fromBytes(secretKey);\n const elm = Point.fromBytes(blindedPoint);\n return elm.multiply(skS).toBytes();\n },\n finalize(input, blindBytes, evaluatedBytes) {\n const blind = Fn.fromBytes(blindBytes);\n const evalPoint = Point.fromBytes(evaluatedBytes);\n const unblinded = evalPoint.multiply(Fn.inv(blind)).toBytes();\n return hashInput(input, unblinded);\n },\n evaluate: (secretKey, input) => evaluate(ctxOPRF, secretKey, input),\n };\n const voprf = {\n generateKeyPair,\n deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxVOPRF, seed, keyInfo),\n blind: (input, rng = randomBytes) => blind(ctxVOPRF, input, rng),\n blindEvaluateBatch(secretKey, publicKey, blinded, rng = randomBytes) {\n if (!Array.isArray(blinded))\n throw new Error('expected array');\n const skS = Fn.fromBytes(secretKey);\n const pkS = Point.fromBytes(publicKey);\n const blindedPoints = blinded.map(Point.fromBytes);\n const evaluated = blindedPoints.map((i) => i.multiply(skS));\n const proof = generateProof(ctxVOPRF, skS, pkS, blindedPoints, evaluated, rng);\n return { evaluated: evaluated.map((i) => i.toBytes()), proof };\n },\n blindEvaluate(secretKey, publicKey, blinded, rng = randomBytes) {\n const res = this.blindEvaluateBatch(secretKey, publicKey, [blinded], rng);\n return { evaluated: res.evaluated[0], proof: res.proof };\n },\n finalizeBatch(items, publicKey, proof) {\n if (!Array.isArray(items))\n throw new Error('expected array');\n const pkS = Point.fromBytes(publicKey);\n const blindedPoints = items.map((i) => i.blinded).map(Point.fromBytes);\n const evalPoints = items.map((i) => i.evaluated).map(Point.fromBytes);\n verifyProof(ctxVOPRF, pkS, blindedPoints, evalPoints, proof);\n return items.map((i) => oprf.finalize(i.input, i.blind, i.evaluated));\n },\n finalize(input, blind, evaluated, blinded, publicKey, proof) {\n return this.finalizeBatch([{ input, blind, evaluated, blinded }], publicKey, proof)[0];\n },\n evaluate: (secretKey, input) => evaluate(ctxVOPRF, secretKey, input),\n };\n // NOTE: info is domain separation\n const poprf = (info) => {\n const m = hashToScalarPrefixed(encode('Info', info), ctxPOPRF);\n const T = Point.BASE.multiply(m);\n return {\n generateKeyPair,\n deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxPOPRF, seed, keyInfo),\n blind(input, publicKey, rng = randomBytes) {\n const pkS = Point.fromBytes(publicKey);\n const tweakedKey = T.add(pkS);\n if (tweakedKey.equals(Point.ZERO))\n throw new Error('tweakedKey point at infinity');\n const blind = randomScalar(rng);\n const inputPoint = hashToGroup(input, ctxPOPRF);\n if (inputPoint.equals(Point.ZERO))\n throw new Error('Input point at infinity');\n const blindedPoint = inputPoint.multiply(blind);\n return {\n blind: Fn.toBytes(blind),\n blinded: blindedPoint.toBytes(),\n tweakedKey: tweakedKey.toBytes(),\n };\n },\n blindEvaluateBatch(secretKey, blinded, rng = randomBytes) {\n if (!Array.isArray(blinded))\n throw new Error('expected array');\n const skS = Fn.fromBytes(secretKey);\n const t = Fn.add(skS, m);\n // \"Hence, this error can be a signal for the server to replace its private key\". We throw inside,\n // should be impossible.\n const invT = Fn.inv(t);\n const blindedPoints = blinded.map(Point.fromBytes);\n const evalPoints = blindedPoints.map((i) => i.multiply(invT));\n const tweakedKey = Point.BASE.multiply(t);\n const proof = generateProof(ctxPOPRF, t, tweakedKey, evalPoints, blindedPoints, rng);\n return { evaluated: evalPoints.map((i) => i.toBytes()), proof };\n },\n blindEvaluate(secretKey, blinded, rng = randomBytes) {\n const res = this.blindEvaluateBatch(secretKey, [blinded], rng);\n return { evaluated: res.evaluated[0], proof: res.proof };\n },\n finalizeBatch(items, proof, tweakedKey) {\n if (!Array.isArray(items))\n throw new Error('expected array');\n const evalPoints = items.map((i) => i.evaluated).map(Point.fromBytes);\n verifyProof(ctxPOPRF, Point.fromBytes(tweakedKey), evalPoints, items.map((i) => i.blinded).map(Point.fromBytes), proof);\n return items.map((i, j) => {\n const blind = Fn.fromBytes(i.blind);\n const point = evalPoints[j].multiply(Fn.inv(blind)).toBytes();\n return hashInput(i.input, info, point);\n });\n },\n finalize(input, blind, evaluated, blinded, proof, tweakedKey) {\n return this.finalizeBatch([{ input, blind, evaluated, blinded }], proof, tweakedKey)[0];\n },\n evaluate(secretKey, input) {\n const skS = Fn.fromBytes(secretKey);\n const inputPoint = hashToGroup(input, ctxPOPRF);\n if (inputPoint.equals(Point.ZERO))\n throw new Error('Input point at infinity');\n const t = Fn.add(skS, m);\n const invT = Fn.inv(t);\n const unblinded = inputPoint.multiply(invT).toBytes();\n return hashInput(input, info, unblinded);\n },\n };\n };\n return Object.freeze({ name, oprf, voprf, poprf, __tests: { Fn } });\n}\n//# sourceMappingURL=oprf.js.map","/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, hexToBytes } from '@noble/hashes/utils.js';\nimport {} from \"./abstract/curve.js\";\nimport { eddsa, edwards, PrimeEdwardsPoint, } from \"./abstract/edwards.js\";\nimport { _DST_scalar, createHasher, expand_message_xmd, } from \"./abstract/hash-to-curve.js\";\nimport { FpInvertBatch, FpSqrtEven, isNegativeLE, mod, pow2, } from \"./abstract/modular.js\";\nimport { montgomery } from \"./abstract/montgomery.js\";\nimport { createORPF } from \"./abstract/oprf.js\";\nimport { asciiToBytes, bytesToNumberLE, equalBytes } from \"./utils.js\";\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n// P = 2n**255n - 19n\nconst ed25519_CURVE_p = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed');\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\nfunction ed25519_pow_2_252_3(x) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ed25519_CURVE_p;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\nfunction adjustScalarBytes(bytes) {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n// √(-1) aka √(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');\n// sqrt(u/v)\nfunction uvRatio(u, v) {\n const P = ed25519_CURVE_p;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P))\n x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\nconst ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });\nconst Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();\nconst Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();\nfunction ed25519_domain(data, ctx, phflag) {\n if (ctx.length > 255)\n throw new Error('Context is too big');\n return concatBytes(asciiToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n}\nfunction ed(opts) {\n return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes }, opts));\n}\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * ```js\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * const { secretKey, publicKey } = ed25519.keygen();\n * // const publicKey = ed25519.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519.sign(msg, secretKey);\n * const isValid = ed25519.verify(sig, msg, pub); // ZIP215\n * // RFC8032 / FIPS 186-5\n * const isValid2 = ed25519.verify(sig, msg, pub, { zip215: false });\n * ```\n */\nexport const ed25519 = /* @__PURE__ */ ed({});\n/** Context version of ed25519 (ctx for domain separation). See {@link ed25519} */\nexport const ed25519ctx = /* @__PURE__ */ ed({ domain: ed25519_domain });\n/** Prehashed version of ed25519. See {@link ed25519} */\nexport const ed25519ph = /* @__PURE__ */ ed({ domain: ed25519_domain, prehash: sha512 });\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * ```js\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const alice = x25519.keygen();\n * const bob = x25519.keygen();\n * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey);\n * ```\n */\nexport const x25519 = /* @__PURE__ */ (() => {\n const P = ed25519_CURVE_p;\n return montgomery({\n P,\n type: 'x25519',\n powPminus2: (x) => {\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n });\n})();\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n/**\n * RFC 9380 method `map_to_curve_elligator2_curve25519`. Experimental name: may be renamed later.\n * @private\n */\n// prettier-ignore\nexport function _map_to_curve_elligator2_curve25519(u) {\n const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u) {\n const { xMn, xMd, yMn, yMd } = _map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n/** Hashing to ed25519 points / field. RFC 9380 methods. */\nexport const ed25519_hasher = /* @__PURE__ */ (() => createHasher(ed25519_Point, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n}))();\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');\n// Calculates 1/√(number)\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_255B = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n/**\n * Computes Elligator map for Ristretto255.\n * Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B) and on\n * the [website](https://ristretto.group/formulas/elligator.html).\n */\nfunction calcElligatorRistrettoMap(r0) {\n const { d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n) => Fp.create(n);\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P))\n s_ = mod(-s_);\n if (!Ns_D_is_sq)\n s = s_; // 7\n if (!Ns_D_is_sq)\n c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519_Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/EdwardsPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like EdwardsPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint {\n // Do NOT change syntax: the following gymnastics is done,\n // because typescript strips comments, which makes bundlers disable tree-shaking.\n // prettier-ignore\n static BASE = \n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))();\n // prettier-ignore\n static ZERO = \n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))();\n // prettier-ignore\n static Fp = \n /* @__PURE__ */ (() => Fp)();\n // prettier-ignore\n static Fn = \n /* @__PURE__ */ (() => Fn)();\n constructor(ep) {\n super(ep);\n }\n static fromAffine(ap) {\n return new _RistrettoPoint(ed25519_Point.fromAffine(ap));\n }\n assertSame(other) {\n if (!(other instanceof _RistrettoPoint))\n throw new Error('RistrettoPoint expected');\n }\n init(ep) {\n return new _RistrettoPoint(ep);\n }\n static fromBytes(bytes) {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n) => Fp.create(n);\n const s = bytes255ToNumberLE(bytes);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P))\n x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n)\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519_Point(x, y, _1n, t));\n }\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex) {\n return _RistrettoPoint.fromBytes(hexToBytes(hex));\n }\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes() {\n let { X, Y, Z, T } = this.ep;\n const P = ed25519_CURVE_p;\n const mod = (n) => Fp.create(n);\n const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1\n const u2 = mod(X * Y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * T); // 6\n let D; // 7\n if (isNegativeLE(T * zInv, P)) {\n let _x = mod(Y * SQRT_M1);\n let _y = mod(X * SQRT_M1);\n X = _x;\n Y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n }\n else {\n D = D2; // 8\n }\n if (isNegativeLE(X * zInv, P))\n Y = mod(-Y); // 9\n let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P))\n s = mod(-s);\n return Fp.toBytes(s); // 11\n }\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other) {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n const mod = (n) => Fp.create(n);\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n is0() {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\nexport const ristretto255 = { Point: _RistrettoPoint };\n/** Hashing to ristretto255 points / field. RFC 9380 methods. */\nexport const ristretto255_hasher = {\n Point: _RistrettoPoint,\n /**\n * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:\n * * There are no test vectors\n * * encodeToCurve / mapToCurve is undefined\n * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!\n * * hashToScalar is undefined too, so we just use OPRF implementation\n * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC\n (os2ip -> bytes255ToNumberLE)\n * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map\n * * hashToScalar is undefined in RFC9380 for ristretto, we are using version from OPRF here, using bytes255ToNumblerLE will create different result if we use bytes255ToNumberLE as os2ip\n * * current version is closest to spec.\n */\n hashToCurve(msg, options) {\n // == 'hash_to_ristretto255'\n const DST = options?.DST || 'ristretto255_XMD:SHA-512_R255MAP_RO_';\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n // NOTE: RFC 9380 incorrectly calls this function 'ristretto255_map', in RFC 9496 map was function inside (per point)\n // That also lead to confustion that ristretto255_map is mapToCurve (it is not! it is old hashToCurve)\n return ristretto255_hasher.deriveToCurve(xmd);\n },\n hashToScalar(msg, options = { DST: _DST_scalar }) {\n const xmd = expand_message_xmd(msg, options.DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n /**\n * HashToCurve-like construction based on RFC 9496 (Element Derivation).\n * Converts 64 uniform random bytes into a curve point.\n *\n * WARNING: This represents an older hash-to-curve construction, preceding the finalization of RFC 9380.\n * It was later reused as a component in the newer `hash_to_ristretto255` function defined in RFC 9380.\n */\n deriveToCurve(bytes) {\n // https://www.rfc-editor.org/rfc/rfc9496.html#name-element-derivation\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n },\n};\n/** ristretto255 OPRF, defined in RFC 9497. */\nexport const ristretto255_oprf = /* @__PURE__ */ (() => createORPF({\n name: 'ristretto255-SHA512',\n Point: _RistrettoPoint,\n hash: sha512,\n hashToGroup: ristretto255_hasher.hashToCurve,\n hashToScalar: ristretto255_hasher.hashToScalar,\n}))();\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * ⟨T⟩ = { O, T, 2T, 3T, 4T, 5T, 6T, 7T }\n */\nexport const ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n//# sourceMappingURL=ed25519.js.map","/**\n * CryptoIdentityKeystore\n *\n * Per-device Ed25519 keypair, private key protected by WebAuthn PRF + AES-256-GCM.\n * Stored in IndexedDB under \"abracadabra:identity\" / \"identity\" / key \"current\".\n *\n * No private key is ever shared between devices. Each device generates its own\n * keypair, encrypts the private key with the PRF output from its own WebAuthn\n * credential, and stores the ciphertext in IndexedDB.\n *\n * Dependencies: @noble/ed25519, @noble/hashes (for HKDF)\n */\n\nimport * as ed from \"@noble/ed25519\";\nimport { hkdf } from \"@noble/hashes/hkdf\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { ed25519 as nobleEd25519Curves } from \"@noble/curves/ed25519.js\";\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\ninterface StoredIdentity {\n\t/**\n\t * Internal label stored locally. NOT sent to the server during the\n\t * challenge-response handshake — the public key is the sole auth identifier.\n\t * This may be used as a hint when calling POST /auth/register (first device)\n\t * or displayed to the user before they set a real display name.\n\t */\n\tusername: string;\n\t/** base64url-encoded Ed25519 public key (32 bytes). Primary auth identifier. */\n\tpublicKey: string;\n\t/** AES-GCM ciphertext of the 32-byte private key */\n\tencryptedPrivateKey: ArrayBuffer;\n\t/** 12-byte AES-GCM nonce */\n\tiv: Uint8Array;\n\t/** 32-byte constant PRF input salt (per-enrollment) */\n\tsalt: Uint8Array;\n\t/** WebAuthn credential ID */\n\tcredentialId: ArrayBuffer;\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────\n\nfunction toBase64url(bytes: Uint8Array): string {\n\treturn btoa(String.fromCharCode(...bytes))\n\t\t.replace(/\\+/g, \"-\")\n\t\t.replace(/\\//g, \"_\")\n\t\t.replace(/=/g, \"\");\n}\n\nfunction fromBase64url(b64: string): Uint8Array {\n\tconst padded = b64.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\tconst padLen = (4 - (padded.length % 4)) % 4;\n\tconst padded2 = padded + \"=\".repeat(padLen);\n\treturn Uint8Array.from(atob(padded2), (c) => c.charCodeAt(0));\n}\n\nconst DB_NAME = \"abracadabra:identity\";\nconst STORE_NAME = \"identity\";\nconst RECORD_KEY = \"current\";\nconst HKDF_INFO = new TextEncoder().encode(\"abracadabra-identity-v1\");\n\n// ── IndexedDB helpers ─────────────────────────────────────────────────────────\n\nfunction openDb(): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = indexedDB.open(DB_NAME, 1);\n\t\treq.onupgradeneeded = () => {\n\t\t\treq.result.createObjectStore(STORE_NAME);\n\t\t};\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nasync function dbGet(db: IDBDatabase): Promise<StoredIdentity | undefined> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst tx = db.transaction(STORE_NAME, \"readonly\");\n\t\tconst req = tx.objectStore(STORE_NAME).get(RECORD_KEY);\n\t\treq.onsuccess = () => resolve(req.result as StoredIdentity | undefined);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nasync function dbPut(db: IDBDatabase, value: StoredIdentity): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst tx = db.transaction(STORE_NAME, \"readwrite\");\n\t\tconst req = tx.objectStore(STORE_NAME).put(value, RECORD_KEY);\n\t\treq.onsuccess = () => resolve();\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nasync function dbDelete(db: IDBDatabase): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst tx = db.transaction(STORE_NAME, \"readwrite\");\n\t\tconst req = tx.objectStore(STORE_NAME).delete(RECORD_KEY);\n\t\treq.onsuccess = () => resolve();\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\n// ── Key derivation ────────────────────────────────────────────────────────────\n\nasync function deriveAesKey(prfOutput: ArrayBuffer, salt: Uint8Array): Promise<CryptoKey> {\n\tconst ikm = new Uint8Array(prfOutput);\n\tconst keyBytes = hkdf(sha256, ikm, salt, HKDF_INFO, 32);\n\treturn crypto.subtle.importKey(\"raw\", keyBytes, { name: \"AES-GCM\" }, false, [\n\t\t\"encrypt\",\n\t\t\"decrypt\",\n\t]);\n}\n\n// ── Main class ───────────────────────────────────────────────────────────────\n\nexport class CryptoIdentityKeystore {\n\t/**\n\t * One-time setup for a device: generates an Ed25519 keypair, creates a\n\t * WebAuthn credential with PRF extension, encrypts the private key, and\n\t * stores everything in IndexedDB.\n\t *\n\t * Returns the base64url-encoded public key. The caller must register this\n\t * key with the server via POST /auth/register (first device) or\n\t * POST /auth/keys (additional device).\n\t *\n\t * @param username - The user's account name.\n\t * @param rpId - WebAuthn relying party ID (e.g. \"example.com\").\n\t * @param rpName - Human-readable relying party name.\n\t */\n\tasync register(username: string, rpId: string, rpName: string): Promise<{publicKey: string; x25519PublicKey: string}> {\n\t\t// 1. Generate Ed25519 keypair\n\t\tconst privateKey = ed.utils.randomPrivateKey();\n\t\tconst publicKey = await ed.getPublicKeyAsync(privateKey);\n\n\t\t// 2. Generate per-enrollment salt\n\t\tconst salt = crypto.getRandomValues(new Uint8Array(32));\n\n\t\t// 3. Create WebAuthn credential with PRF extension\n\t\tconst credential = await navigator.credentials.create({\n\t\t\tpublicKey: {\n\t\t\t\tchallenge: crypto.getRandomValues(new Uint8Array(32)),\n\t\t\t\trp: { id: rpId, name: rpName },\n\t\t\t\tuser: {\n\t\t\t\t\tid: new TextEncoder().encode(username),\n\t\t\t\t\tname: username,\n\t\t\t\t\tdisplayName: username,\n\t\t\t\t},\n\t\t\t\tpubKeyCredParams: [\n\t\t\t\t\t{ alg: -7, type: \"public-key\" }, // ES256\n\t\t\t\t\t{ alg: -257, type: \"public-key\" }, // RS256\n\t\t\t\t],\n\t\t\t\tauthenticatorSelection: {\n\t\t\t\t\tuserVerification: \"required\",\n\t\t\t\t},\n\t\t\t\textensions: {\n\t\t\t\t\tprf: { eval: { first: salt.buffer } },\n\t\t\t\t} as AuthenticationExtensionsClientInputs,\n\t\t\t},\n\t\t}) as PublicKeyCredential | null;\n\n\t\tif (!credential) {\n\t\t\tthrow new Error(\"WebAuthn credential creation failed\");\n\t\t}\n\n\t\tconst extResults = credential.getClientExtensionResults() as {\n\t\t\tprf?: { results?: { first?: ArrayBuffer } };\n\t\t};\n\t\tconst prfOutput = extResults?.prf?.results?.first;\n\t\tif (!prfOutput) {\n\t\t\tthrow new Error(\n\t\t\t\t\"WebAuthn PRF extension not available on this authenticator. \" +\n\t\t\t\t\t\"A PRF-capable authenticator (e.g. platform authenticator with PRF support) is required.\",\n\t\t\t);\n\t\t}\n\n\t\t// 4. Derive AES key from PRF output via HKDF\n\t\tconst aesKey = await deriveAesKey(prfOutput, salt);\n\n\t\t// 5. Encrypt private key\n\t\tconst iv = crypto.getRandomValues(new Uint8Array(12));\n\t\tconst encryptedPrivateKey = await crypto.subtle.encrypt(\n\t\t\t{ name: \"AES-GCM\", iv },\n\t\t\taesKey,\n\t\t\tprivateKey,\n\t\t);\n\n\t\t// 6. Store in IndexedDB\n\t\tconst db = await openDb();\n\t\tawait dbPut(db, {\n\t\t\tusername,\n\t\t\tpublicKey: toBase64url(publicKey),\n\t\t\tencryptedPrivateKey,\n\t\t\tiv,\n\t\t\tsalt,\n\t\t\tcredentialId: credential.rawId,\n\t\t});\n\t\tdb.close();\n\n\t\tconst x25519Pub = nobleEd25519Curves.utils.toMontgomery(publicKey);\n\t\treturn { publicKey: toBase64url(publicKey), x25519PublicKey: toBase64url(x25519Pub) };\n\t}\n\n\t/**\n\t * Sign a base64url-encoded challenge using the stored Ed25519 private key.\n\t *\n\t * This triggers a WebAuthn assertion (biometric / PIN prompt) to unlock the\n\t * private key via PRF → HKDF → AES-GCM decryption. The private key is\n\t * wiped from memory after signing.\n\t *\n\t * @param challengeB64 - base64url-encoded challenge bytes from the server.\n\t * @returns base64url-encoded Ed25519 signature (64 bytes).\n\t */\n\tasync sign(challengeB64: string): Promise<string> {\n\t\tconst db = await openDb();\n\t\tconst stored = await dbGet(db);\n\t\tdb.close();\n\n\t\tif (!stored) {\n\t\t\tthrow new Error(\"No identity stored. Call register() first.\");\n\t\t}\n\n\t\t// WebAuthn assertion with PRF\n\t\tconst assertion = await navigator.credentials.get({\n\t\t\tpublicKey: {\n\t\t\t\tchallenge: crypto.getRandomValues(new Uint8Array(32)),\n\t\t\t\tallowCredentials: [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: stored.credentialId,\n\t\t\t\t\t\ttype: \"public-key\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tuserVerification: \"required\",\n\t\t\t\textensions: {\n\t\t\t\t\tprf: { eval: { first: stored.salt.buffer } },\n\t\t\t\t} as AuthenticationExtensionsClientInputs,\n\t\t\t},\n\t\t}) as PublicKeyCredential | null;\n\n\t\tif (!assertion) {\n\t\t\tthrow new Error(\"WebAuthn assertion failed\");\n\t\t}\n\n\t\tconst extResults = assertion.getClientExtensionResults() as {\n\t\t\tprf?: { results?: { first?: ArrayBuffer } };\n\t\t};\n\t\tconst prfOutput = extResults?.prf?.results?.first;\n\t\tif (!prfOutput) {\n\t\t\tthrow new Error(\"PRF output not available from authenticator\");\n\t\t}\n\n\t\t// Derive the same AES key\n\t\tconst aesKey = await deriveAesKey(prfOutput, stored.salt);\n\n\t\t// Decrypt private key\n\t\tconst privateKeyBytes = await crypto.subtle.decrypt(\n\t\t\t{ name: \"AES-GCM\", iv: stored.iv },\n\t\t\taesKey,\n\t\t\tstored.encryptedPrivateKey,\n\t\t);\n\n\t\tconst privateKey = new Uint8Array(privateKeyBytes);\n\n\t\t// Sign the challenge\n\t\tconst challengeBytes = fromBase64url(challengeB64);\n\t\tconst signature = await ed.signAsync(challengeBytes, privateKey);\n\n\t\t// Wipe private key from memory\n\t\tprivateKey.fill(0);\n\n\t\treturn toBase64url(signature);\n\t}\n\n\t/** Returns the stored base64url public key, or null if no identity exists. */\n\tasync getPublicKey(): Promise<string | null> {\n\t\tconst db = await openDb();\n\t\tconst stored = await dbGet(db);\n\t\tdb.close();\n\t\treturn stored?.publicKey ?? null;\n\t}\n\n\t/**\n\t * Returns the locally-stored internal username label, or null if no identity exists.\n\t *\n\t * This is NOT the auth identifier (the public key is). It can be used as a\n\t * hint when calling POST /auth/register, or displayed before the user sets\n\t * a real display name via PATCH /users/me.\n\t */\n\tasync getUsername(): Promise<string | null> {\n\t\tconst db = await openDb();\n\t\tconst stored = await dbGet(db);\n\t\tdb.close();\n\t\treturn stored?.username ?? null;\n\t}\n\n\t/** Returns true if an identity is stored in IndexedDB. */\n\tasync hasIdentity(): Promise<boolean> {\n\t\tconst db = await openDb();\n\t\tconst stored = await dbGet(db);\n\t\tdb.close();\n\t\treturn stored !== undefined;\n\t}\n\n\t/** Remove the stored identity from IndexedDB. */\n\tasync clear(): Promise<void> {\n\t\tconst db = await openDb();\n\t\tawait dbDelete(db);\n\t\tdb.close();\n\t}\n\n\t/**\n\t * Returns the X25519 public key derived from the stored Ed25519 private key.\n\t * Does NOT require WebAuthn — computed from the stored encrypted key... actually\n\t * we derive from the Ed25519 public key directly (Montgomery form), no decryption needed\n\t * since nobleEd25519Curves.utils.toMontgomery only needs the public key.\n\t * Returns null if no identity is stored.\n\t */\n\tasync getX25519PublicKey(): Promise<Uint8Array | null> {\n\t\tconst db = await openDb();\n\t\tconst stored = await dbGet(db);\n\t\tdb.close();\n\t\tif (!stored) return null;\n\t\tconst edPub = fromBase64url(stored.publicKey);\n\t\treturn nobleEd25519Curves.utils.toMontgomery(edPub);\n\t}\n\n\t/**\n\t * Returns the X25519 private key derived from the stored Ed25519 private key.\n\t * Requires WebAuthn assertion to decrypt the private key.\n\t * The caller MUST wipe the returned Uint8Array after use.\n\t */\n\tasync getX25519PrivateKey(): Promise<Uint8Array> {\n\t\tconst db = await openDb();\n\t\tconst stored = await dbGet(db);\n\t\tdb.close();\n\n\t\tif (!stored) {\n\t\t\tthrow new Error(\"No identity stored. Call register() first.\");\n\t\t}\n\n\t\tconst assertion = await navigator.credentials.get({\n\t\t\tpublicKey: {\n\t\t\t\tchallenge: crypto.getRandomValues(new Uint8Array(32)),\n\t\t\t\tallowCredentials: [{ id: stored.credentialId, type: \"public-key\" }],\n\t\t\t\tuserVerification: \"required\",\n\t\t\t\textensions: {\n\t\t\t\t\tprf: { eval: { first: stored.salt.buffer } },\n\t\t\t\t} as AuthenticationExtensionsClientInputs,\n\t\t\t},\n\t\t}) as PublicKeyCredential | null;\n\n\t\tif (!assertion) throw new Error(\"WebAuthn assertion failed\");\n\n\t\tconst extResults = assertion.getClientExtensionResults() as {\n\t\t\tprf?: { results?: { first?: ArrayBuffer } };\n\t\t};\n\t\tconst prfOutput = extResults?.prf?.results?.first;\n\t\tif (!prfOutput) throw new Error(\"PRF output not available from authenticator\");\n\n\t\tconst aesKey = await deriveAesKey(prfOutput, stored.salt);\n\t\tconst privateKeyBytes = await crypto.subtle.decrypt(\n\t\t\t{ name: \"AES-GCM\", iv: stored.iv },\n\t\t\taesKey,\n\t\t\tstored.encryptedPrivateKey,\n\t\t);\n\t\tconst edPrivKey = new Uint8Array(privateKeyBytes);\n\t\tconst x25519Priv = nobleEd25519Curves.utils.toMontgomerySecret(edPrivKey);\n\t\tedPrivKey.fill(0);\n\t\treturn x25519Priv;\n\t}\n}\n","/**\n * IndexedDB-backed cache for REST API metadata (documents, children, profiles,\n * permissions, uploads). Provides offline-first read access to data fetched\n * from the server.\n *\n * Each entry carries a `cachedAt` timestamp; reads return null once the TTL\n * has elapsed. The cache is scoped by server origin so the same app can work\n * against multiple backends without cross-contamination.\n *\n * Designed to be passed to AbracadabraClientConfig.cache so the client\n * automatically checks the cache before hitting the network.\n */\n\nimport type {\n\tDocumentMeta,\n\tUserProfile,\n\tPermissionEntry,\n\tUploadInfo,\n} from \"./types.ts\";\n\nconst DB_VERSION = 1;\nconst DEFAULT_TTL_MS = 5 * 60 * 1000; // 5 minutes\n\nfunction idbAvailable(): boolean {\n\treturn typeof globalThis !== \"undefined\" && \"indexedDB\" in globalThis;\n}\n\nfunction openDb(origin: string): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = globalThis.indexedDB.open(\n\t\t\t`abracadabra:meta-cache:${origin}`,\n\t\t\tDB_VERSION,\n\t\t);\n\n\t\treq.onupgradeneeded = (event) => {\n\t\t\tconst db = (event.target as IDBOpenDBRequest).result;\n\t\t\tfor (const name of [\"doc_meta\", \"children\", \"user_profile\", \"permissions\", \"uploads\"]) {\n\t\t\t\tif (!db.objectStoreNames.contains(name)) {\n\t\t\t\t\tdb.createObjectStore(name);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nfunction txPromise<T>(store: IDBObjectStore, request: IDBRequest<T>): Promise<T> {\n\treturn new Promise((resolve, reject) => {\n\t\trequest.onsuccess = () => resolve(request.result);\n\t\trequest.onerror = () => reject(request.error);\n\t});\n}\n\nexport interface DocumentCacheOptions {\n\t/** How long cached entries remain valid. Default: 5 minutes. */\n\tttlMs?: number;\n}\n\nexport class DocumentCache {\n\tprivate readonly origin: string;\n\tprivate readonly ttlMs: number;\n\tprivate dbPromise: Promise<IDBDatabase | null> | null = null;\n\tprivate db: IDBDatabase | null = null;\n\n\tconstructor(serverOrigin: string, opts?: DocumentCacheOptions) {\n\t\tthis.origin = serverOrigin;\n\t\tthis.ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;\n\t}\n\n\tprivate getDb(): Promise<IDBDatabase | null> {\n\t\tif (!idbAvailable()) return Promise.resolve(null);\n\t\tif (!this.dbPromise) {\n\t\t\tthis.dbPromise = openDb(this.origin)\n\t\t\t\t.catch(() => null)\n\t\t\t\t.then((db) => {\n\t\t\t\t\tthis.db = db;\n\t\t\t\t\treturn db;\n\t\t\t\t});\n\t\t}\n\t\treturn this.dbPromise;\n\t}\n\n\tprivate isExpired(cachedAt: number): boolean {\n\t\treturn Date.now() - cachedAt > this.ttlMs;\n\t}\n\n\t// ── Generic TTL helpers ───────────────────────────────────────────────────\n\n\tprivate async getWithTtl<T>(\n\t\tstoreName: string,\n\t\tkey: string,\n\t): Promise<T | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(storeName, \"readonly\");\n\t\tconst result = await txPromise<{ value: T; cachedAt: number } | undefined>(\n\t\t\ttx.objectStore(storeName),\n\t\t\ttx.objectStore(storeName).get(key),\n\t\t);\n\t\tif (!result) return null;\n\t\tif (this.isExpired(result.cachedAt)) {\n\t\t\t// Stale — evict asynchronously and signal miss\n\t\t\tthis.deleteKey(storeName, key).catch(() => null);\n\t\t\treturn null;\n\t\t}\n\t\treturn result.value;\n\t}\n\n\tprivate async setWithTtl<T>(storeName: string, key: string, value: T): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst entry = { value, cachedAt: Date.now() };\n\t\tconst tx = db.transaction(storeName, \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(storeName),\n\t\t\ttx.objectStore(storeName).put(entry, key),\n\t\t);\n\t}\n\n\tprivate async deleteKey(storeName: string, key: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(storeName, \"readwrite\");\n\t\tawait txPromise(tx.objectStore(storeName), tx.objectStore(storeName).delete(key));\n\t}\n\n\t// ── Document metadata ─────────────────────────────────────────────────────\n\n\tasync getDoc(docId: string): Promise<DocumentMeta | null> {\n\t\treturn this.getWithTtl<DocumentMeta>(\"doc_meta\", docId);\n\t}\n\n\tasync setDoc(meta: DocumentMeta): Promise<void> {\n\t\treturn this.setWithTtl(\"doc_meta\", meta.id, meta);\n\t}\n\n\tasync invalidateDoc(docId: string): Promise<void> {\n\t\tawait this.deleteKey(\"doc_meta\", docId).catch(() => null);\n\t}\n\n\t// ── Children list ─────────────────────────────────────────────────────────\n\n\tasync getChildren(parentId: string): Promise<string[] | null> {\n\t\treturn this.getWithTtl<string[]>(\"children\", parentId);\n\t}\n\n\tasync setChildren(parentId: string, items: string[]): Promise<void> {\n\t\treturn this.setWithTtl(\"children\", parentId, items);\n\t}\n\n\tasync invalidateChildren(parentId: string): Promise<void> {\n\t\tawait this.deleteKey(\"children\", parentId).catch(() => null);\n\t}\n\n\t// ── User profile ──────────────────────────────────────────────────────────\n\n\tasync getProfile(userId: string): Promise<UserProfile | null> {\n\t\treturn this.getWithTtl<UserProfile>(\"user_profile\", userId);\n\t}\n\n\tasync setProfile(profile: UserProfile): Promise<void> {\n\t\treturn this.setWithTtl(\"user_profile\", profile.id, profile);\n\t}\n\n\t/** Get the cached profile for the currently authenticated user. */\n\tasync getCurrentProfile(): Promise<UserProfile | null> {\n\t\treturn this.getWithTtl<UserProfile>(\"user_profile\", \"__current__\");\n\t}\n\n\t/** Cache a profile both by its ID and as the current user. */\n\tasync setCurrentProfile(profile: UserProfile): Promise<void> {\n\t\tawait Promise.all([\n\t\t\tthis.setWithTtl(\"user_profile\", profile.id, profile),\n\t\t\tthis.setWithTtl(\"user_profile\", \"__current__\", profile),\n\t\t]);\n\t}\n\n\t// ── Permissions ───────────────────────────────────────────────────────────\n\n\tasync getPermissions(docId: string): Promise<PermissionEntry[] | null> {\n\t\treturn this.getWithTtl<PermissionEntry[]>(\"permissions\", docId);\n\t}\n\n\tasync setPermissions(docId: string, items: PermissionEntry[]): Promise<void> {\n\t\treturn this.setWithTtl(\"permissions\", docId, items);\n\t}\n\n\t// ── Uploads list ──────────────────────────────────────────────────────────\n\n\tasync getUploads(docId: string): Promise<UploadInfo[] | null> {\n\t\treturn this.getWithTtl<UploadInfo[]>(\"uploads\", docId);\n\t}\n\n\tasync setUploads(docId: string, items: UploadInfo[]): Promise<void> {\n\t\treturn this.setWithTtl(\"uploads\", docId, items);\n\t}\n\n\tasync invalidateUploads(docId: string): Promise<void> {\n\t\tawait this.deleteKey(\"uploads\", docId).catch(() => null);\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\tdestroy(): void {\n\t\tthis.db?.close();\n\t\tthis.db = null;\n\t}\n}\n","/**\n * IndexedDB-backed trigram full-text search index.\n *\n * Generic: caller passes (docId, texts[]) — works for Y.Doc text content,\n * file names, document titles, or any other text. No Y.js coupling.\n *\n * Algorithm: trigram inverted index.\n * - Each document is decomposed into overlapping 3-character windows.\n * - The \"postings\" store maps trigram → [docId, ...].\n * - The \"doc_trigrams\" store maps docId → [trigram, ...] for efficient removal.\n * - search() scores by number of query trigrams that match.\n *\n * IDB transactions that touch multiple stores use the callback-only pattern\n * (not async/await inside a transaction) to avoid the transaction auto-commit\n * issue across microtask boundaries.\n */\n\nimport type { SearchResult } from \"./types.ts\";\n\nconst DB_VERSION = 1;\n\nfunction idbAvailable(): boolean {\n\treturn typeof globalThis !== \"undefined\" && \"indexedDB\" in globalThis;\n}\n\nfunction openDb(origin: string): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = globalThis.indexedDB.open(`abracadabra:search:${origin}`, DB_VERSION);\n\n\t\treq.onupgradeneeded = (event) => {\n\t\t\tconst db = (event.target as IDBOpenDBRequest).result;\n\t\t\tif (!db.objectStoreNames.contains(\"postings\")) {\n\t\t\t\tdb.createObjectStore(\"postings\");\n\t\t\t}\n\t\t\tif (!db.objectStoreNames.contains(\"doc_trigrams\")) {\n\t\t\t\tdb.createObjectStore(\"doc_trigrams\");\n\t\t\t}\n\t\t};\n\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\n/** Extract the set of trigrams for a piece of text. */\nfunction extractTrigrams(text: string): Set<string> {\n\tconst trigrams = new Set<string>();\n\tconst padded = ` ${text.toLowerCase()} `;\n\tfor (let i = 0; i <= padded.length - 3; i++) {\n\t\ttrigrams.add(padded.slice(i, i + 3));\n\t}\n\treturn trigrams;\n}\n\n/** Merge trigrams from multiple texts into a single set. */\nfunction extractAllTrigrams(texts: string[]): Set<string> {\n\tconst result = new Set<string>();\n\tfor (const t of texts) {\n\t\tfor (const trigram of extractTrigrams(t)) {\n\t\t\tresult.add(trigram);\n\t\t}\n\t}\n\treturn result;\n}\n\nexport class SearchIndex {\n\tprivate readonly origin: string;\n\tprivate dbPromise: Promise<IDBDatabase | null> | null = null;\n\tprivate db: IDBDatabase | null = null;\n\n\tconstructor(serverOrigin: string) {\n\t\tthis.origin = serverOrigin;\n\t}\n\n\tprivate getDb(): Promise<IDBDatabase | null> {\n\t\tif (!idbAvailable()) return Promise.resolve(null);\n\t\tif (!this.dbPromise) {\n\t\t\tthis.dbPromise = openDb(this.origin)\n\t\t\t\t.catch(() => null)\n\t\t\t\t.then((db) => {\n\t\t\t\t\tthis.db = db;\n\t\t\t\t\treturn db;\n\t\t\t\t});\n\t\t}\n\t\treturn this.dbPromise;\n\t}\n\n\t/**\n\t * Replace the index for docId with the given texts.\n\t * Old trigram associations are removed before new ones are added.\n\t */\n\tasync index(docId: string, texts: string[]): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\n\t\tconst newTrigrams = extractAllTrigrams(texts);\n\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst tx = db.transaction([\"postings\", \"doc_trigrams\"], \"readwrite\");\n\t\t\ttx.oncomplete = () => resolve();\n\t\t\ttx.onerror = () => reject(tx.error);\n\n\t\t\tconst postings = tx.objectStore(\"postings\");\n\t\t\tconst docTrigramsStore = tx.objectStore(\"doc_trigrams\");\n\n\t\t\t// Step 1: read old trigrams for this doc\n\t\t\tconst oldReq = docTrigramsStore.get(docId);\n\t\t\toldReq.onsuccess = () => {\n\t\t\t\tconst oldTrigrams: string[] = oldReq.result ?? [];\n\t\t\t\tlet pending = oldTrigrams.length + newTrigrams.size + 1; // +1 for doc_trigrams write\n\n\t\t\t\tfunction done() {\n\t\t\t\t\tpending--;\n\t\t\t\t\t// tx.oncomplete fires naturally once all requests settle\n\t\t\t\t}\n\n\t\t\t\t// Step 2: remove docId from each old trigram's posting list\n\t\t\t\tfor (const trigram of oldTrigrams) {\n\t\t\t\t\tconst req = postings.get(trigram);\n\t\t\t\t\treq.onsuccess = () => {\n\t\t\t\t\t\tconst list: string[] = req.result ?? [];\n\t\t\t\t\t\tconst updated = list.filter((id) => id !== docId);\n\t\t\t\t\t\tif (updated.length === 0) {\n\t\t\t\t\t\t\tpostings.delete(trigram);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpostings.put(updated, trigram);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdone();\n\t\t\t\t\t};\n\t\t\t\t\treq.onerror = done;\n\t\t\t\t}\n\n\t\t\t\t// Step 3: add docId to each new trigram's posting list\n\t\t\t\tfor (const trigram of newTrigrams) {\n\t\t\t\t\tconst req = postings.get(trigram);\n\t\t\t\t\treq.onsuccess = () => {\n\t\t\t\t\t\tconst list: string[] = req.result ?? [];\n\t\t\t\t\t\tif (!list.includes(docId)) {\n\t\t\t\t\t\t\tlist.push(docId);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpostings.put(list, trigram);\n\t\t\t\t\t\tdone();\n\t\t\t\t\t};\n\t\t\t\t\treq.onerror = done;\n\t\t\t\t}\n\n\t\t\t\t// Step 4: save new trigram set for this doc\n\t\t\t\tconst writeReq = docTrigramsStore.put([...newTrigrams], docId);\n\t\t\t\twriteReq.onsuccess = done;\n\t\t\t\twriteReq.onerror = done;\n\t\t\t};\n\t\t\toldReq.onerror = () => reject(oldReq.error);\n\t\t});\n\t}\n\n\t/** Remove all indexed content for a document. */\n\tasync remove(docId: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst tx = db.transaction([\"postings\", \"doc_trigrams\"], \"readwrite\");\n\t\t\ttx.oncomplete = () => resolve();\n\t\t\ttx.onerror = () => reject(tx.error);\n\n\t\t\tconst postings = tx.objectStore(\"postings\");\n\t\t\tconst docTrigramsStore = tx.objectStore(\"doc_trigrams\");\n\n\t\t\tconst oldReq = docTrigramsStore.get(docId);\n\t\t\toldReq.onsuccess = () => {\n\t\t\t\tconst oldTrigrams: string[] = oldReq.result ?? [];\n\n\t\t\t\tfor (const trigram of oldTrigrams) {\n\t\t\t\t\tconst req = postings.get(trigram);\n\t\t\t\t\treq.onsuccess = () => {\n\t\t\t\t\t\tconst list: string[] = req.result ?? [];\n\t\t\t\t\t\tconst updated = list.filter((id) => id !== docId);\n\t\t\t\t\t\tif (updated.length === 0) {\n\t\t\t\t\t\t\tpostings.delete(trigram);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpostings.put(updated, trigram);\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tdocTrigramsStore.delete(docId);\n\t\t\t};\n\t\t\toldReq.onerror = () => reject(oldReq.error);\n\t\t});\n\t}\n\n\t/**\n\t * Search for documents matching the query.\n\t * Returns results sorted by score (matching trigram count) descending.\n\t */\n\tasync search(query: string, limit = 20): Promise<SearchResult[]> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\n\t\tconst queryTrigrams = [...extractTrigrams(query)];\n\t\tif (queryTrigrams.length === 0) return [];\n\n\t\treturn new Promise<SearchResult[]>((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"postings\", \"readonly\");\n\t\t\tconst postings = tx.objectStore(\"postings\");\n\t\t\tconst scores = new Map<string, number>();\n\t\t\tlet remaining = queryTrigrams.length;\n\n\t\t\tfor (const trigram of queryTrigrams) {\n\t\t\t\tconst req = postings.get(trigram);\n\t\t\t\treq.onsuccess = () => {\n\t\t\t\t\tconst docIds: string[] = req.result ?? [];\n\t\t\t\t\tfor (const docId of docIds) {\n\t\t\t\t\t\tscores.set(docId, (scores.get(docId) ?? 0) + 1);\n\t\t\t\t\t}\n\t\t\t\t\tremaining--;\n\t\t\t\t\tif (remaining === 0) {\n\t\t\t\t\t\tconst results: SearchResult[] = [...scores.entries()]\n\t\t\t\t\t\t\t.map(([docId, score]) => ({ docId, score }))\n\t\t\t\t\t\t\t.sort((a, b) => b.score - a.score)\n\t\t\t\t\t\t\t.slice(0, limit);\n\t\t\t\t\t\tresolve(results);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\treq.onerror = () => {\n\t\t\t\t\tremaining--;\n\t\t\t\t\tif (remaining === 0) {\n\t\t\t\t\t\tconst results: SearchResult[] = [...scores.entries()]\n\t\t\t\t\t\t\t.map(([docId, score]) => ({ docId, score }))\n\t\t\t\t\t\t\t.sort((a, b) => b.score - a.score)\n\t\t\t\t\t\t\t.slice(0, limit);\n\t\t\t\t\t\tresolve(results);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\n\t\t\ttx.onerror = () => reject(tx.error);\n\t\t});\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\tdestroy(): void {\n\t\tthis.db?.close();\n\t\tthis.db = null;\n\t}\n}\n","/**\n * IndexedDB-backed file blob cache with an offline-tolerant upload queue.\n *\n * Responsibilities:\n * - Cache downloaded file blobs locally so they can be served offline via\n * object URLs (URL.createObjectURL).\n * - Queue file uploads when the network is unavailable. The queue persists\n * across page reloads (IndexedDB-backed).\n * - Auto-flush the upload queue when the browser reports it is back online,\n * and expose flushQueue() for manual flushing.\n *\n * Events:\n * - \"upload:queued\" — entry added to queue\n * - \"upload:started\" — upload attempt started\n * - \"upload:done\" — upload succeeded\n * - \"upload:error\" — upload attempt failed\n *\n * Falls back to a silent no-op when IndexedDB is unavailable (SSR / Node.js).\n */\n\nimport type { UploadQueueEntry } from \"./types.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport EventEmitter from \"./EventEmitter.ts\";\n\nconst DB_VERSION = 1;\n\nfunction idbAvailable(): boolean {\n\treturn typeof globalThis !== \"undefined\" && \"indexedDB\" in globalThis;\n}\n\nfunction openDb(origin: string): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = globalThis.indexedDB.open(`abracadabra:files:${origin}`, DB_VERSION);\n\n\t\treq.onupgradeneeded = (event) => {\n\t\t\tconst db = (event.target as IDBOpenDBRequest).result;\n\t\t\tif (!db.objectStoreNames.contains(\"blobs\")) {\n\t\t\t\tdb.createObjectStore(\"blobs\");\n\t\t\t}\n\t\t\tif (!db.objectStoreNames.contains(\"upload_queue\")) {\n\t\t\t\tdb.createObjectStore(\"upload_queue\", { keyPath: \"id\" });\n\t\t\t}\n\t\t};\n\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nfunction txPromise<T>(store: IDBObjectStore, request: IDBRequest<T>): Promise<T> {\n\treturn new Promise((resolve, reject) => {\n\t\trequest.onsuccess = () => resolve(request.result);\n\t\trequest.onerror = () => reject(request.error);\n\t});\n}\n\ninterface BlobCacheEntry {\n\tblob: Blob;\n\tmime_type: string;\n\tfilename: string;\n\tcachedAt: number;\n}\n\nexport class FileBlobStore extends EventEmitter {\n\tprivate readonly origin: string;\n\tprivate readonly client: AbracadabraClient;\n\tprivate dbPromise: Promise<IDBDatabase | null> | null = null;\n\tprivate db: IDBDatabase | null = null;\n\n\t/** Tracks active object URLs so we can revoke them on destroy. */\n\tprivate readonly objectUrls = new Map<string, string>();\n\n\t/** Prevents concurrent flush runs. */\n\tprivate _flushing = false;\n\n\tprivate readonly _onlineHandler: () => void;\n\n\tconstructor(serverOrigin: string, client: AbracadabraClient) {\n\t\tsuper();\n\t\tthis.origin = serverOrigin;\n\t\tthis.client = client;\n\n\t\tthis._onlineHandler = () => { this.flushQueue().catch(() => null); };\n\t\tif (typeof window !== \"undefined\") {\n\t\t\twindow.addEventListener(\"online\", this._onlineHandler);\n\t\t}\n\t}\n\n\tprivate getDb(): Promise<IDBDatabase | null> {\n\t\tif (!idbAvailable()) return Promise.resolve(null);\n\t\tif (!this.dbPromise) {\n\t\t\tthis.dbPromise = openDb(this.origin)\n\t\t\t\t.catch(() => null)\n\t\t\t\t.then((db) => {\n\t\t\t\t\tthis.db = db;\n\t\t\t\t\treturn db;\n\t\t\t\t});\n\t\t}\n\t\treturn this.dbPromise;\n\t}\n\n\tprivate blobKey(docId: string, uploadId: string): string {\n\t\treturn `${docId}/${uploadId}`;\n\t}\n\n\t// ── Blob cache ────────────────────────────────────────────────────────────\n\n\t/**\n\t * Return a local object URL for a file.\n\t * On first call the blob is downloaded from the server and cached in IDB.\n\t * Returns null when offline and the blob is not yet cached, or when\n\t * URL.createObjectURL is unavailable (e.g. Node.js / SSR).\n\t */\n\tasync getBlobUrl(docId: string, uploadId: string): Promise<string | null> {\n\t\t// Object URLs are only meaningful in browser environments.\n\t\tif (typeof window === \"undefined\") return null;\n\n\t\tconst key = this.blobKey(docId, uploadId);\n\n\t\t// Reuse existing in-memory object URL if available\n\t\tconst existing = this.objectUrls.get(key);\n\t\tif (existing) return existing;\n\n\t\tconst db = await this.getDb();\n\t\tif (db) {\n\t\t\tconst tx = db.transaction(\"blobs\", \"readonly\");\n\t\t\tconst entry = await txPromise<BlobCacheEntry | undefined>(\n\t\t\t\ttx.objectStore(\"blobs\"),\n\t\t\t\ttx.objectStore(\"blobs\").get(key),\n\t\t\t);\n\t\t\tif (entry) {\n\t\t\t\tconst url = URL.createObjectURL(entry.blob);\n\t\t\t\tthis.objectUrls.set(key, url);\n\t\t\t\treturn url;\n\t\t\t}\n\t\t}\n\n\t\t// Not cached — try downloading\n\t\tlet blob: Blob;\n\t\ttry {\n\t\t\tblob = await this.client.getUpload(docId, uploadId);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Cache the blob\n\t\tif (db) {\n\t\t\tconst entry: BlobCacheEntry = {\n\t\t\t\tblob,\n\t\t\t\tmime_type: blob.type,\n\t\t\t\tfilename: uploadId,\n\t\t\t\tcachedAt: Date.now(),\n\t\t\t};\n\t\t\tconst tx = db.transaction(\"blobs\", \"readwrite\");\n\t\t\ttx.objectStore(\"blobs\").put(entry, key);\n\t\t}\n\n\t\tconst url = URL.createObjectURL(blob);\n\t\tthis.objectUrls.set(key, url);\n\t\treturn url;\n\t}\n\n\t/** Revoke the object URL and remove the blob from cache. */\n\tasync evictBlob(docId: string, uploadId: string): Promise<void> {\n\t\tconst key = this.blobKey(docId, uploadId);\n\n\t\tconst url = this.objectUrls.get(key);\n\t\tif (url) {\n\t\t\tURL.revokeObjectURL(url);\n\t\t\tthis.objectUrls.delete(key);\n\t\t}\n\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"blobs\", \"readwrite\");\n\t\tawait txPromise(tx.objectStore(\"blobs\"), tx.objectStore(\"blobs\").delete(key));\n\t}\n\n\t// ── Upload queue ──────────────────────────────────────────────────────────\n\n\t/**\n\t * Queue a file for upload. Works offline — the entry is persisted to IDB\n\t * and flushed the next time the queue is flushed.\n\t * Returns the generated queue entry id.\n\t */\n\tasync queueUpload(\n\t\tdocId: string,\n\t\tfile: File | Blob,\n\t\tfilename?: string,\n\t): Promise<string> {\n\t\tconst id = crypto.randomUUID();\n\t\tconst resolvedFilename =\n\t\t\tfile instanceof File ? file.name : (filename ?? \"file\");\n\n\t\tconst entry: UploadQueueEntry = {\n\t\t\tid,\n\t\t\tdocId,\n\t\t\tfile,\n\t\t\tfilename: resolvedFilename,\n\t\t\tstatus: \"pending\",\n\t\t\tcreatedAt: Date.now(),\n\t\t};\n\n\t\tconst db = await this.getDb();\n\t\tif (db) {\n\t\t\tconst tx = db.transaction(\"upload_queue\", \"readwrite\");\n\t\t\tawait txPromise(\n\t\t\t\ttx.objectStore(\"upload_queue\"),\n\t\t\t\ttx.objectStore(\"upload_queue\").put(entry),\n\t\t\t);\n\t\t}\n\n\t\tthis.emit(\"upload:queued\", entry);\n\t\treturn id;\n\t}\n\n\t/** Return all upload queue entries. */\n\tasync getQueue(): Promise<UploadQueueEntry[]> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"upload_queue\", \"readonly\");\n\t\t\tconst req = tx.objectStore(\"upload_queue\").getAll();\n\t\t\treq.onsuccess = () => resolve(req.result as UploadQueueEntry[]);\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\t/**\n\t * Upload all pending queue entries via AbracadabraClient.\n\t * Safe to call repeatedly — a concurrent call is a no-op.\n\t * Entries that fail are marked with status \"error\" and left in the queue.\n\t */\n\tasync flushQueue(): Promise<void> {\n\t\tif (this._flushing) return;\n\t\tthis._flushing = true;\n\n\t\ttry {\n\t\t\tconst all = await this.getQueue();\n\t\t\tconst pending = all.filter((e) => e.status === \"pending\");\n\n\t\t\tfor (const entry of pending) {\n\t\t\t\tawait this._updateQueueEntry(entry.id, { status: \"uploading\" });\n\t\t\t\tthis.emit(\"upload:started\", { ...entry, status: \"uploading\" });\n\n\t\t\t\ttry {\n\t\t\t\t\tawait this.client.upload(entry.docId, entry.file, entry.filename);\n\t\t\t\t\tawait this._updateQueueEntry(entry.id, { status: \"done\" });\n\t\t\t\t\tthis.emit(\"upload:done\", { ...entry, status: \"done\" });\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tawait this._updateQueueEntry(entry.id, { status: \"error\", error: message });\n\t\t\t\t\tthis.emit(\"upload:error\", { ...entry, status: \"error\", error: message });\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._flushing = false;\n\t\t}\n\t}\n\n\tprivate async _updateQueueEntry(\n\t\tid: string,\n\t\tpatch: Partial<UploadQueueEntry>,\n\t): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"upload_queue\", \"readwrite\");\n\t\t\tconst store = tx.objectStore(\"upload_queue\");\n\t\t\tconst req = store.get(id);\n\t\t\treq.onsuccess = () => {\n\t\t\t\tif (!req.result) { resolve(); return; }\n\t\t\t\tconst updated = { ...req.result, ...patch };\n\t\t\t\tstore.put(updated);\n\t\t\t\ttx.oncomplete = () => resolve();\n\t\t\t\ttx.onerror = () => reject(tx.error);\n\t\t\t};\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\tdestroy(): void {\n\t\tif (typeof window !== \"undefined\") {\n\t\t\twindow.removeEventListener(\"online\", this._onlineHandler);\n\t\t}\n\n\t\t// Revoke all tracked object URLs\n\t\tfor (const url of this.objectUrls.values()) {\n\t\t\tURL.revokeObjectURL(url);\n\t\t}\n\t\tthis.objectUrls.clear();\n\n\t\tthis.db?.close();\n\t\tthis.db = null;\n\t\tthis.removeAllListeners();\n\t}\n}\n","/**\n * DocKeyManager\n *\n * Manages AES-256-GCM document keys for CSE and E2E encrypted documents.\n * Keys are wrapped per-user using X25519 ECDH + HKDF-SHA256 + AES-256-GCM.\n */\n\nimport { x25519 } from \"@noble/curves/ed25519.js\";\nimport { hkdf } from \"@noble/hashes/hkdf\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport type { CryptoIdentityKeystore } from \"./CryptoIdentityKeystore.ts\";\n\nconst HKDF_INFO = new TextEncoder().encode(\"abracadabra-dockey-v1\");\n\nfunction fromBase64(b64: string): Uint8Array {\n\treturn Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n}\n\nexport class DocKeyManager {\n\tprivate cache = new Map<string, { key: CryptoKey; epoch: number }>();\n\n\t/** Generate a new random AES-256-GCM document key. */\n\tstatic async generateDocKey(): Promise<CryptoKey> {\n\t\treturn crypto.subtle.generateKey(\n\t\t\t{ name: \"AES-GCM\", length: 256 },\n\t\t\ttrue,\n\t\t\t[\"encrypt\", \"decrypt\"],\n\t\t);\n\t}\n\n\t/**\n\t * Get (or fetch) the DocKey for a document.\n\t * Returns null if no envelope exists (user not provisioned).\n\t */\n\tasync getDocKey(\n\t\tdocId: string,\n\t\tclient: AbracadabraClient,\n\t\tkeystore: CryptoIdentityKeystore,\n\t): Promise<CryptoKey | null> {\n\t\tconst cached = this.cache.get(docId);\n\t\tif (cached) return cached.key;\n\n\t\tconst envelope = await client.getMyKeyEnvelope(docId);\n\t\tif (!envelope) return null;\n\n\t\tconst x25519PrivKey = await keystore.getX25519PrivateKey();\n\t\ttry {\n\t\t\tconst wrapped = fromBase64(envelope.encrypted_key);\n\t\t\tconst docKey = await this._unwrapKey(wrapped, x25519PrivKey, docId);\n\t\t\tthis.cache.set(docId, { key: docKey, epoch: envelope.key_epoch });\n\t\t\treturn docKey;\n\t\t} finally {\n\t\t\tx25519PrivKey.fill(0);\n\t\t}\n\t}\n\n\t/**\n\t * Wrap a DocKey for a recipient.\n\t * Output: [ephemeralPub(32) || nonce(12) || ciphertext(~48)] bytes\n\t */\n\tasync wrapKeyForRecipient(\n\t\tdocKey: CryptoKey,\n\t\trecipientX25519PubKey: Uint8Array,\n\t\tdocId: string,\n\t): Promise<Uint8Array> {\n\t\tconst ephemeralPriv = crypto.getRandomValues(new Uint8Array(32));\n\t\tconst ephemeralPub = x25519.getPublicKey(ephemeralPriv);\n\t\tconst sharedSecret = x25519.getSharedSecret(ephemeralPriv, recipientX25519PubKey);\n\n\t\tconst salt = new TextEncoder().encode(docId);\n\t\tconst keyBytes = hkdf(sha256, sharedSecret, salt, HKDF_INFO, 32);\n\t\tconst wrapKey = await crypto.subtle.importKey(\"raw\", keyBytes, { name: \"AES-GCM\" }, false, [\"encrypt\"]);\n\n\t\tconst rawDocKey = await crypto.subtle.exportKey(\"raw\", docKey);\n\t\tconst nonce = crypto.getRandomValues(new Uint8Array(12));\n\t\tconst ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv: nonce }, wrapKey, rawDocKey));\n\n\t\tconst result = new Uint8Array(32 + 12 + ciphertext.length);\n\t\tresult.set(ephemeralPub, 0);\n\t\tresult.set(nonce, 32);\n\t\tresult.set(ciphertext, 44);\n\t\treturn result;\n\t}\n\n\tprivate async _unwrapKey(wrapped: Uint8Array, recipientX25519PrivKey: Uint8Array, docId: string): Promise<CryptoKey> {\n\t\tconst ephemeralPub = wrapped.slice(0, 32);\n\t\tconst nonce = wrapped.slice(32, 44);\n\t\tconst ciphertext = wrapped.slice(44);\n\n\t\tconst sharedSecret = x25519.getSharedSecret(recipientX25519PrivKey, ephemeralPub);\n\t\tconst salt = new TextEncoder().encode(docId);\n\t\tconst keyBytes = hkdf(sha256, sharedSecret, salt, HKDF_INFO, 32);\n\t\tconst wrapKey = await crypto.subtle.importKey(\"raw\", keyBytes, { name: \"AES-GCM\" }, false, [\"decrypt\"]);\n\t\tconst rawDocKey = await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: nonce }, wrapKey, ciphertext);\n\t\treturn crypto.subtle.importKey(\"raw\", rawDocKey, { name: \"AES-GCM\" }, true, [\"encrypt\", \"decrypt\"]);\n\t}\n\n\t/** Clear the cached key for a document (or all if docId omitted). */\n\tclearCache(docId?: string): void {\n\t\tif (docId) {\n\t\t\tthis.cache.delete(docId);\n\t\t} else {\n\t\t\tthis.cache.clear();\n\t\t}\n\t}\n}\n","/**\n * EncryptedY - CSE (Client-Side Encryption) primitives for Yjs documents.\n *\n * Wire format for encrypted fields: [nonce(12) || AES-GCM ciphertext]\n *\n * Limitations (documented):\n * - Concurrent writes to the same Y.Map key produce last-write-wins semantics\n * (not character-level CRDT merge), because encrypted values are opaque to Yrs.\n */\n\nimport * as Y from \"yjs\";\n\n// ── Field-level encryption ─────────────────────────────────────────────────────\n\n/** Encrypt a field value with AES-256-GCM. Returns [nonce(12) || ciphertext]. */\nexport async function encryptField(value: Uint8Array, docKey: CryptoKey): Promise<Uint8Array> {\n\tconst nonce = crypto.getRandomValues(new Uint8Array(12));\n\tconst ciphertext = new Uint8Array(\n\t\tawait crypto.subtle.encrypt({ name: \"AES-GCM\", iv: nonce }, docKey, value),\n\t);\n\tconst result = new Uint8Array(12 + ciphertext.length);\n\tresult.set(nonce, 0);\n\tresult.set(ciphertext, 12);\n\treturn result;\n}\n\n/** Decrypt a field value from [nonce(12) || ciphertext] format. */\nexport async function decryptField(ciphertext: Uint8Array, docKey: CryptoKey): Promise<Uint8Array> {\n\tconst nonce = ciphertext.slice(0, 12);\n\tconst ct = ciphertext.slice(12);\n\treturn new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: nonce }, docKey, ct));\n}\n\n// ── EncryptedYMap ─────────────────────────────────────────────────────────────\n\n/**\n * A proxy wrapper around a Y.Map<Uint8Array> that transparently encrypts\n * values on .set() and decrypts on .get().\n *\n * NOTE: Concurrent writes to the same key produce last-write-wins (LWW)\n * because encrypted values are opaque blobs from Yrs's perspective.\n */\nexport class EncryptedYMap {\n\tconstructor(\n\t\tprivate readonly ymap: Y.Map<Uint8Array>,\n\t\tprivate readonly docKey: CryptoKey,\n\t) {}\n\n\tasync set(key: string, value: Uint8Array): Promise<void> {\n\t\tconst encrypted = await encryptField(value, this.docKey);\n\t\tthis.ymap.set(key, encrypted);\n\t}\n\n\tasync get(key: string): Promise<Uint8Array | null> {\n\t\tconst encrypted = this.ymap.get(key);\n\t\tif (!encrypted) return null;\n\t\ttry {\n\t\t\treturn await decryptField(encrypted, this.docKey);\n\t\t} catch {\n\t\t\treturn null; // Decryption failed (wrong key or corrupted)\n\t\t}\n\t}\n\n\thas(key: string): boolean {\n\t\treturn this.ymap.has(key);\n\t}\n\n\tdelete(key: string): void {\n\t\tthis.ymap.delete(key);\n\t}\n\n\tget size(): number {\n\t\treturn this.ymap.size;\n\t}\n\n\t/** Get all keys (encrypted values remain opaque until .get() is called). */\n\tkeys(): string[] {\n\t\treturn Array.from(this.ymap.keys());\n\t}\n\n\t/** Observe changes on the underlying Y.Map. */\n\tobserve(f: (event: Y.YMapEvent<Uint8Array>) => void): void {\n\t\tthis.ymap.observe(f);\n\t}\n\n\tunobserve(f: (event: Y.YMapEvent<Uint8Array>) => void): void {\n\t\tthis.ymap.unobserve(f);\n\t}\n}\n\n/** Create an EncryptedYMap wrapping a Y.Map<Uint8Array>. */\nexport function makeEncryptedYMap(ymap: Y.Map<Uint8Array>, docKey: CryptoKey): EncryptedYMap {\n\treturn new EncryptedYMap(ymap, docKey);\n}\n\n// ── EncryptedYText ────────────────────────────────────────────────────────────\n\n/**\n * Stores full text as a single encrypted blob in a Y.Map<Uint8Array> under a\n * fixed field name. This is last-write-wins for the entire text field.\n *\n * NOTE: This does NOT preserve character-level CRDT merge for concurrent edits.\n * It trades CRDT merge for confidentiality.\n */\nexport class EncryptedYText {\n\tprivate readonly ymap: Y.Map<Uint8Array>;\n\n\tconstructor(\n\t\tydoc: Y.Doc,\n\t\tfieldName: string,\n\t\tprivate readonly docKey: CryptoKey,\n\t) {\n\t\tthis.ymap = ydoc.getMap(`_encrypted_${fieldName}`);\n\t}\n\n\tasync set(text: string): Promise<void> {\n\t\tconst encoded = new TextEncoder().encode(text);\n\t\tconst encrypted = await encryptField(encoded, this.docKey);\n\t\tthis.ymap.set(\"v\", encrypted);\n\t}\n\n\tasync get(): Promise<string | null> {\n\t\tconst encrypted = this.ymap.get(\"v\");\n\t\tif (!encrypted) return null;\n\t\ttry {\n\t\t\tconst decoded = await decryptField(encrypted, this.docKey);\n\t\t\treturn new TextDecoder().decode(decoded);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tobserve(f: (event: Y.YMapEvent<Uint8Array>) => void): void {\n\t\tthis.ymap.observe(f);\n\t}\n\n\tunobserve(f: (event: Y.YMapEvent<Uint8Array>) => void): void {\n\t\tthis.ymap.unobserve(f);\n\t}\n}\n\n/** Create an EncryptedYText for a field in a Y.Doc. */\nexport function makeEncryptedYText(ydoc: Y.Doc, fieldName: string, docKey: CryptoKey): EncryptedYText {\n\treturn new EncryptedYText(ydoc, fieldName, docKey);\n}\n","/**\n * E2EOfflineStore\n *\n * Extends OfflineStore with transparent AES-GCM encryption of the document\n * snapshot, ensuring that even if the device is compromised, the local\n * IndexedDB data cannot be read without the doc key.\n *\n * Only the snapshot is encrypted (not the meta store entries, which contain\n * non-sensitive data like sequence numbers).\n *\n * Key availability limitation: if the user's WebAuthn key is not in\n * DocKeyManager's in-memory cache and there is no network, E2E docs show\n * empty — this is expected Phase 2 behavior.\n */\n\nimport { OfflineStore } from \"./OfflineStore.ts\";\nimport { encryptField, decryptField } from \"./EncryptedY.ts\";\n\nexport class E2EOfflineStore extends OfflineStore {\n\tprivate readonly docKey: CryptoKey;\n\n\t/**\n\t * @param docId The document UUID.\n\t * @param serverOrigin Hostname of the server (namespaces the IDB key).\n\t * @param docKey AES-GCM CryptoKey used to encrypt/decrypt the snapshot.\n\t */\n\tconstructor(docId: string, serverOrigin: string | undefined, docKey: CryptoKey) {\n\t\tsuper(docId, serverOrigin);\n\t\tthis.docKey = docKey;\n\t}\n\n\t/**\n\t * Encrypt the snapshot before storing it.\n\t */\n\toverride async saveDocSnapshot(snapshot: Uint8Array): Promise<void> {\n\t\tconst encrypted = await encryptField(snapshot, this.docKey);\n\t\tawait super.saveDocSnapshot(encrypted);\n\t}\n\n\t/**\n\t * Decrypt the snapshot after loading it.\n\t * Returns null if decryption fails (e.g. key mismatch or corrupt data).\n\t */\n\toverride async getDocSnapshot(): Promise<Uint8Array | null> {\n\t\tconst encrypted = await super.getDocSnapshot();\n\t\tif (!encrypted) return null;\n\t\ttry {\n\t\t\treturn await decryptField(encrypted, this.docKey);\n\t\t} catch {\n\t\t\t// Key mismatch or tampered data — return null so the provider falls\n\t\t\t// back to fetching from the server.\n\t\t\treturn null;\n\t\t}\n\t}\n}\n","/**\n * E2EAbracadabraProvider\n *\n * Extends AbracadabraProvider with full E2E encryption support.\n *\n * Differences from standard provider:\n * - startSync() sends a stateless e2e_sync_request instead of SYNC_STEP1\n * - On receiving e2e_ready, fetches all blobs via REST, decrypts, applies to Y.Doc\n * - Local updates are AES-GCM encrypted before sending over WebSocket\n * - Incoming e2e_update stateless messages are decrypted and applied\n *\n * Phase 2 offline support:\n * - After the doc key is obtained, an E2EOfflineStore is created for this doc.\n * - The stored encrypted snapshot is applied before fetching server updates.\n * - The last-seen sequence number (e2e_seq) is persisted so only delta updates\n * are fetched on subsequent connects.\n * - After sync, a fresh encrypted snapshot is saved.\n *\n * Key availability limitation: if the user's WebAuthn key is not in\n * DocKeyManager's in-memory cache and there is no network, E2E docs show\n * empty — the key fetch requires either a cached in-memory key or network.\n */\n\nimport * as Y from \"yjs\";\nimport { AbracadabraProvider } from \"./AbracadabraProvider.ts\";\nimport type { AbracadabraProviderConfiguration } from \"./AbracadabraProvider.ts\";\nimport type { DocKeyManager } from \"./DocKeyManager.ts\";\nimport type { CryptoIdentityKeystore } from \"./CryptoIdentityKeystore.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport { UpdateMessage } from \"./OutgoingMessages/UpdateMessage.ts\";\nimport { encryptField, decryptField } from \"./EncryptedY.ts\";\nimport { E2EOfflineStore } from \"./E2EOfflineStore.ts\";\n\nfunction fromBase64(b64: string): Uint8Array {\n\treturn Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n}\n\nexport interface E2EAbracadabraProviderConfiguration extends AbracadabraProviderConfiguration {\n\tdocKeyManager: DocKeyManager;\n\tkeystore: CryptoIdentityKeystore;\n\tclient: AbracadabraClient;\n}\n\nexport class E2EAbracadabraProvider extends AbracadabraProvider {\n\tprivate readonly docKeyManager: DocKeyManager;\n\tprivate readonly keystore: CryptoIdentityKeystore;\n\tprivate readonly e2eClient: AbracadabraClient;\n\tprivate docKey: CryptoKey | null = null;\n\tprivate lastSeq = -1;\n\n\t/** E2E-encrypted offline store; created after the doc key is available. */\n\tprivate e2eStore: E2EOfflineStore | null = null;\n\tprivate readonly e2eServerOrigin: string | undefined;\n\n\tconstructor(configuration: E2EAbracadabraProviderConfiguration) {\n\t\t// Disable the parent's offline store — E2E uses its own encrypted store.\n\t\tsuper({ ...configuration, disableOfflineStore: true });\n\t\tthis.docKeyManager = configuration.docKeyManager;\n\t\tthis.keystore = configuration.keystore;\n\t\tthis.e2eClient = configuration.client;\n\n\t\t// Derive server origin for E2EOfflineStore namespacing\n\t\tthis.e2eServerOrigin = E2EAbracadabraProvider.deriveServerOrigin(\n\t\t\tconfiguration,\n\t\t\tconfiguration.client,\n\t\t);\n\t}\n\n\t/** Fetch the doc key from the server (requires WebAuthn if not cached). */\n\tprivate async ensureDocKey(): Promise<CryptoKey | null> {\n\t\tif (this.docKey) return this.docKey;\n\t\tthis.docKey = await this.docKeyManager.getDocKey(\n\t\t\tthis.configuration.name,\n\t\t\tthis.e2eClient,\n\t\t\tthis.keystore,\n\t\t);\n\n\t\t// Create the encrypted offline store now that we have the key\n\t\tif (this.docKey && !this.e2eStore) {\n\t\t\tthis.e2eStore = new E2EOfflineStore(\n\t\t\t\tthis.configuration.name,\n\t\t\t\tthis.e2eServerOrigin,\n\t\t\t\tthis.docKey,\n\t\t\t);\n\t\t}\n\n\t\treturn this.docKey;\n\t}\n\n\t/** Handle stateless messages including e2e_ready and e2e_update. */\n\toverride receiveStateless(payload: string): void {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(payload);\n\t\t} catch {\n\t\t\tsuper.receiveStateless(payload);\n\t\t\treturn;\n\t\t}\n\n\t\tconst msg = parsed as { type?: string; seq?: number; data?: string; doc_id?: string };\n\n\t\tif (msg.type === \"e2e_ready\") {\n\t\t\t// Fetch all blobs and hydrate doc\n\t\t\tthis._fetchAndApplyAllBlobs().catch((e) => {\n\t\t\t\tconsole.error(\"[E2EAbracadabraProvider] failed to fetch e2e blobs:\", e);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (msg.type === \"e2e_update\" && msg.data !== undefined && msg.seq !== undefined) {\n\t\t\tif (msg.seq <= this.lastSeq) return; // Already applied\n\t\t\tthis._decryptAndApply(fromBase64(msg.data), msg.seq).catch((e) => {\n\t\t\t\tconsole.error(\"[E2EAbracadabraProvider] failed to apply e2e_update:\", e);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tsuper.receiveStateless(payload);\n\t}\n\n\tprivate async _fetchAndApplyAllBlobs(): Promise<void> {\n\t\tconst key = await this.ensureDocKey();\n\t\tif (!key) {\n\t\t\tconsole.warn(\"[E2EAbracadabraProvider] no doc key available, cannot decrypt blobs\");\n\t\t\tthis.synced = true;\n\t\t\treturn;\n\t\t}\n\n\t\t// Phase 2: load stored snapshot + lastSeq before fetching from server\n\t\tif (this.e2eStore) {\n\t\t\tconst storedSeqStr = await this.e2eStore.getMeta(\"e2e_seq\").catch(() => null);\n\t\t\tif (storedSeqStr !== null) {\n\t\t\t\tthis.lastSeq = parseInt(storedSeqStr, 10);\n\t\t\t}\n\n\t\t\tconst snapshot = await this.e2eStore.getDocSnapshot().catch(() => null);\n\t\t\tif (snapshot) {\n\t\t\t\tY.applyUpdate(this.document, snapshot, this.e2eStore);\n\t\t\t}\n\t\t}\n\n\t\t// Only fetch updates newer than lastSeq\n\t\tconst updates = await this.e2eClient.getE2EUpdatesSince(\n\t\t\tthis.configuration.name,\n\t\t\tthis.lastSeq,\n\t\t);\n\t\tfor (const { seq, data } of updates) {\n\t\t\tawait this._decryptAndApply(data, seq);\n\t\t}\n\n\t\tthis.synced = true;\n\n\t\t// Phase 2: persist updated snapshot and lastSeq\n\t\tif (this.e2eStore) {\n\t\t\tconst snapshot = Y.encodeStateAsUpdate(this.document);\n\t\t\tawait this.e2eStore.saveDocSnapshot(snapshot).catch(() => null);\n\t\t\tawait this.e2eStore.setMeta(\"e2e_seq\", String(this.lastSeq)).catch(() => null);\n\t\t}\n\t}\n\n\tprivate async _decryptAndApply(encryptedData: Uint8Array, seq: number): Promise<void> {\n\t\tconst key = await this.ensureDocKey();\n\t\tif (!key) return;\n\t\ttry {\n\t\t\tconst plaintext = await decryptField(encryptedData, key);\n\t\t\tY.applyUpdate(this.document, plaintext, this);\n\t\t\tthis.lastSeq = Math.max(this.lastSeq, seq);\n\t\t} catch (e) {\n\t\t\tconsole.error(\"[E2EAbracadabraProvider] decryption failed for seq\", seq, e);\n\t\t}\n\t}\n\n\t/** Encrypt local updates before sending over WebSocket. */\n\toverride documentUpdateHandler(update: Uint8Array, origin: unknown): void {\n\t\tif (origin === this) return;\n\t\t// Don't call super (which would send plaintext); encrypt first\n\t\tthis._encryptAndSend(update).catch((e) => {\n\t\t\tconsole.error(\"[E2EAbracadabraProvider] failed to encrypt update:\", e);\n\t\t});\n\t}\n\n\tprivate async _encryptAndSend(update: Uint8Array): Promise<void> {\n\t\tconst key = await this.ensureDocKey();\n\t\tif (!key) {\n\t\t\tconsole.warn(\"[E2EAbracadabraProvider] no doc key, dropping update\");\n\t\t\treturn;\n\t\t}\n\t\tconst encrypted = await encryptField(update, key);\n\t\tthis.send(UpdateMessage, {\n\t\t\tupdate: encrypted,\n\t\t\tdocumentName: this.configuration.name,\n\t\t});\n\t}\n\n\toverride destroy(): void {\n\t\tthis.e2eStore?.destroy();\n\t\tthis.e2eStore = null;\n\t\tsuper.destroy();\n\t}\n}\n","/**\n * TreeTimestamps\n *\n * Attaches an afterUpdate observer on a child Y.Doc so that whenever a\n * non-offline update is applied, the `updatedAt` timestamp on the\n * corresponding entry in the root doc's `doc-tree` map is written.\n *\n * This propagates \"last edited\" timestamps to all peers via the root CRDT,\n * without requiring any server-side changes.\n *\n * Limitation: at least one client must have the child doc open after an edit\n * for the timestamp to propagate (eventually consistent).\n */\n\nimport * as Y from \"yjs\";\nimport type { OfflineStore } from \"./OfflineStore.ts\";\n\n/**\n * Attach an observer that writes `updatedAt: Date.now()` to the root\n * doc-tree entry for `childDocId` whenever the child doc receives a\n * non-offline update.\n *\n * @param treeMap The root doc's \"doc-tree\" Y.Map.\n * @param childDocId The child document's UUID (key in treeMap).\n * @param childDoc The child Y.Doc to observe.\n * @param offlineStore The child provider's OfflineStore (used to detect\n * offline-replay origins and skip them). Pass null when\n * the offline store is disabled.\n * @returns Cleanup function — call on provider destroy.\n */\nexport function attachUpdatedAtObserver(\n\ttreeMap: Y.Map<any>,\n\tchildDocId: string,\n\tchildDoc: Y.Doc,\n\tofflineStore: OfflineStore | null,\n): () => void {\n\tfunction handler(update: Uint8Array, origin: unknown): void {\n\t\t// Skip updates replayed from the local offline store — they represent\n\t\t// content that was already \"seen\" and shouldn't advance updatedAt.\n\t\tif (offlineStore !== null && origin === offlineStore) return;\n\n\t\t// Update the root tree entry (no-op if the entry doesn't exist).\n\t\tconst entry = treeMap.get(childDocId);\n\t\tif (!entry) return;\n\n\t\ttreeMap.set(childDocId, { ...entry, updatedAt: Date.now() });\n\t}\n\n\tchildDoc.on(\"update\", handler);\n\treturn () => childDoc.off(\"update\", handler);\n}\n","/**\n * BackgroundSyncPersistence\n *\n * Minimal IndexedDB store (`abracadabra:bgsync:{serverOrigin}`) that persists\n * per-document sync state across page reloads. A single object store,\n * `sync_state`, is keyed by `docId`.\n *\n * Falls back to a no-op when IndexedDB is unavailable (SSR / Node.js).\n */\n\nexport interface DocSyncState {\n\tdocId: string;\n\t/** Current lifecycle status of this document's background sync. */\n\tstatus: \"pending\" | \"syncing\" | \"synced\" | \"error\" | \"skipped\";\n\t/** Unix ms of the last successful sync, or null if never synced. */\n\tlastSynced: number | null;\n\t/** Human-readable error message if status === \"error\". */\n\terror?: string;\n\t/** Whether the document uses E2E encryption. */\n\tisE2E: boolean;\n}\n\nconst DB_VERSION = 1;\n\nfunction idbAvailable(): boolean {\n\treturn typeof globalThis !== \"undefined\" && \"indexedDB\" in globalThis;\n}\n\nfunction openDb(serverOrigin: string): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = globalThis.indexedDB.open(\n\t\t\t`abracadabra:bgsync:${serverOrigin}`,\n\t\t\tDB_VERSION,\n\t\t);\n\t\treq.onupgradeneeded = (event) => {\n\t\t\tconst db = (event.target as IDBOpenDBRequest).result;\n\t\t\tif (!db.objectStoreNames.contains(\"sync_state\")) {\n\t\t\t\tdb.createObjectStore(\"sync_state\", { keyPath: \"docId\" });\n\t\t\t}\n\t\t};\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nfunction idbPromise<T>(request: IDBRequest<T>): Promise<T> {\n\treturn new Promise((resolve, reject) => {\n\t\trequest.onsuccess = () => resolve(request.result);\n\t\trequest.onerror = () => reject(request.error);\n\t});\n}\n\nexport class BackgroundSyncPersistence {\n\tprivate dbPromise: Promise<IDBDatabase | null> | null = null;\n\tprivate readonly serverOrigin: string;\n\n\tconstructor(serverOrigin: string) {\n\t\tthis.serverOrigin = serverOrigin;\n\t}\n\n\tprivate getDb(): Promise<IDBDatabase | null> {\n\t\tif (!idbAvailable()) return Promise.resolve(null);\n\t\tif (!this.dbPromise) {\n\t\t\tthis.dbPromise = openDb(this.serverOrigin).catch(() => null);\n\t\t}\n\t\treturn this.dbPromise;\n\t}\n\n\tasync getState(docId: string): Promise<DocSyncState | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(\"sync_state\", \"readonly\");\n\t\tconst result = await idbPromise<DocSyncState | undefined>(\n\t\t\ttx.objectStore(\"sync_state\").get(docId),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\tasync getAllStates(): Promise<DocSyncState[]> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"sync_state\", \"readonly\");\n\t\t\tconst req = tx.objectStore(\"sync_state\").getAll();\n\t\t\treq.onsuccess = () => resolve(req.result as DocSyncState[]);\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\tasync setState(state: DocSyncState): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"sync_state\", \"readwrite\");\n\t\tawait idbPromise(tx.objectStore(\"sync_state\").put(state));\n\t}\n\n\tasync deleteState(docId: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"sync_state\", \"readwrite\");\n\t\tawait idbPromise(tx.objectStore(\"sync_state\").delete(docId));\n\t}\n\n\tdestroy(): void {\n\t\t// No cleanup needed — shared IDB connection managed by browser\n\t}\n}\n","/**\n * BackgroundSyncManager\n *\n * Proactively syncs all documents in the root tree map to IndexedDB so they\n * are available offline even if the user has never opened them directly.\n *\n * Key behaviours:\n * - Priority queue: sorted by updatedAt desc → never-synced first → errored last\n * - Concurrency: semaphore (default 2 parallel WS connections)\n * - Provider selection: non-E2E via rootProvider.loadChild(); E2E via\n * E2EAbracadabraProvider directly when docKeyManager + keystore are present\n * - File pre-caching: after sync, walks the Y.Doc for file refs and warms\n * the FileBlobStore cache (opt-in via prefetchFiles, default true)\n * - Cover images: at start of syncAll(), pre-caches all cover upload IDs\n * from the root tree map immediately (fire-and-forget)\n * - Periodic sync: startPeriodicSync() returns a cleanup function\n *\n * Note: This is in-page only (no Service Worker). The existing\n * flushPendingUpdates() handles offline → reconnect for open docs.\n */\n\nimport * as Y from \"yjs\";\nimport type { AbracadabraProvider } from \"./AbracadabraProvider.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport type { FileBlobStore } from \"./FileBlobStore.ts\";\nimport {\n\tBackgroundSyncPersistence,\n\ttype DocSyncState,\n} from \"./BackgroundSyncPersistence.ts\";\nimport EventEmitter from \"./EventEmitter.ts\";\nimport { E2EAbracadabraProvider } from \"./E2EAbracadabraProvider.ts\";\n\nexport interface BackgroundSyncManagerOptions {\n\t/** Max parallel WS connections for background sync. Default: 2. */\n\tconcurrency?: number;\n\t/** Timeout (ms) waiting for a provider to sync. Default: 15 000. */\n\tsyncTimeout?: number;\n\t/** Pre-cache file blobs after syncing a doc. Default: true. */\n\tprefetchFiles?: boolean;\n}\n\n/**\n * Simple semaphore for capping concurrency.\n */\nclass Semaphore {\n\tprivate slots: number;\n\tprivate queue: Array<() => void> = [];\n\n\tconstructor(limit: number) {\n\t\tthis.slots = limit;\n\t}\n\n\tacquire(): Promise<void> {\n\t\tif (this.slots > 0) {\n\t\t\tthis.slots--;\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\treturn new Promise((resolve) => this.queue.push(resolve));\n\t}\n\n\trelease(): void {\n\t\tconst next = this.queue.shift();\n\t\tif (next) {\n\t\t\tnext();\n\t\t} else {\n\t\t\tthis.slots++;\n\t\t}\n\t}\n}\n\nexport class BackgroundSyncManager extends EventEmitter {\n\tprivate readonly rootProvider: AbracadabraProvider;\n\tprivate readonly client: AbracadabraClient;\n\tprivate readonly fileBlobStore: FileBlobStore | null;\n\tprivate readonly opts: Required<BackgroundSyncManagerOptions>;\n\n\tprivate readonly persistence: BackgroundSyncPersistence;\n\tprivate readonly semaphore: Semaphore;\n\tprivate readonly syncStates = new Map<string, DocSyncState>();\n\n\tprivate _destroyed = false;\n\n\tconstructor(\n\t\trootProvider: AbracadabraProvider,\n\t\tclient: AbracadabraClient,\n\t\tfileBlobStore?: FileBlobStore | null,\n\t\topts?: BackgroundSyncManagerOptions,\n\t) {\n\t\tsuper();\n\t\tthis.rootProvider = rootProvider;\n\t\tthis.client = client;\n\t\tthis.fileBlobStore = fileBlobStore ?? null;\n\t\tthis.opts = {\n\t\t\tconcurrency: opts?.concurrency ?? 2,\n\t\t\tsyncTimeout: opts?.syncTimeout ?? 15_000,\n\t\t\tprefetchFiles: opts?.prefetchFiles ?? true,\n\t\t};\n\n\t\t// Derive server origin from client URL for IDB namespacing\n\t\tlet serverOrigin = \"default\";\n\t\ttry {\n\t\t\tserverOrigin = new URL((client as any).baseUrl ?? \"\").hostname;\n\t\t} catch {}\n\n\t\tthis.persistence = new BackgroundSyncPersistence(serverOrigin);\n\t\tthis.semaphore = new Semaphore(this.opts.concurrency);\n\t}\n\n\t// ── Public API ────────────────────────────────────────────────────────────\n\n\t/** Sync all documents in the root tree. */\n\tasync syncAll(): Promise<void> {\n\t\tif (this._destroyed) return;\n\n\t\tconst treeMap = this.rootProvider.document.getMap(\"doc-tree\") as Y.Map<any>;\n\t\tconst entries = Array.from(treeMap.entries()) as Array<[string, any]>;\n\n\t\tif (entries.length === 0) return;\n\n\t\t// Pre-cache cover images immediately (fire-and-forget)\n\t\tthis._prefetchCovers(entries).catch(() => null);\n\n\t\t// Build the priority queue\n\t\tconst queue = this._buildQueue(entries);\n\n\t\t// Sync all docs respecting concurrency limit\n\t\tawait Promise.all(queue.map((docId) => this._syncWithSemaphore(docId)));\n\t}\n\n\t/** Sync a single document by ID. */\n\tasync syncDoc(docId: string): Promise<DocSyncState> {\n\t\tconst state = await this._doSyncDoc(docId);\n\t\tthis.syncStates.set(docId, state);\n\t\tawait this.persistence.setState(state).catch(() => null);\n\t\tthis.emit(\"stateChanged\", { docId, state });\n\t\treturn state;\n\t}\n\n\t/** Return a snapshot of all known sync states. */\n\tgetSyncStatus(): Map<string, DocSyncState> {\n\t\treturn new Map(this.syncStates);\n\t}\n\n\t/**\n\t * Start periodic background sync.\n\t * @param intervalMs Interval between sync runs. Default: 5 minutes.\n\t * @returns Cleanup function to stop the periodic sync.\n\t */\n\tstartPeriodicSync(intervalMs = 5 * 60 * 1000): () => void {\n\t\tconst handle = setInterval(() => {\n\t\t\tif (!this._destroyed) {\n\t\t\t\tthis.syncAll().catch(() => null);\n\t\t\t}\n\t\t}, intervalMs);\n\t\treturn () => clearInterval(handle);\n\t}\n\n\tdestroy(): void {\n\t\tthis._destroyed = true;\n\t\tthis.removeAllListeners();\n\t}\n\n\t// ── Internal ──────────────────────────────────────────────────────────────\n\n\t/**\n\t * Build a priority-sorted list of doc IDs:\n\t * 1. Never-synced docs first (lastSynced === null, status !== \"error\")\n\t * 2. Synced docs sorted by updatedAt desc (most-recently-edited first)\n\t * 3. Errored docs last\n\t */\n\tprivate _buildQueue(entries: Array<[string, any]>): string[] {\n\t\ttype Sortable = { docId: string; priority: number };\n\n\t\tconst items: Sortable[] = entries.map(([docId, v]) => {\n\t\t\tconst state = this.syncStates.get(docId);\n\t\t\tconst updatedAt: number = v?.updatedAt ?? v?.createdAt ?? 0;\n\n\t\t\tlet priority: number;\n\t\t\tif (!state || state.status === \"pending\") {\n\t\t\t\t// Never synced — high priority (large number so it sorts first when DESC)\n\t\t\t\tpriority = Number.MAX_SAFE_INTEGER - updatedAt;\n\t\t\t} else if (state.status === \"error\") {\n\t\t\t\t// Errored — lowest priority (large negative offset)\n\t\t\t\tpriority = -1;\n\t\t\t} else {\n\t\t\t\t// Synced — sort by updatedAt desc (most recent = highest priority)\n\t\t\t\tpriority = updatedAt;\n\t\t\t}\n\t\t\treturn { docId, priority };\n\t\t});\n\n\t\t// Sort descending by priority\n\t\titems.sort((a, b) => b.priority - a.priority);\n\t\treturn items.map((i) => i.docId);\n\t}\n\n\tprivate async _syncWithSemaphore(docId: string): Promise<void> {\n\t\tif (this._destroyed) return;\n\t\tawait this.semaphore.acquire();\n\t\ttry {\n\t\t\tconst state = await this._doSyncDoc(docId);\n\t\t\tthis.syncStates.set(docId, state);\n\t\t\tawait this.persistence.setState(state).catch(() => null);\n\t\t\tthis.emit(\"stateChanged\", { docId, state });\n\t\t} finally {\n\t\t\tthis.semaphore.release();\n\t\t}\n\t}\n\n\tprivate async _doSyncDoc(docId: string): Promise<DocSyncState> {\n\t\t// Mark as syncing\n\t\tconst syncing: DocSyncState = {\n\t\t\tdocId,\n\t\t\tstatus: \"syncing\",\n\t\t\tlastSynced: this.syncStates.get(docId)?.lastSynced ?? null,\n\t\t\tisE2E: false,\n\t\t};\n\t\tthis.syncStates.set(docId, syncing);\n\t\tthis.emit(\"stateChanged\", { docId, state: syncing });\n\n\t\ttry {\n\t\t\t// Check encryption type\n\t\t\tlet isE2E = false;\n\t\t\ttry {\n\t\t\t\tconst enc = await this.client.getDocEncryption(docId);\n\t\t\t\tisE2E = enc.mode === \"e2e\";\n\t\t\t} catch {\n\t\t\t\t// If we can't check, treat as non-E2E\n\t\t\t}\n\n\t\t\tif (isE2E) {\n\t\t\t\treturn await this._syncE2EDoc(docId);\n\t\t\t} else {\n\t\t\t\treturn await this._syncNonE2EDoc(docId);\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tconst error = err instanceof Error ? err.message : String(err);\n\t\t\treturn {\n\t\t\t\tdocId,\n\t\t\t\tstatus: \"error\",\n\t\t\t\tlastSynced: this.syncStates.get(docId)?.lastSynced ?? null,\n\t\t\t\terror,\n\t\t\t\tisE2E: false,\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate async _syncNonE2EDoc(docId: string): Promise<DocSyncState> {\n\t\t// loadChild() returns cached provider if already open\n\t\tconst childProvider = await this.rootProvider.loadChild(docId);\n\n\t\t// Wait for ready (offline snapshot loaded) then synced (server sync done)\n\t\tawait childProvider.ready;\n\t\tawait this._waitForSynced(childProvider);\n\n\t\t// Prefetch file blobs\n\t\tif (this.opts.prefetchFiles && this.fileBlobStore) {\n\t\t\tthis._prefetchDocFiles(docId, childProvider.document).catch(() => null);\n\t\t}\n\n\t\treturn { docId, status: \"synced\", lastSynced: Date.now(), isE2E: false };\n\t}\n\n\tprivate async _syncE2EDoc(docId: string): Promise<DocSyncState> {\n\t\t// Attempt E2E sync only when docKeyManager and keystore are available\n\t\tconst docKeyManager = (this.rootProvider as any).abracadabraConfig\n\t\t\t?.docKeyManager;\n\t\tconst keystore = (this.rootProvider as any).abracadabraConfig?.keystore;\n\n\t\tif (!docKeyManager || !keystore) {\n\t\t\t// No key management configured — skip silently\n\t\t\treturn { docId, status: \"skipped\", lastSynced: null, isE2E: true };\n\t\t}\n\n\t\tconst childDoc = new Y.Doc({ guid: docId });\n\t\tconst childProvider = new E2EAbracadabraProvider({\n\t\t\tname: docId,\n\t\t\tdocument: childDoc,\n\t\t\tclient: this.client,\n\t\t\tdocKeyManager,\n\t\t\tkeystore,\n\t\t});\n\n\t\ttry {\n\t\t\tawait childProvider.ready;\n\t\t\tawait this._waitForSynced(childProvider);\n\n\t\t\tif (this.opts.prefetchFiles && this.fileBlobStore) {\n\t\t\t\tthis._prefetchDocFiles(docId, childDoc).catch(() => null);\n\t\t\t}\n\n\t\t\treturn { docId, status: \"synced\", lastSynced: Date.now(), isE2E: true };\n\t\t} finally {\n\t\t\tchildProvider.destroy();\n\t\t}\n\t}\n\n\t/**\n\t * Wait for a provider to emit the \"synced\" event (with state=true),\n\t * timing out after opts.syncTimeout ms.\n\t */\n\tprivate _waitForSynced(provider: any): Promise<void> {\n\t\t// If already synced, resolve immediately\n\t\tif (provider.synced === true) return Promise.resolve();\n\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tprovider.off(\"synced\", onSynced);\n\t\t\t\treject(new Error(`Sync timeout after ${this.opts.syncTimeout}ms`));\n\t\t\t}, this.opts.syncTimeout);\n\n\t\t\tfunction onSynced(state: boolean | { state: boolean }) {\n\t\t\t\t// Hocuspocus passes `{ state }` or a boolean directly\n\t\t\t\tconst synced =\n\t\t\t\t\ttypeof state === \"boolean\" ? state : (state as any)?.state ?? state;\n\t\t\t\tif (synced) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tprovider.off(\"synced\", onSynced);\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprovider.on(\"synced\", onSynced);\n\t\t});\n\t}\n\n\t/**\n\t * Pre-cache all cover images referenced in the root tree map.\n\t */\n\tprivate async _prefetchCovers(entries: Array<[string, any]>): Promise<void> {\n\t\tif (!this.fileBlobStore) return;\n\t\tfor (const [docId, v] of entries) {\n\t\t\tconst coverUploadId = v?.meta?.coverUploadId;\n\t\t\tif (coverUploadId) {\n\t\t\t\tthis.fileBlobStore.getBlobUrl(docId, coverUploadId).catch(() => null);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Pre-cache file blobs referenced in a synced Y.Doc.\n\t * Walks:\n\t * - ydoc.getXmlFragment('default') for `fileBlock` nodes (TipTap)\n\t * - ydoc.getMap('doc-tree') for meta.coverUploadId entries\n\t */\n\tprivate async _prefetchDocFiles(\n\t\tdocId: string,\n\t\tydoc: Y.Doc,\n\t): Promise<void> {\n\t\tif (!this.fileBlobStore) return;\n\n\t\tconst refs = this._extractFileRefs(ydoc);\n\t\tfor (const { refDocId, uploadId } of refs) {\n\t\t\tthis.fileBlobStore\n\t\t\t\t.getBlobUrl(refDocId ?? docId, uploadId)\n\t\t\t\t.catch(() => null);\n\t\t}\n\t}\n\n\tprivate _extractFileRefs(\n\t\tydoc: Y.Doc,\n\t): Array<{ refDocId: string | null; uploadId: string }> {\n\t\tconst refs: Array<{ refDocId: string | null; uploadId: string }> = [];\n\n\t\t// Walk XML fragment for fileBlock nodes\n\t\ttry {\n\t\t\tconst fragment = ydoc.getXmlFragment(\"default\");\n\t\t\tthis._walkXml(fragment, refs);\n\t\t} catch {}\n\n\t\t// Walk doc-tree meta for cover upload IDs\n\t\ttry {\n\t\t\tconst treeMap = ydoc.getMap(\"doc-tree\") as Y.Map<any>;\n\t\t\tfor (const [id, v] of treeMap.entries()) {\n\t\t\t\tconst coverUploadId = v?.meta?.coverUploadId;\n\t\t\t\tif (coverUploadId) {\n\t\t\t\t\trefs.push({ refDocId: id, uploadId: coverUploadId });\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {}\n\n\t\treturn refs;\n\t}\n\n\tprivate _walkXml(\n\t\tnode: Y.XmlFragment | Y.XmlElement,\n\t\trefs: Array<{ refDocId: string | null; uploadId: string }>,\n\t): void {\n\t\tfor (const child of node.toArray()) {\n\t\t\tif (child instanceof Y.XmlElement) {\n\t\t\t\tif (child.nodeName === \"fileBlock\") {\n\t\t\t\t\tconst uploadId = child.getAttribute(\"uploadId\");\n\t\t\t\t\tconst refDocId = child.getAttribute(\"docId\") ?? null;\n\t\t\t\t\tif (uploadId) refs.push({ refDocId, uploadId });\n\t\t\t\t}\n\t\t\t\tthis._walkXml(child, refs);\n\t\t\t}\n\t\t}\n\t}\n}\n"],"x_google_ignoreList":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,19,20,21,22,23,24,25,26,32,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,MAAa,0BACZ,WACI;AACJ,QAAO,MAAM,KAAK,OAAO,SAAS,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW;AACzD,SAAO;GACN,UAAU;GACV,GAAG;GACH;GACA;;;;;;;;;;ACFH,MAAaA,UAAQ,KAAK;;;;;;;AAwB1B,MAAaC,SAAO,GAAG,MAAM,IAAI,IAAI,IAAI;;;;;;;AAQzC,MAAaC,SAAO,GAAG,MAAM,IAAI,IAAI,IAAI;AAEzC,MAAaC,UAAQ,OAAO;;;;ACpB5B,MAAaC,SAAO;AAUpB,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAC1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BAAgB,GAAG,MAAM;AAC/B,QAAI,cACH,MAAK,KAAK;KAAE,UAAU;KAAI,UAAU;KAAe,CAAC;;UAG/C;AAER,SAAO;;CAGR,AAAQ,SACP,MACA,MACO;AACP,OAAK,MAAM,SAAS,KAAK,SAAS,CACjC,KAAI,iBAAiBA,IAAE,YAAY;AAClC,OAAI,MAAM,aAAa,aAAa;IACnC,MAAM,WAAW,MAAM,aAAa,WAAW;IAC/C,MAAM,WAAW,MAAM,aAAa,QAAQ,IAAI;AAChD,QAAI,SAAU,MAAK,KAAK;KAAE;KAAU;KAAU,CAAC;;AAEhD,QAAK,SAAS,OAAO,KAAK"}
|
|
1
|
+
{"version":3,"file":"abracadabra-provider.cjs","names":["floor","min","max","isNaN","BIT8","BIT18","BIT19","BIT20","BIT21","BIT22","BIT23","BIT24","BIT25","BIT26","BIT27","BIT28","BIT29","BIT30","BIT31","BIT32","BITS7","BITS17","BITS18","BITS19","BITS20","BITS21","BITS22","BITS23","BITS24","BITS25","BITS26","BITS27","BITS28","BITS29","BITS30","BITS31","BITS32","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","LOWEST_INT32","HIGHEST_INT32","binary.BITS31","HIGHEST_UINT32","binary.BITS32","isInteger","math.floor","isNaN","parseInt","create","isArray","fromCharCode","fromCodePoint","MAX_UTF16_CHARACTER","_encodeUtf8Polyfill","utf8TextEncoder","_encodeUtf8Native","encodeUtf8","utf8TextDecoder","Encoder","createEncoder","length","toUint8Array","write","writeVarUint","binary.BITS7","binary.BIT8","math.floor","_strBuffer","_maxStrBSize","_writeVarStringNative","string.encodeUtf8","_writeVarStringPolyfill","writeVarString","string.utf8TextEncoder","writeUint8Array","math.min","math.max","writeVarUint8Array","create","errorUnexpectedEndOfArray","error.create","errorIntegerOutOfRange","Decoder","createDecoder","readUint8Array","readVarUint8Array","readVarUint","readUint8","binary.BITS7","binary.BIT8","number.MAX_SAFE_INTEGER","_readVarStringPolyfill","_readVarStringNative","readVarString","string.utf8TextDecoder","getUnixTime","create","map.create","set.create","array.from","equalityTrait.EqualityTraitSymbol","object.size","object.hasProperty","array.isArray","time.getUnixTime","math.floor","f.equalityDeep","encoding.createEncoder","encoding.toUint8Array","decoding.createDecoder","decoding.readVarUint","decoding.readVarString","isNaN","binary.BITS31","binary.BITS32","math.floor","parseInt","binary.BITS7","binary.BIT8","math.floor","string.encodeUtf8","string.utf8TextEncoder","math.min","math.max","error.create","binary.BITS7","binary.BIT8","number.MAX_SAFE_INTEGER","binary.BITS6","binary.BIT7","string.utf8TextDecoder","time.getUnixTime","decoding.readVarUint","decoding.readVarString","Y","decoding.readVarUint8Array","decoding.readVarUint","awarenessProtocol.encodeAwarenessUpdate","Y","DB_VERSION","idbAvailable","openDb","txPromise","Y","fromBase64","isBytes","anumber","abytes","aexists","aoutput","clean","createView","isLE","hasHexBuiltin","createHasher","HashMD","createView","U32_MASK64","_32n","fromBig","split","HashMD","K512","u64.split","SHA512_Kh","SHA512_Kl","sha256","sha256n","createHasher","u64.split","u64.rotrSH","u64.shrSH","u64.rotrSL","u64.shrSL","u64.rotrBH","u64.rotrBL","u64.add4L","u64.add4H","u64.add5L","u64.add5H","u64.add","u64.add3L","u64.add3H","_0n","_1n","bytesToHex_","abytes_","hexToBytes_","_0n","_1n","_2n","_3n","_5n","_8n","_0n","_1n","_0n","_1n","_2n","_8n","randomBytes","wcRandomBytes","_0n","_1n","_2n","HKDF_INFO","openDb","ed","nobleEd25519Curves","DB_VERSION","idbAvailable","openDb","txPromise","DB_VERSION","idbAvailable","openDb","DB_VERSION","idbAvailable","openDb","fromBase64","Y","Y"],"sources":["../src/awarenessStatesToArray.ts","../../../node_modules/lib0/math.js","../../../node_modules/lib0/binary.js","../../../node_modules/lib0/number.js","../../../node_modules/lib0/set.js","../../../node_modules/lib0/array.js","../../../node_modules/lib0/string.js","../../../node_modules/lib0/encoding.js","../../../node_modules/lib0/error.js","../../../node_modules/lib0/decoding.js","../../../node_modules/lib0/time.js","../../../node_modules/lib0/map.js","../../../node_modules/lib0/observable.js","../../../node_modules/lib0/trait/equality.js","../../../node_modules/lib0/object.js","../../../node_modules/lib0/function.js","../../../node_modules/y-protocols/awareness.js","../src/EventEmitter.ts","../src/types.ts","../node_modules/lib0/math.js","../node_modules/lib0/time.js","../node_modules/lib0/binary.js","../node_modules/lib0/number.js","../node_modules/lib0/string.js","../node_modules/lib0/error.js","../node_modules/lib0/encoding.js","../node_modules/lib0/decoding.js","../src/IncomingMessage.ts","../src/OutgoingMessage.ts","../src/OutgoingMessages/CloseMessage.ts","../src/AbracadabraWS.ts","../src/auth.ts","../../../node_modules/y-protocols/sync.js","../src/MessageReceiver.ts","../src/MessageSender.ts","../src/OutgoingMessages/AuthenticationMessage.ts","../src/OutgoingMessages/AwarenessMessage.ts","../src/OutgoingMessages/StatelessMessage.ts","../src/OutgoingMessages/SyncStepOneMessage.ts","../src/OutgoingMessages/UpdateMessage.ts","../src/AbracadabraBaseProvider.ts","../src/OfflineStore.ts","../src/OutgoingMessages/SubdocMessage.ts","../src/AbracadabraProvider.ts","../src/AbracadabraClient.ts","../src/CloseEvents.ts","../node_modules/@noble/hashes/esm/utils.js","../node_modules/@noble/hashes/esm/hmac.js","../node_modules/@noble/hashes/esm/hkdf.js","../node_modules/@noble/hashes/esm/_md.js","../node_modules/@noble/hashes/esm/_u64.js","../node_modules/@noble/hashes/esm/sha2.js","../node_modules/@noble/hashes/esm/sha256.js","../node_modules/@noble/curves/node_modules/@noble/hashes/utils.js","../node_modules/@noble/curves/node_modules/@noble/hashes/_md.js","../node_modules/@noble/curves/node_modules/@noble/hashes/_u64.js","../node_modules/@noble/curves/node_modules/@noble/hashes/sha2.js","../node_modules/@noble/curves/utils.js","../node_modules/@noble/curves/abstract/modular.js","../node_modules/@noble/curves/abstract/curve.js","../node_modules/@noble/curves/abstract/edwards.js","../node_modules/@noble/curves/abstract/hash-to-curve.js","../node_modules/@noble/curves/abstract/montgomery.js","../node_modules/@noble/curves/abstract/oprf.js","../node_modules/@noble/curves/ed25519.js","../src/CryptoIdentityKeystore.ts","../src/DocumentCache.ts","../src/SearchIndex.ts","../src/FileBlobStore.ts","../src/DocKeyManager.ts","../src/EncryptedY.ts","../src/E2EOfflineStore.ts","../src/E2EAbracadabraProvider.ts","../src/TreeTimestamps.ts","../src/BackgroundSyncPersistence.ts","../src/BackgroundSyncManager.ts"],"sourcesContent":["export const awarenessStatesToArray = (\n\tstates: Map<number, Record<string, any>>,\n) => {\n\treturn Array.from(states.entries()).map(([key, value]) => {\n\t\treturn {\n\t\t\tclientId: key,\n\t\t\t...value,\n\t\t};\n\t});\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 * Check whether n is negative, while considering the -0 edge case. While `-0 < 0` is false, this\n * function returns true for -0,-1,,.. and returns false for 0,1,2,...\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also distinguishes between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\nexport const HIGHEST_INT32 = binary.BITS31\nexport const HIGHEST_UINT32 = binary.BITS32\n\n/* c8 ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n\n/**\n * Count the number of \"1\" bits in an unsigned 32bit number.\n *\n * Super fun bitcount algorithm by Brian Kernighan.\n *\n * @param {number} n\n */\nexport const countBits = n => {\n n &= binary.BITS32\n let count = 0\n while (n) {\n n &= (n - 1)\n count++\n }\n return count\n}\n","/**\n * Utility module to work with sets.\n *\n * @module set\n */\n\nexport const create = () => new Set()\n\n/**\n * @template T\n * @param {Set<T>} set\n * @return {Array<T>}\n */\nexport const toArray = set => Array.from(set)\n\n/**\n * @template T\n * @param {Set<T>} set\n * @return {T|undefined}\n */\nexport const first = set => set.values().next().value\n\n/**\n * @template T\n * @param {Iterable<T>} entries\n * @return {Set<T>}\n */\nexport const from = entries => new Set(entries)\n","/**\n * Utility module to work with Arrays.\n *\n * @module array\n */\n\nimport * as set from './set.js'\n\n/**\n * Return the last element of an array. The element must exist\n *\n * @template L\n * @param {ArrayLike<L>} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array<C>}\n */\nexport const create = () => /** @type {Array<C>} */ ([])\n\n/**\n * @template D\n * @param {Array<D>} a\n * @return {Array<D>}\n */\nexport const copy = a => /** @type {Array<D>} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array<M>} dest\n * @param {Array<M>} src\n */\nexport const appendTo = (dest, src) => {\n for (let i = 0; i < src.length; i++) {\n dest.push(src[i])\n }\n}\n\n/**\n * Transforms something array-like to an actual Array.\n *\n * @function\n * @template T\n * @param {ArrayLike<T>|Iterable<T>} arraylike\n * @return {T}\n */\nexport const from = Array.from\n\n/**\n * True iff condition holds on every element in the Array.\n *\n * @function\n * @template {ArrayLike<any>} ARR\n *\n * @param {ARR} arr\n * @param {ARR extends ArrayLike<infer S> ? ((value:S, index:number, arr:ARR) => boolean) : any} f\n * @return {boolean}\n */\nexport const every = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (!f(arr[i], i, arr)) {\n return false\n }\n }\n return true\n}\n\n/**\n * True iff condition holds on some element in the Array.\n *\n * @function\n * @template {ArrayLike<any>} ARR\n *\n * @param {ARR} arr\n * @param {ARR extends ArrayLike<infer S> ? ((value:S, index:number, arr:ARR) => boolean) : never} f\n * @return {boolean}\n */\nexport const some = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (f(arr[i], i, arr)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @template ELEM\n *\n * @param {ArrayLike<ELEM>} a\n * @param {ArrayLike<ELEM>} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a.length === b.length && every(a, (item, index) => item === b[index])\n\n/**\n * @template ELEM\n * @param {Array<Array<ELEM>>} arr\n * @return {Array<ELEM>}\n */\nexport const flatten = arr => fold(arr, /** @type {Array<ELEM>} */ ([]), (acc, val) => acc.concat(val))\n\n/**\n * @template T\n * @param {number} len\n * @param {function(number, Array<T>):T} f\n * @return {Array<T>}\n */\nexport const unfold = (len, f) => {\n const array = new Array(len)\n for (let i = 0; i < len; i++) {\n array[i] = f(i, array)\n }\n return array\n}\n\n/**\n * @template T\n * @template RESULT\n * @param {Array<T>} arr\n * @param {RESULT} seed\n * @param {function(RESULT, T, number):RESULT} folder\n */\nexport const fold = (arr, seed, folder) => arr.reduce(folder, seed)\n\nexport const isArray = Array.isArray\n\n/**\n * @template T\n * @param {Array<T>} arr\n * @return {Array<T>}\n */\nexport const unique = arr => from(set.from(arr))\n\n/**\n * @template T\n * @template M\n * @param {ArrayLike<T>} arr\n * @param {function(T):M} mapper\n * @return {Array<T>}\n */\nexport const uniqueBy = (arr, mapper) => {\n /**\n * @type {Set<M>}\n */\n const happened = set.create()\n /**\n * @type {Array<T>}\n */\n const result = []\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i]\n const mapped = mapper(el)\n if (!happened.has(mapped)) {\n happened.add(mapped)\n result.push(el)\n }\n }\n return result\n}\n\n/**\n * @template {ArrayLike<any>} ARR\n * @template {function(ARR extends ArrayLike<infer T> ? T : never, number, ARR):any} MAPPER\n * @param {ARR} arr\n * @param {MAPPER} mapper\n * @return {Array<MAPPER extends function(...any): infer M ? M : never>}\n */\nexport const map = (arr, mapper) => {\n /**\n * @type {Array<any>}\n */\n const res = Array(arr.length)\n for (let i = 0; i < arr.length; i++) {\n res[i] = mapper(/** @type {any} */ (arr[i]), i, /** @type {any} */ (arr))\n }\n return /** @type {any} */ (res)\n}\n\n/**\n * This function bubble-sorts a single item to the correct position. The sort happens in-place and\n * might be useful to ensure that a single item is at the correct position in an otherwise sorted\n * array.\n *\n * @example\n * const arr = [3, 2, 5]\n * arr.sort((a, b) => a - b)\n * arr // => [2, 3, 5]\n * arr.splice(1, 0, 7)\n * array.bubbleSortItem(arr, 1, (a, b) => a - b)\n * arr // => [2, 3, 5, 7]\n *\n * @template T\n * @param {Array<T>} arr\n * @param {number} i\n * @param {(a:T,b:T) => number} compareFn\n */\nexport const bubblesortItem = (arr, i, compareFn) => {\n const n = arr[i]\n let j = i\n // try to sort to the right\n while (j + 1 < arr.length && compareFn(n, arr[j + 1]) > 0) {\n arr[j] = arr[j + 1]\n arr[++j] = n\n }\n if (i === j && j > 0) { // no change yet\n // sort to the left\n while (j > 0 && compareFn(arr[j - 1], n) > 0) {\n arr[j] = arr[j - 1]\n arr[--j] = n\n }\n }\n return j\n}\n","import * as array from './array.js'\n\n/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * The largest utf16 character.\n * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8)\n */\nexport const MAX_UTF16_CHARACTER = fromCharCode(65535)\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array<ArrayBuffer>}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* c8 ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array<ArrayBuffer>}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* c8 ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* c8 ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* c8 ignore start */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* c8 ignore next */\n utf8TextDecoder = null\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* c8 ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n\n/**\n * @param {string} source\n * @param {number} n\n */\nexport const repeat = (source, n) => array.unfold(n, () => source).join('')\n\n/**\n * Escape HTML characters &,<,>,',\" to their respective HTML entities &,<,>,',"\n *\n * @param {string} str\n */\nexport const escapeHTML = str =>\n str.replace(/[&<>'\"]/g, r => /** @type {string} */ ({\n '&': '&',\n '<': '<',\n '>': '>',\n \"'\": ''',\n '\"': '"'\n }[r]))\n\n/**\n * Reverse of `escapeHTML`\n *\n * @param {string} str\n */\nexport const unescapeHTML = str =>\n str.replace(/&|<|>|'|"/g, r => /** @type {string} */ ({\n '&': '&',\n '<': '<',\n '>': '>',\n ''': \"'\",\n '"': '\"'\n }[r]))\n","/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\nimport * as string from './string.js'\nimport * as array from './array.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array<Uint8Array>}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * @param {function(Encoder):void} f\n */\nexport const encode = (f) => {\n const encoder = createEncoder()\n f(encoder)\n return toUint8Array(encoder)\n}\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Check whether encoder is empty.\n *\n * @function\n * @param {Encoder} encoder\n * @return {boolean}\n */\nexport const hasContent = encoder => encoder.cpos > 0 || encoder.bufs.length > 0\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array<ArrayBuffer>} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nexport const verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer. Max encodable integer is 2^53.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num = math.floor(num / 64) // shift >>> 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n}\n\n/**\n * A cache to store strings temporarily\n */\nconst _strBuffer = new Uint8Array(30000)\nconst _maxStrBSize = _strBuffer.length / 3\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringNative = (encoder, str) => {\n if (str.length < _maxStrBSize) {\n // We can encode the string into the existing buffer\n /* c8 ignore next */\n const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0\n writeVarUint(encoder, written)\n for (let i = 0; i < written; i++) {\n write(encoder, _strBuffer[i])\n }\n } else {\n writeVarUint8Array(encoder, string.encodeUtf8(str))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringPolyfill = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\n/* c8 ignore next */\nexport const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill\n\n/**\n * Write a string terminated by a special byte sequence. This is not very performant and is\n * generally discouraged. However, the resulting byte arrays are lexiographically ordered which\n * makes this a nice feature for databases.\n *\n * The string will be encoded using utf8 and then terminated and escaped using writeTerminatingUint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const writeTerminatedString = (encoder, str) =>\n writeTerminatedUint8Array(encoder, string.encodeUtf8(str))\n\n/**\n * Write a terminating Uint8Array. Note that this is not performant and is generally\n * discouraged. There are few situations when this is needed.\n *\n * We use 0x0 as a terminating character. 0x1 serves as an escape character for 0x0 and 0x1.\n *\n * Example: [0,1,2] is encoded to [1,0,1,1,2,0]. 0x0, and 0x1 needed to be escaped using 0x1. Then\n * the result is terminated using the 0x0 character.\n *\n * This is basically how many systems implement null terminated strings. However, we use an escape\n * character 0x1 to avoid issues and potenial attacks on our database (if this is used as a key\n * encoder for NoSql databases).\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} buf The string that is to be encoded.\n */\nexport const writeTerminatedUint8Array = (encoder, buf) => {\n for (let i = 0; i < buf.length; i++) {\n const b = buf[i]\n if (b === 0 || b === 1) {\n write(encoder, 1)\n }\n write(encoder, buf[i])\n }\n write(encoder, 0)\n}\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * @typedef {Array<AnyEncodable>} AnyEncodableArray\n */\n\n/**\n * @typedef {undefined|null|number|bigint|boolean|string|{[k:string]:AnyEncodable}|AnyEncodableArray|Uint8Array} AnyEncodable\n */\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object<string,any> | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array<any> | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {AnyEncodable} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && math.abs(data) <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (array.isArray(data)) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array<string>}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n","/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* c8 ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n\n/**\n * @param {boolean} property\n * @return {asserts property is true}\n */\nexport const assert = property => { if (!property) throw create('Assert failed') }\n","/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as binary from './binary.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as string from './string.js'\nimport * as error from './error.js'\nimport * as encoding from './encoding.js'\n\nconst errorUnexpectedEndOfArray = error.create('Unexpected end of array')\nconst errorIntegerOutOfRange = error.create('Integer out of Range')\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n * @template {ArrayBufferLike} [Buf=ArrayBufferLike]\n */\nexport class Decoder {\n /**\n * @param {Uint8Array<Buf>} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array<Buf>}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Uint8Array<Buf>} uint8Array\n * @return {Decoder<Buf>}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Decoder<Buf>} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array<Buf>}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Decoder<Buf>} decoder\n * @return {Uint8Array<Buf>}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let mult = 1\n const len = decoder.arr.length\n while (decoder.pos < len) {\n const r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num\n mult *= 128 // next iteration, shift 7 \"more\" to the left\n if (r < binary.BIT8) {\n return num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let mult = 64\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n const len = decoder.arr.length\n while (decoder.pos < len) {\n r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult\n mult *= 128\n if (r < binary.BIT8) {\n return sign * num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * We don't test this function anymore as we use native decoding/encoding by default now.\n * Better not modify this anymore..\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\n/* c8 ignore start */\nexport const _readVarStringPolyfill = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n/* c8 ignore stop */\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n */\nexport const _readVarStringNative = decoder =>\n /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder))\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n *\n */\n/* c8 ignore next */\nexport const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill\n\n/**\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTerminatedUint8Array = decoder => {\n const encoder = encoding.createEncoder()\n let b\n while (true) {\n b = readUint8(decoder)\n if (b === 0) {\n return encoding.toUint8Array(encoder)\n }\n if (b === 1) {\n b = readUint8(decoder)\n }\n encoding.write(encoder, b)\n }\n}\n\n/**\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const readTerminatedString = decoder => string.decodeUtf8(readTerminatedUint8Array(decoder))\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array<function(Decoder):any>}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object<string,any>\n const len = readVarUint(decoder)\n /**\n * @type {Object<string,any>}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array<any>\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = math.floor(diff / 2) // shift >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n","/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* c8 ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n","/**\n * Utility module to work with key-value stores.\n *\n * @module map\n */\n\n/**\n * @template K\n * @template V\n * @typedef {Map<K,V>} GlobalMap\n */\n\n/**\n * Creates a new Map instance.\n *\n * @function\n * @return {Map<any, any>}\n *\n * @function\n */\nexport const create = () => new Map()\n\n/**\n * Copy a Map object into a fresh Map object.\n *\n * @function\n * @template K,V\n * @param {Map<K,V>} m\n * @return {Map<K,V>}\n */\nexport const copy = m => {\n const r = create()\n m.forEach((v, k) => { r.set(k, v) })\n return r\n}\n\n/**\n * Get map property. Create T if property is undefined and set T on map.\n *\n * ```js\n * const listeners = map.setIfUndefined(events, 'eventName', set.create)\n * listeners.add(listener)\n * ```\n *\n * @function\n * @template {Map<any, any>} MAP\n * @template {MAP extends Map<any,infer V> ? function():V : unknown} CF\n * @param {MAP} map\n * @param {MAP extends Map<infer K,any> ? K : unknown} key\n * @param {CF} createT\n * @return {ReturnType<CF>}\n */\nexport const setIfUndefined = (map, key, createT) => {\n let set = map.get(key)\n if (set === undefined) {\n map.set(key, set = createT())\n }\n return set\n}\n\n/**\n * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function.\n *\n * @function\n * @template K\n * @template V\n * @template R\n * @param {Map<K,V>} m\n * @param {function(V,K):R} f\n * @return {Array<R>}\n */\nexport const map = (m, f) => {\n const res = []\n for (const [key, value] of m) {\n res.push(f(value, key))\n }\n return res\n}\n\n/**\n * Tests whether any key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @todo should rename to some - similarly to Array.some\n *\n * @function\n * @template K\n * @template V\n * @param {Map<K,V>} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const any = (m, f) => {\n for (const [key, value] of m) {\n if (f(value, key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * Tests whether all key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @function\n * @template K\n * @template V\n * @param {Map<K,V>} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const all = (m, f) => {\n for (const [key, value] of m) {\n if (!f(value, key)) {\n return false\n }\n }\n return true\n}\n","/**\n * Observable class prototype.\n *\n * @module observable\n */\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as array from './array.js'\n\n/**\n * Handles named events.\n * @experimental\n *\n * This is basically a (better typed) duplicate of Observable, which will replace Observable in the\n * next release.\n *\n * @template {{[key in keyof EVENTS]: function(...any):void}} EVENTS\n */\nexport class ObservableV2 {\n constructor () {\n /**\n * Some desc.\n * @type {Map<string, Set<any>>}\n */\n this._observers = map.create()\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, /** @type {string} */ (name), set.create).add(f)\n return f\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, /** @type {any} */ (_f))\n f(...args)\n }\n this.on(name, /** @type {any} */ (_f))\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name The event name.\n * @param {Parameters<EVENTS[NAME]>} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n\n/* c8 ignore start */\n/**\n * Handles named events.\n *\n * @deprecated\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map<N, any>}\n */\n this._observers = map.create()\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, name, set.create).add(f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, _f)\n f(...args)\n }\n this.on(name, _f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @param {N} name The event name.\n * @param {Array<any>} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n/* c8 ignore end */\n","export const EqualityTraitSymbol = Symbol('Equality')\n\n/**\n * @typedef {{ [EqualityTraitSymbol]:(other:EqualityTrait)=>boolean }} EqualityTrait\n */\n\n/**\n *\n * Utility function to compare any two objects.\n *\n * Note that it is expected that the first parameter is more specific than the latter one.\n *\n * @example js\n * class X { [traits.EqualityTraitSymbol] (other) { return other === this } }\n * class X2 { [traits.EqualityTraitSymbol] (other) { return other === this }, x2 () { return 2 } }\n * // this is fine\n * traits.equals(new X2(), new X())\n * // this is not, because the left type is less specific than the right one\n * traits.equals(new X(), new X2())\n *\n * @template {EqualityTrait} T\n * @param {NoInfer<T>} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equals = (a, b) => a === b || !!a?.[EqualityTraitSymbol]?.(b) || false\n","import * as equalityTrait from './trait/equality.js'\n\n/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object<string,any>} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * @param {any} o\n * @return {o is { [k:string]:any }}\n */\nexport const isObject = o => typeof o === 'object'\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object<string,any>} obj\n */\nexport const keys = Object.keys\n\n/**\n * @template V\n * @param {{[key:string]: V}} obj\n * @return {Array<V>}\n */\nexport const values = Object.values\n\n/**\n * @template V\n * @param {{[k:string]:V}} obj\n * @param {function(V,string):any} f\n */\nexport const forEach = (obj, f) => {\n for (const key in obj) {\n f(obj[key], key)\n }\n}\n\n/**\n * @todo implement mapToArray & map\n *\n * @template R\n * @param {Object<string,any>} obj\n * @param {function(any,string):R} f\n * @return {Array<R>}\n */\nexport const map = (obj, f) => {\n const results = []\n for (const key in obj) {\n results.push(f(obj[key], key))\n }\n return results\n}\n\n/**\n * @deprecated use object.size instead\n * @param {Object<string,any>} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object<string,any>} obj\n * @return {number}\n */\nexport const size = obj => keys(obj).length\n\n/**\n * @template {{ [key:string|number|symbol]: any }} T\n * @param {T} obj\n * @param {(v:T[keyof T],k:keyof T)=>boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n for (const key in obj) {\n if (f(obj[key], key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {Object|null|undefined} obj\n */\nexport const isEmpty = obj => {\n // eslint-disable-next-line no-unreachable-loop\n for (const _k in obj) {\n return false\n }\n return true\n}\n\n/**\n * @template {{ [key:string|number|symbol]: any }} T\n * @param {T} obj\n * @param {(v:T[keyof T],k:keyof T)=>boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n for (const key in obj) {\n if (!f(obj[key], key)) {\n return false\n }\n }\n return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|number|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object<string,any>} a\n * @param {Object<string,any>} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (size(a) === size(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && equalityTrait.equals(b[key], val)))\n\n/**\n * Make an object immutable. This hurts performance and is usually not needed if you perform good\n * coding practices.\n */\nexport const freeze = Object.freeze\n\n/**\n * Make an object and all its children immutable.\n * This *really* hurts performance and is usually not needed if you perform good coding practices.\n *\n * @template {any} T\n * @param {T} o\n * @return {Readonly<T>}\n */\nexport const deepFreeze = (o) => {\n for (const key in o) {\n const c = o[key]\n if (typeof c === 'object' || typeof c === 'function') {\n deepFreeze(o[key])\n }\n }\n return freeze(o)\n}\n\n/**\n * Get object property. Create T if property is undefined and set T on object.\n *\n * @function\n * @template {object} KV\n * @template {keyof KV} [K=keyof KV]\n * @param {KV} o\n * @param {K} key\n * @param {() => KV[K]} createT\n * @return {KV[K]}\n */\nexport const setIfUndefined = (o, key, createT) => hasProperty(o, key) ? o[key] : (o[key] = createT())\n","/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\nimport * as equalityTrait from './trait/equality.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array<function>} fs\n * @param {Array<any>} args\n */\nexport const callAll = (fs, args, i = 0) => {\n try {\n for (; i < fs.length; i++) {\n fs[i](...args)\n }\n } finally {\n if (i < fs.length) {\n callAll(fs, args, i + 1)\n }\n }\n}\n\nexport const nop = () => {}\n\n/**\n * @template T\n * @param {function():T} f\n * @return {T}\n */\nexport const apply = f => f()\n\n/**\n * @template A\n *\n * @param {A} a\n * @return {A}\n */\nexport const id = a => a\n\n/**\n * @template T\n *\n * @param {T} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equalityStrict = (a, b) => a === b\n\n/**\n * @template T\n *\n * @param {Array<T>|object} a\n * @param {Array<T>|object} b\n * @return {boolean}\n */\nexport const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((array.isArray(a) && array.equalFlat(a, /** @type {Array<T>} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/* c8 ignore start */\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a === b) {\n return true\n }\n if (a == null || b == null || (a.constructor !== b.constructor && (a.constructor || Object) !== (b.constructor || Object))) {\n return false\n }\n if (a[equalityTrait.EqualityTraitSymbol] != null) {\n return a[equalityTrait.EqualityTraitSymbol](b)\n }\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n break\n }\n case Map: {\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n return false\n }\n }\n break\n }\n case undefined:\n case Object:\n if (object.size(a) !== object.size(b)) {\n return false\n }\n for (const key in a) {\n if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n return false\n }\n }\n break\n case Array:\n if (a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!equalityDeep(a[i], b[i])) {\n return false\n }\n }\n break\n default:\n return false\n }\n return true\n}\n\n/**\n * @template V\n * @template {V} OPTS\n *\n * @param {V} value\n * @param {Array<OPTS>} options\n */\n// @ts-ignore\nexport const isOneOf = (value, options) => options.includes(value)\n/* c8 ignore stop */\n\nexport const isArray = array.isArray\n\n/**\n * @param {any} s\n * @return {s is String}\n */\nexport const isString = (s) => s && s.constructor === String\n\n/**\n * @param {any} n\n * @return {n is Number}\n */\nexport const isNumber = n => n != null && n.constructor === Number\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {any} n\n * @param {TYPE} T\n * @return {n is InstanceType<TYPE>}\n */\nexport const is = (n, T) => n && n.constructor === T\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {TYPE} T\n */\nexport const isTemplate = (T) =>\n /**\n * @param {any} n\n * @return {n is InstanceType<TYPE>}\n **/\n n => n && n.constructor === T\n","/**\n * @module awareness-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as time from 'lib0/time'\nimport * as math from 'lib0/math'\nimport { Observable } from 'lib0/observable'\nimport * as f from 'lib0/function'\nimport * as Y from 'yjs' // eslint-disable-line\n\nexport const outdatedTimeout = 30000\n\n/**\n * @typedef {Object} MetaClientState\n * @property {number} MetaClientState.clock\n * @property {number} MetaClientState.lastUpdated unix timestamp\n */\n\n/**\n * The Awareness class implements a simple shared state protocol that can be used for non-persistent data like awareness information\n * (cursor, username, status, ..). Each client can update its own local state and listen to state changes of\n * remote clients. Every client may set a state of a remote peer to `null` to mark the client as offline.\n *\n * Each client is identified by a unique client id (something we borrow from `doc.clientID`). A client can override\n * its own state by propagating a message with an increasing timestamp (`clock`). If such a message is received, it is\n * applied if the known state of that client is older than the new state (`clock < newClock`). If a client thinks that\n * a remote client is offline, it may propagate a message with\n * `{ clock: currentClientClock, state: null, client: remoteClient }`. If such a\n * message is received, and the known clock of that client equals the received clock, it will override the state with `null`.\n *\n * Before a client disconnects, it should propagate a `null` state with an updated clock.\n *\n * Awareness states must be updated every 30 seconds. Otherwise the Awareness instance will delete the client state.\n *\n * @extends {Observable<string>}\n */\nexport class Awareness extends Observable {\n /**\n * @param {Y.Doc} doc\n */\n constructor (doc) {\n super()\n this.doc = doc\n /**\n * @type {number}\n */\n this.clientID = doc.clientID\n /**\n * Maps from client id to client state\n * @type {Map<number, Object<string, any>>}\n */\n this.states = new Map()\n /**\n * @type {Map<number, MetaClientState>}\n */\n this.meta = new Map()\n this._checkInterval = /** @type {any} */ (setInterval(() => {\n const now = time.getUnixTime()\n if (this.getLocalState() !== null && (outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ (this.meta.get(this.clientID)).lastUpdated)) {\n // renew local clock\n this.setLocalState(this.getLocalState())\n }\n /**\n * @type {Array<number>}\n */\n const remove = []\n this.meta.forEach((meta, clientid) => {\n if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) {\n remove.push(clientid)\n }\n })\n if (remove.length > 0) {\n removeAwarenessStates(this, remove, 'timeout')\n }\n }, math.floor(outdatedTimeout / 10)))\n doc.on('destroy', () => {\n this.destroy()\n })\n this.setLocalState({})\n }\n\n destroy () {\n this.emit('destroy', [this])\n this.setLocalState(null)\n super.destroy()\n clearInterval(this._checkInterval)\n }\n\n /**\n * @return {Object<string,any>|null}\n */\n getLocalState () {\n return this.states.get(this.clientID) || null\n }\n\n /**\n * @param {Object<string,any>|null} state\n */\n setLocalState (state) {\n const clientID = this.clientID\n const currLocalMeta = this.meta.get(clientID)\n const clock = currLocalMeta === undefined ? 0 : currLocalMeta.clock + 1\n const prevState = this.states.get(clientID)\n if (state === null) {\n this.states.delete(clientID)\n } else {\n this.states.set(clientID, state)\n }\n this.meta.set(clientID, {\n clock,\n lastUpdated: time.getUnixTime()\n })\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n if (state === null) {\n removed.push(clientID)\n } else if (prevState == null) {\n if (state != null) {\n added.push(clientID)\n }\n } else {\n updated.push(clientID)\n if (!f.equalityDeep(prevState, state)) {\n filteredUpdated.push(clientID)\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n this.emit('change', [{ added, updated: filteredUpdated, removed }, 'local'])\n }\n this.emit('update', [{ added, updated, removed }, 'local'])\n }\n\n /**\n * @param {string} field\n * @param {any} value\n */\n setLocalStateField (field, value) {\n const state = this.getLocalState()\n if (state !== null) {\n this.setLocalState({\n ...state,\n [field]: value\n })\n }\n }\n\n /**\n * @return {Map<number,Object<string,any>>}\n */\n getStates () {\n return this.states\n }\n}\n\n/**\n * Mark (remote) clients as inactive and remove them from the list of active peers.\n * This change will be propagated to remote clients.\n *\n * @param {Awareness} awareness\n * @param {Array<number>} clients\n * @param {any} origin\n */\nexport const removeAwarenessStates = (awareness, clients, origin) => {\n const removed = []\n for (let i = 0; i < clients.length; i++) {\n const clientID = clients[i]\n if (awareness.states.has(clientID)) {\n awareness.states.delete(clientID)\n if (clientID === awareness.clientID) {\n const curMeta = /** @type {MetaClientState} */ (awareness.meta.get(clientID))\n awareness.meta.set(clientID, {\n clock: curMeta.clock + 1,\n lastUpdated: time.getUnixTime()\n })\n }\n removed.push(clientID)\n }\n }\n if (removed.length > 0) {\n awareness.emit('change', [{ added: [], updated: [], removed }, origin])\n awareness.emit('update', [{ added: [], updated: [], removed }, origin])\n }\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Array<number>} clients\n * @return {Uint8Array}\n */\nexport const encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {\n const len = clients.length\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = clients[i]\n const state = states.get(clientID) || null\n const clock = /** @type {MetaClientState} */ (awareness.meta.get(clientID)).clock\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(state))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Modify the content of an awareness update before re-encoding it to an awareness update.\n *\n * This might be useful when you have a central server that wants to ensure that clients\n * cant hijack somebody elses identity.\n *\n * @param {Uint8Array} update\n * @param {function(any):any} modify\n * @return {Uint8Array}\n */\nexport const modifyAwarenessUpdate = (update, modify) => {\n const decoder = decoding.createDecoder(update)\n const encoder = encoding.createEncoder()\n const len = decoding.readVarUint(decoder)\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n const clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const modifiedState = modify(state)\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(modifiedState))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Uint8Array} update\n * @param {any} origin This will be added to the emitted change event\n */\nexport const applyAwarenessUpdate = (awareness, update, origin) => {\n const decoder = decoding.createDecoder(update)\n const timestamp = time.getUnixTime()\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n const len = decoding.readVarUint(decoder)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n let clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const clientMeta = awareness.meta.get(clientID)\n const prevState = awareness.states.get(clientID)\n const currClock = clientMeta === undefined ? 0 : clientMeta.clock\n if (currClock < clock || (currClock === clock && state === null && awareness.states.has(clientID))) {\n if (state === null) {\n // never let a remote client remove this local state\n if (clientID === awareness.clientID && awareness.getLocalState() != null) {\n // remote client removed the local state. Do not remote state. Broadcast a message indicating\n // that this client still exists by increasing the clock\n clock++\n } else {\n awareness.states.delete(clientID)\n }\n } else {\n awareness.states.set(clientID, state)\n }\n awareness.meta.set(clientID, {\n clock,\n lastUpdated: timestamp\n })\n if (clientMeta === undefined && state !== null) {\n added.push(clientID)\n } else if (clientMeta !== undefined && state === null) {\n removed.push(clientID)\n } else if (state !== null) {\n if (!f.equalityDeep(state, prevState)) {\n filteredUpdated.push(clientID)\n }\n updated.push(clientID)\n }\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n awareness.emit('change', [{\n added, updated: filteredUpdated, removed\n }, origin])\n }\n if (added.length > 0 || updated.length > 0 || removed.length > 0) {\n awareness.emit('update', [{\n added, updated, removed\n }, origin])\n }\n}\n","export default class EventEmitter {\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic callbacks: { [key: string]: Function[] } = {};\n\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic on(event: string, fn: Function): this {\n\t\tif (!this.callbacks[event]) {\n\t\t\tthis.callbacks[event] = [];\n\t\t}\n\n\t\tthis.callbacks[event].push(fn);\n\n\t\treturn this;\n\t}\n\n\tprotected emit(event: string, ...args: any): this {\n\t\tconst callbacks = this.callbacks[event];\n\n\t\tif (callbacks) {\n\t\t\tcallbacks.forEach((callback) => callback.apply(this, args));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic off(event: string, fn?: Function): this {\n\t\tconst callbacks = this.callbacks[event];\n\n\t\tif (callbacks) {\n\t\t\tif (fn) {\n\t\t\t\tthis.callbacks[event] = callbacks.filter((callback) => callback !== fn);\n\t\t\t} else {\n\t\t\t\tdelete this.callbacks[event];\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tremoveAllListeners(): void {\n\t\tthis.callbacks = {};\n\t}\n}\n","import type { Encoder } from \"lib0/encoding\";\nimport type { Event, MessageEvent } from \"ws\";\nimport type { Awareness } from \"y-protocols/awareness\";\nimport type * as Y from \"yjs\";\nimport type { CloseEvent } from \"./CloseEvents.ts\";\nimport type { IncomingMessage } from \"./IncomingMessage.ts\";\nimport type { OutgoingMessage } from \"./OutgoingMessage.ts\";\nimport type { AuthenticationMessage } from \"./OutgoingMessages/AuthenticationMessage.ts\";\nimport type { AwarenessMessage } from \"./OutgoingMessages/AwarenessMessage.ts\";\nimport type { QueryAwarenessMessage } from \"./OutgoingMessages/QueryAwarenessMessage.ts\";\nimport type { SyncStepOneMessage } from \"./OutgoingMessages/SyncStepOneMessage.ts\";\nimport type { SyncStepTwoMessage } from \"./OutgoingMessages/SyncStepTwoMessage.ts\";\nimport type { UpdateMessage } from \"./OutgoingMessages/UpdateMessage.ts\";\n\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 enum MessageType {\n Sync = 0,\n Awareness = 1,\n Auth = 2,\n QueryAwareness = 3,\n Subdoc = 4,\n Stateless = 5,\n CLOSE = 7,\n SyncStatus = 8,\n}\n\nexport enum WebSocketStatus {\n Connecting = \"connecting\",\n Connected = \"connected\",\n Disconnected = \"disconnected\",\n}\n\nexport type AuthorizedScope = \"service\" | \"admin\" | \"owner\" | \"editor\" | \"viewer\" | \"read-write\" | \"readonly\";\n\nexport interface OutgoingMessageInterface {\n encoder: Encoder;\n type?: MessageType;\n}\n\nexport interface OutgoingMessageArguments {\n documentName: string;\n token: string;\n document: Y.Doc;\n awareness: Awareness;\n clients: number[];\n states: Map<number, { [key: string]: any }>;\n update: any;\n payload: string;\n encoder: Encoder;\n}\n\nexport interface Constructable<T> {\n new (...args: any): T;\n}\n\nexport type ConstructableOutgoingMessage =\n | Constructable<AuthenticationMessage>\n | Constructable<AwarenessMessage>\n | Constructable<QueryAwarenessMessage>\n | Constructable<SyncStepOneMessage>\n | Constructable<SyncStepTwoMessage>\n | Constructable<UpdateMessage>;\n\nexport type onAuthenticationFailedParameters = {\n reason: string;\n};\n\nexport type onAuthenticatedParameters = {\n scope: AuthorizedScope;\n};\n\nexport type onOpenParameters = {\n event: Event;\n};\n\nexport type onMessageParameters = {\n event: MessageEvent;\n message: IncomingMessage;\n};\n\nexport type onOutgoingMessageParameters = {\n message: OutgoingMessage;\n};\n\nexport type onStatusParameters = {\n status: WebSocketStatus;\n};\n\nexport type onSyncedParameters = {\n state: boolean;\n};\n\nexport type onUnsyncedChangesParameters = {\n number: number;\n};\n\nexport type onDisconnectParameters = {\n event: CloseEvent;\n};\n\nexport type onCloseParameters = {\n event: CloseEvent;\n};\n\nexport type onAwarenessUpdateParameters = {\n states: StatesArray;\n};\n\nexport type onAwarenessChangeParameters = {\n states: StatesArray;\n};\n\nexport type onStatelessParameters = {\n payload: string;\n};\n\nexport type StatesArray = { clientId: number; [key: string | number]: any }[];\n\n// ── Abracadabra extensions ────────────────────────────────────────────────────\n\nexport type EffectiveRole = \"service\" | \"admin\" | \"owner\" | \"editor\" | \"viewer\" | null;\n\n/**\n * Ed25519 identity for passwordless crypto auth.\n *\n * The public key is the sole identifier sent to the server during the\n * challenge-response handshake. Username is decoupled from auth and is\n * managed separately as a mutable display name (see PATCH /users/me).\n */\nexport interface CryptoIdentity {\n /** base64url-encoded Ed25519 public key (32 bytes). Primary auth identifier. */\n publicKey: string;\n}\n\nexport interface SubdocRegisteredEvent {\n childId: string;\n parentId: string;\n}\n\nexport type onSubdocRegisteredParameters = SubdocRegisteredEvent;\n\nexport type onSubdocLoadedParameters = {\n childId: string;\n provider: import(\"./AbracadabraProvider.ts\").AbracadabraProvider;\n};\n\nexport interface AbracadabraOutgoingMessageArguments extends OutgoingMessageArguments {\n childDocumentName: string;\n}\n\n// ── REST API response types ──────────────────────────────────────────────────\n\nexport interface UserProfile {\n id: string;\n username: string;\n email: string | null;\n displayName: string | null;\n role: string;\n}\n\nexport interface DocumentMeta {\n id: string;\n parent_id: string | null;\n}\n\nexport interface UploadMeta {\n id: string;\n doc_id: string;\n filename: string;\n}\n\nexport interface UploadInfo {\n id: string;\n filename: string;\n mime_type: string;\n size: number;\n}\n\nexport interface PublicKeyInfo {\n id: string;\n publicKey: string;\n deviceName: string | null;\n revoked: boolean;\n}\n\nexport interface PermissionEntry {\n user_id: string;\n role: \"owner\" | \"editor\" | \"viewer\" | \"observer\";\n username: string;\n display_name: string | null;\n}\n\nexport interface HealthStatus {\n status: string;\n version: string;\n active_documents: number;\n}\n\nexport interface ServerInfo {\n /** Human-readable server name set by the operator. */\n name?: string;\n /** Server version string. */\n version?: string;\n /** Entry-point document ID advertised by the server, if configured. */\n index_doc_id?: string;\n}\n\n// ── Search ───────────────────────────────────────────────────────────────────\n\nexport interface SearchResult {\n docId: string;\n /** Number of matching trigrams — higher is better. */\n score: number;\n}\n\n// ── Spaces ───────────────────────────────────────────────────────────────────\n\nexport interface SpaceMeta {\n id: string;\n doc_id: string;\n name: string;\n description: string | null;\n visibility: \"public\" | \"private\" | \"invite\";\n is_hub: boolean;\n owner_id: string | null;\n created_at: number;\n updated_at: number;\n}\n\n// ── Invites ──────────────────────────────────────────────────────────────────\n\nexport interface InviteRow {\n code: string;\n createdBy: string | null;\n role: string;\n maxUses: number;\n useCount: number;\n expiresAt: number | null;\n revoked: boolean;\n createdAt: number;\n}\n\n// ── Upload queue ─────────────────────────────────────────────────────────────\n\nexport type UploadQueueStatus = \"pending\" | \"uploading\" | \"done\" | \"error\";\n\nexport interface UploadQueueEntry {\n /** Client-generated UUID. */\n id: string;\n docId: string;\n /** File or Blob to upload. File extends Blob and survives IDB as Blob. */\n file: Blob;\n /** Eagerly captured filename (from File.name or explicit arg). */\n filename: string;\n status: UploadQueueStatus;\n createdAt: number;\n error?: string;\n}\n\nexport interface DocEncryptionInfo {\n mode: \"none\" | \"cse\" | \"e2e\";\n effective_mode: \"none\" | \"cse\" | \"e2e\";\n inherited_from?: string;\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 * Check whether n is negative, while considering the -0 edge case. While `-0 < 0` is false, this\n * function returns true for -0,-1,,.. and returns false for 0,1,2,...\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also distinguishes between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* c8 ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\nexport const HIGHEST_INT32 = binary.BITS31\nexport const HIGHEST_UINT32 = binary.BITS32\n\n/* c8 ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n\n/**\n * Count the number of \"1\" bits in an unsigned 32bit number.\n *\n * Super fun bitcount algorithm by Brian Kernighan.\n *\n * @param {number} n\n */\nexport const countBits = n => {\n n &= binary.BITS32\n let count = 0\n while (n) {\n n &= (n - 1)\n count++\n }\n return count\n}\n","import * as array from './array.js'\n\n/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * The largest utf16 character.\n * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8)\n */\nexport const MAX_UTF16_CHARACTER = fromCharCode(65535)\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array<ArrayBuffer>}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* c8 ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array<ArrayBuffer>}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* c8 ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* c8 ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* c8 ignore start */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* c8 ignore next */\n utf8TextDecoder = null\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* c8 ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n\n/**\n * @param {string} source\n * @param {number} n\n */\nexport const repeat = (source, n) => array.unfold(n, () => source).join('')\n\n/**\n * Escape HTML characters &,<,>,',\" to their respective HTML entities &,<,>,',"\n *\n * @param {string} str\n */\nexport const escapeHTML = str =>\n str.replace(/[&<>'\"]/g, r => /** @type {string} */ ({\n '&': '&',\n '<': '<',\n '>': '>',\n \"'\": ''',\n '\"': '"'\n }[r]))\n\n/**\n * Reverse of `escapeHTML`\n *\n * @param {string} str\n */\nexport const unescapeHTML = str =>\n str.replace(/&|<|>|'|"/g, r => /** @type {string} */ ({\n '&': '&',\n '<': '<',\n '>': '>',\n ''': \"'\",\n '"': '\"'\n }[r]))\n","/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* c8 ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n\n/**\n * @param {boolean} property\n * @return {asserts property is true}\n */\nexport const assert = property => { if (!property) throw create('Assert failed') }\n","/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\nimport * as string from './string.js'\nimport * as array from './array.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array<Uint8Array>}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * @param {function(Encoder):void} f\n */\nexport const encode = (f) => {\n const encoder = createEncoder()\n f(encoder)\n return toUint8Array(encoder)\n}\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Check whether encoder is empty.\n *\n * @function\n * @param {Encoder} encoder\n * @return {boolean}\n */\nexport const hasContent = encoder => encoder.cpos > 0 || encoder.bufs.length > 0\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array<ArrayBuffer>} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nexport const verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer. Max encodable integer is 2^53.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num = math.floor(num / 64) // shift >>> 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n}\n\n/**\n * A cache to store strings temporarily\n */\nconst _strBuffer = new Uint8Array(30000)\nconst _maxStrBSize = _strBuffer.length / 3\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringNative = (encoder, str) => {\n if (str.length < _maxStrBSize) {\n // We can encode the string into the existing buffer\n /* c8 ignore next */\n const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0\n writeVarUint(encoder, written)\n for (let i = 0; i < written; i++) {\n write(encoder, _strBuffer[i])\n }\n } else {\n writeVarUint8Array(encoder, string.encodeUtf8(str))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringPolyfill = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\n/* c8 ignore next */\nexport const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill\n\n/**\n * Write a string terminated by a special byte sequence. This is not very performant and is\n * generally discouraged. However, the resulting byte arrays are lexiographically ordered which\n * makes this a nice feature for databases.\n *\n * The string will be encoded using utf8 and then terminated and escaped using writeTerminatingUint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const writeTerminatedString = (encoder, str) =>\n writeTerminatedUint8Array(encoder, string.encodeUtf8(str))\n\n/**\n * Write a terminating Uint8Array. Note that this is not performant and is generally\n * discouraged. There are few situations when this is needed.\n *\n * We use 0x0 as a terminating character. 0x1 serves as an escape character for 0x0 and 0x1.\n *\n * Example: [0,1,2] is encoded to [1,0,1,1,2,0]. 0x0, and 0x1 needed to be escaped using 0x1. Then\n * the result is terminated using the 0x0 character.\n *\n * This is basically how many systems implement null terminated strings. However, we use an escape\n * character 0x1 to avoid issues and potenial attacks on our database (if this is used as a key\n * encoder for NoSql databases).\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} buf The string that is to be encoded.\n */\nexport const writeTerminatedUint8Array = (encoder, buf) => {\n for (let i = 0; i < buf.length; i++) {\n const b = buf[i]\n if (b === 0 || b === 1) {\n write(encoder, 1)\n }\n write(encoder, buf[i])\n }\n write(encoder, 0)\n}\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * @typedef {Array<AnyEncodable>} AnyEncodableArray\n */\n\n/**\n * @typedef {undefined|null|number|bigint|boolean|string|{[k:string]:AnyEncodable}|AnyEncodableArray|Uint8Array} AnyEncodable\n */\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object<string,any> | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array<any> | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {AnyEncodable} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && math.abs(data) <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (array.isArray(data)) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array<string>}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n","/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as binary from './binary.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as string from './string.js'\nimport * as error from './error.js'\nimport * as encoding from './encoding.js'\n\nconst errorUnexpectedEndOfArray = error.create('Unexpected end of array')\nconst errorIntegerOutOfRange = error.create('Integer out of Range')\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n * @template {ArrayBufferLike} [Buf=ArrayBufferLike]\n */\nexport class Decoder {\n /**\n * @param {Uint8Array<Buf>} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array<Buf>}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Uint8Array<Buf>} uint8Array\n * @return {Decoder<Buf>}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Decoder<Buf>} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array<Buf>}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Decoder<Buf>} decoder\n * @return {Uint8Array<Buf>}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let mult = 1\n const len = decoder.arr.length\n while (decoder.pos < len) {\n const r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num\n mult *= 128 // next iteration, shift 7 \"more\" to the left\n if (r < binary.BIT8) {\n return num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let mult = 64\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n const len = decoder.arr.length\n while (decoder.pos < len) {\n r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult\n mult *= 128\n if (r < binary.BIT8) {\n return sign * num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * We don't test this function anymore as we use native decoding/encoding by default now.\n * Better not modify this anymore..\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\n/* c8 ignore start */\nexport const _readVarStringPolyfill = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n/* c8 ignore stop */\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n */\nexport const _readVarStringNative = decoder =>\n /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder))\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n *\n */\n/* c8 ignore next */\nexport const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill\n\n/**\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTerminatedUint8Array = decoder => {\n const encoder = encoding.createEncoder()\n let b\n while (true) {\n b = readUint8(decoder)\n if (b === 0) {\n return encoding.toUint8Array(encoder)\n }\n if (b === 1) {\n b = readUint8(decoder)\n }\n encoding.write(encoder, b)\n }\n}\n\n/**\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const readTerminatedString = decoder => string.decodeUtf8(readTerminatedUint8Array(decoder))\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array<function(Decoder):any>}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object<string,any>\n const len = readVarUint(decoder)\n /**\n * @type {Object<string,any>}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array<any>\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = math.floor(diff / 2) // shift >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n","import type { Decoder } from \"lib0/decoding\";\nimport {\n\tcreateDecoder,\n\tpeekVarString,\n\treadVarUint,\n\treadVarUint8Array,\n\treadVarString,\n} from \"lib0/decoding\";\nimport type { Encoder } from \"lib0/encoding\";\nimport {\n\tcreateEncoder,\n\twriteVarUint,\n\twriteVarUint8Array,\n\twriteVarString,\n\tlength,\n} from \"lib0/encoding\";\nimport type { MessageType } from \"./types.ts\";\n\nexport class IncomingMessage {\n\tdata: any;\n\n\tencoder: Encoder;\n\n\tdecoder: Decoder;\n\n\tconstructor(data: any) {\n\t\tthis.data = data;\n\t\tthis.encoder = createEncoder();\n\t\tthis.decoder = createDecoder(new Uint8Array(this.data));\n\t}\n\n\tpeekVarString(): string {\n\t\treturn peekVarString(this.decoder);\n\t}\n\n\treadVarUint(): MessageType {\n\t\treturn readVarUint(this.decoder);\n\t}\n\n\treadVarString(): string {\n\t\treturn readVarString(this.decoder);\n\t}\n\n\treadVarUint8Array() {\n\t\treturn readVarUint8Array(this.decoder);\n\t}\n\n\twriteVarUint(type: MessageType) {\n\t\treturn writeVarUint(this.encoder, type);\n\t}\n\n\twriteVarString(string: string) {\n\t\treturn writeVarString(this.encoder, string);\n\t}\n\n\twriteVarUint8Array(data: Uint8Array) {\n\t\treturn writeVarUint8Array(this.encoder, data);\n\t}\n\n\tlength() {\n\t\treturn length(this.encoder);\n\t}\n}\n","import type { Encoder } from \"lib0/encoding\";\nimport { createEncoder, toUint8Array } from \"lib0/encoding\";\nimport type {\n\tMessageType,\n\tOutgoingMessageArguments,\n\tOutgoingMessageInterface,\n} from \"./types.ts\";\n\nexport class OutgoingMessage implements OutgoingMessageInterface {\n\tencoder: Encoder;\n\n\ttype?: MessageType;\n\n\tconstructor() {\n\t\tthis.encoder = createEncoder();\n\t}\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\treturn args.encoder;\n\t}\n\n\ttoUint8Array() {\n\t\treturn toUint8Array(this.encoder);\n\t}\n}\n","import * as encoding from \"lib0/encoding\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class CloseMessage extends OutgoingMessage {\n\ttype = MessageType.CLOSE;\n\n\tdescription = \"Ask the server to close the connection\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tencoding.writeVarString(this.encoder, args.documentName!);\n\t\tencoding.writeVarUint(this.encoder, this.type);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { WsReadyStates } from \"./types.ts\";\nimport { retry } from \"@lifeomic/attempt\";\nimport * as time from \"lib0/time\";\nimport type { Event, MessageEvent } from \"ws\";\nimport EventEmitter from \"./EventEmitter.ts\";\nimport type { AbracadabraBaseProvider } from \"./AbracadabraBaseProvider.ts\";\nimport { IncomingMessage } from \"./IncomingMessage.ts\";\nimport { CloseMessage } from \"./OutgoingMessages/CloseMessage.ts\";\nimport {\n WebSocketStatus,\n type onAwarenessChangeParameters,\n type onAwarenessUpdateParameters,\n type onCloseParameters,\n type onDisconnectParameters,\n type onMessageParameters,\n type onOpenParameters,\n type onOutgoingMessageParameters,\n type onStatusParameters,\n} from \"./types.ts\";\n\nexport type AbracadabraWebSocketConn = WebSocket & { identifier: string };\n/** @deprecated Use AbracadabraWebSocketConn */\nexport type HocuspocusWebSocket = AbracadabraWebSocketConn;\n/** @deprecated Use AbracadabraWebSocketConn */\nexport type HocusPocusWebSocket = AbracadabraWebSocketConn;\n\nexport type AbracadabraWSConfiguration = Required<\n Pick<CompleteAbracadabraWSConfiguration, \"url\">\n> &\n Partial<CompleteAbracadabraWSConfiguration>;\n\n/** @deprecated Use AbracadabraWSConfiguration */\nexport type HocuspocusProviderWebsocketConfiguration = AbracadabraWSConfiguration;\n\nexport interface CompleteAbracadabraWSConfiguration {\n /**\n * Whether to connect automatically when creating the provider instance. Default=true\n */\n autoConnect: boolean;\n\n /**\n * URL of your @hocuspocus/server instance\n */\n url: string;\n\n /**\n * By default, trailing slashes are removed from the URL. Set this to true\n * to preserve trailing slashes if your server configuration requires them.\n */\n preserveTrailingSlash: boolean;\n\n /**\n * An optional WebSocket polyfill, for example for Node.js\n */\n WebSocketPolyfill: any;\n\n /**\n * Disconnect when no message is received for the defined amount of milliseconds.\n */\n messageReconnectTimeout: number;\n /**\n * The delay between each attempt in milliseconds. You can provide a factor to have the delay grow exponentially.\n */\n delay: number;\n /**\n * The initialDelay is the amount of time to wait before making the first attempt. This option should typically be 0 since you typically want the first attempt to happen immediately.\n */\n initialDelay: number;\n /**\n * The factor option is used to grow the delay exponentially.\n */\n factor: number;\n /**\n * The maximum number of attempts or 0 if there is no limit on number of attempts.\n */\n maxAttempts: number;\n /**\n * minDelay is used to set a lower bound of delay when jitter is enabled. This property has no effect if jitter is disabled.\n */\n minDelay: number;\n /**\n * The maxDelay option is used to set an upper bound for the delay when factor is enabled. A value of 0 can be provided if there should be no upper bound when calculating delay.\n */\n maxDelay: number;\n /**\n * If jitter is true then the calculated delay will be a random integer value between minDelay and the calculated delay for the current iteration.\n */\n jitter: boolean;\n /**\n * A timeout in milliseconds. If timeout is non-zero then a timer is set using setTimeout. If the timeout is triggered then future attempts will be aborted.\n */\n timeout: number;\n handleTimeout: (() => Promise<unknown>) | null;\n onOpen: (data: onOpenParameters) => void;\n onConnect: () => void;\n onMessage: (data: onMessageParameters) => void;\n onOutgoingMessage: (data: onOutgoingMessageParameters) => void;\n onStatus: (data: onStatusParameters) => void;\n onDisconnect: (data: onDisconnectParameters) => void;\n onClose: (data: onCloseParameters) => void;\n onDestroy: () => void;\n onAwarenessUpdate: (data: onAwarenessUpdateParameters) => void;\n onAwarenessChange: (data: onAwarenessChangeParameters) => void;\n\n /**\n * Map of attached providers keyed by documentName.\n */\n providerMap: Map<string, AbracadabraBaseProvider>;\n}\n\n/** @deprecated Use CompleteAbracadabraWSConfiguration */\nexport type CompleteHocuspocusProviderWebsocketConfiguration = CompleteAbracadabraWSConfiguration;\n\nexport class AbracadabraWS extends EventEmitter {\n private messageQueue: any[] = [];\n\n public configuration: CompleteAbracadabraWSConfiguration = {\n url: \"\",\n autoConnect: true,\n preserveTrailingSlash: false,\n // @ts-ignore\n document: undefined,\n WebSocketPolyfill: undefined,\n // TODO: this should depend on awareness.outdatedTime\n messageReconnectTimeout: 30000,\n // 1 second\n delay: 1000,\n // instant\n initialDelay: 0,\n // double the delay each time\n factor: 2,\n // unlimited retries\n maxAttempts: 0,\n // wait at least 1 second\n minDelay: 1000,\n // at least every 30 seconds\n maxDelay: 30000,\n // randomize\n jitter: true,\n // retry forever\n timeout: 0,\n onOpen: () => null,\n onConnect: () => null,\n onMessage: () => null,\n onOutgoingMessage: () => null,\n onStatus: () => null,\n onDisconnect: () => null,\n onClose: () => null,\n onDestroy: () => null,\n onAwarenessUpdate: () => null,\n onAwarenessChange: () => null,\n handleTimeout: null,\n providerMap: new Map(),\n };\n\n webSocket: AbracadabraWebSocketConn | null = null;\n\n webSocketHandlers: { [key: string]: any } = {};\n\n shouldConnect = true;\n\n status = WebSocketStatus.Disconnected;\n\n lastMessageReceived = 0;\n\n identifier = 0;\n\n intervals: any = {\n connectionChecker: null,\n };\n\n connectionAttempt: {\n resolve: (value?: any) => void;\n reject: (reason?: any) => void;\n } | null = null;\n\n constructor(configuration: AbracadabraWSConfiguration) {\n super();\n this.setConfiguration(configuration);\n\n this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill\n ? configuration.WebSocketPolyfill\n : WebSocket;\n\n this.on(\"open\", this.configuration.onOpen);\n this.on(\"open\", this.onOpen.bind(this));\n this.on(\"connect\", this.configuration.onConnect);\n this.on(\"message\", this.configuration.onMessage);\n this.on(\"outgoingMessage\", this.configuration.onOutgoingMessage);\n this.on(\"status\", this.configuration.onStatus);\n this.on(\"disconnect\", this.configuration.onDisconnect);\n this.on(\"close\", this.configuration.onClose);\n this.on(\"destroy\", this.configuration.onDestroy);\n this.on(\"awarenessUpdate\", this.configuration.onAwarenessUpdate);\n this.on(\"awarenessChange\", this.configuration.onAwarenessChange);\n\n this.on(\"close\", this.onClose.bind(this));\n this.on(\"message\", this.onMessage.bind(this));\n\n this.intervals.connectionChecker = setInterval(\n this.checkConnection.bind(this),\n this.configuration.messageReconnectTimeout / 10,\n );\n\n if (this.shouldConnect) {\n this.connect();\n }\n }\n\n receivedOnOpenPayload?: Event | undefined = undefined;\n\n async onOpen(event: Event) {\n this.status = WebSocketStatus.Connected;\n this.emit(\"status\", { status: WebSocketStatus.Connected });\n\n this.cancelWebsocketRetry = undefined;\n this.receivedOnOpenPayload = event;\n }\n\n attach(provider: AbracadabraBaseProvider) {\n this.configuration.providerMap.set(provider.configuration.name, provider);\n\n if (this.status === WebSocketStatus.Disconnected && this.shouldConnect) {\n this.connect();\n }\n\n if (this.receivedOnOpenPayload && this.status === WebSocketStatus.Connected) {\n provider.onOpen(this.receivedOnOpenPayload);\n }\n }\n\n detach(provider: AbracadabraBaseProvider) {\n if (this.configuration.providerMap.has(provider.configuration.name)) {\n provider.send(CloseMessage, {\n documentName: provider.configuration.name,\n });\n this.configuration.providerMap.delete(provider.configuration.name);\n }\n }\n\n public setConfiguration(\n configuration: Partial<AbracadabraWSConfiguration> = {},\n ): void {\n this.configuration = { ...this.configuration, ...configuration };\n\n if (!this.configuration.autoConnect) {\n this.shouldConnect = false;\n }\n }\n\n cancelWebsocketRetry?: () => void;\n\n async connect() {\n if (this.status === WebSocketStatus.Connected) {\n return;\n }\n\n // Always cancel any previously initiated connection retryer instances\n if (this.cancelWebsocketRetry) {\n this.cancelWebsocketRetry();\n this.cancelWebsocketRetry = undefined;\n }\n\n this.receivedOnOpenPayload = undefined;\n this.shouldConnect = true;\n\n const abortableRetry = () => {\n let cancelAttempt = false;\n\n const retryPromise = retry(this.createWebSocketConnection.bind(this), {\n delay: this.configuration.delay,\n initialDelay: this.configuration.initialDelay,\n factor: this.configuration.factor,\n maxAttempts: this.configuration.maxAttempts,\n minDelay: this.configuration.minDelay,\n maxDelay: this.configuration.maxDelay,\n jitter: this.configuration.jitter,\n timeout: this.configuration.timeout,\n handleTimeout: this.configuration.handleTimeout,\n beforeAttempt: (context) => {\n if (!this.shouldConnect || cancelAttempt) {\n context.abort();\n }\n },\n }).catch((error: any) => {\n // If we aborted the connection attempt then don't throw an error\n // ref: https://github.com/lifeomic/attempt/blob/master/src/index.ts#L136\n if (error && error.code !== \"ATTEMPT_ABORTED\") {\n throw error;\n }\n });\n\n return {\n retryPromise,\n cancelFunc: () => {\n cancelAttempt = true;\n },\n };\n };\n\n const { retryPromise, cancelFunc } = abortableRetry();\n this.cancelWebsocketRetry = cancelFunc;\n\n return retryPromise;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n attachWebSocketListeners(ws: AbracadabraWebSocketConn, reject: Function) {\n const { identifier } = ws;\n const onMessageHandler = (payload: any) => this.emit(\"message\", payload);\n const onCloseHandler = (payload: any) => this.emit(\"close\", { event: payload });\n const onOpenHandler = (payload: any) => this.emit(\"open\", payload);\n const onErrorHandler = (err: any) => {\n reject(err);\n };\n\n this.webSocketHandlers[identifier] = {\n message: onMessageHandler,\n close: onCloseHandler,\n open: onOpenHandler,\n error: onErrorHandler,\n };\n\n const handlers = this.webSocketHandlers[ws.identifier];\n\n Object.keys(handlers).forEach((name) => {\n ws.addEventListener(name, handlers[name]);\n });\n }\n\n cleanupWebSocket() {\n if (!this.webSocket) {\n return;\n }\n const { identifier } = this.webSocket;\n const handlers = this.webSocketHandlers[identifier];\n\n Object.keys(handlers).forEach((name) => {\n this.webSocket?.removeEventListener(name, handlers[name]);\n delete this.webSocketHandlers[identifier];\n });\n\n try {\n // Check if the WebSocket is still in CONNECTING state (0)\n // If so, calling close() might throw in some environments or be race-prone\n if (this.webSocket.readyState !== 0 && this.webSocket.readyState !== 3) {\n this.webSocket.close();\n }\n } catch (e) {\n // Ignore errors during close\n }\n\n this.webSocket = null;\n }\n\n createWebSocketConnection() {\n return new Promise((resolve, reject) => {\n if (this.webSocket) {\n this.messageQueue = [];\n this.cleanupWebSocket();\n }\n this.lastMessageReceived = 0;\n this.identifier += 1;\n\n // Init the WebSocket connection\n const ws = new this.configuration.WebSocketPolyfill(this.url);\n ws.binaryType = \"arraybuffer\";\n ws.identifier = this.identifier;\n\n this.attachWebSocketListeners(ws, reject);\n\n this.webSocket = ws;\n\n // Reset the status\n this.status = WebSocketStatus.Connecting;\n this.emit(\"status\", { status: WebSocketStatus.Connecting });\n\n // Store resolve/reject for later use\n this.connectionAttempt = {\n resolve,\n reject,\n };\n });\n }\n\n onMessage(event: MessageEvent) {\n this.resolveConnectionAttempt();\n\n this.lastMessageReceived = time.getUnixTime();\n\n const message = new IncomingMessage(event.data);\n const documentName = message.peekVarString();\n\n this.configuration.providerMap.get(documentName)?.onMessage(event);\n }\n\n resolveConnectionAttempt() {\n if (this.connectionAttempt) {\n this.connectionAttempt.resolve();\n this.connectionAttempt = null;\n\n this.status = WebSocketStatus.Connected;\n this.emit(\"status\", { status: WebSocketStatus.Connected });\n this.emit(\"connect\");\n this.messageQueue.forEach((message) => this.send(message));\n this.messageQueue = [];\n }\n }\n\n stopConnectionAttempt() {\n this.connectionAttempt = null;\n }\n\n rejectConnectionAttempt() {\n this.connectionAttempt?.reject();\n this.connectionAttempt = null;\n }\n\n closeTries = 0;\n\n checkConnection() {\n // Don't check the connection when it's not even established\n if (this.status !== WebSocketStatus.Connected) {\n return;\n }\n\n // Don't close the connection while waiting for the first message\n if (!this.lastMessageReceived) {\n return;\n }\n\n // Don't close the connection when a message was received recently\n if (\n this.configuration.messageReconnectTimeout >=\n time.getUnixTime() - this.lastMessageReceived\n ) {\n return;\n }\n\n // No message received in a long time, not even your own\n // Awareness updates, which are updated every 15 seconds\n // if awareness is enabled.\n this.closeTries += 1;\n // https://bugs.webkit.org/show_bug.cgi?id=247943\n if (this.closeTries > 2) {\n this.onClose({\n event: {\n code: 4408,\n reason: \"forced\",\n },\n });\n this.closeTries = 0;\n } else {\n this.webSocket?.close();\n this.messageQueue = [];\n }\n }\n\n get serverUrl() {\n if (this.configuration.preserveTrailingSlash) {\n return this.configuration.url;\n }\n\n // By default, ensure that the URL never ends with /\n let url = this.configuration.url;\n while (url[url.length - 1] === \"/\") {\n url = url.slice(0, url.length - 1);\n }\n\n return url;\n }\n\n get url() {\n return this.serverUrl;\n }\n\n disconnect() {\n this.shouldConnect = false;\n\n if (this.webSocket === null) {\n return;\n }\n\n try {\n this.webSocket.close();\n this.messageQueue = [];\n } catch (e) {\n console.error(e);\n }\n }\n\n send(message: any) {\n if (this.webSocket?.readyState === WsReadyStates.Open) {\n this.webSocket.send(message);\n } else {\n this.messageQueue.push(message);\n }\n }\n\n onClose({ event }: onCloseParameters) {\n this.closeTries = 0;\n this.cleanupWebSocket();\n\n if (this.connectionAttempt) {\n // That connection attempt failed.\n this.rejectConnectionAttempt();\n }\n\n // Let's update the connection status.\n this.status = WebSocketStatus.Disconnected;\n this.emit(\"status\", { status: WebSocketStatus.Disconnected });\n\n // Detect server-side rate-limit close (code 4429).\n const isRateLimited = (event as any)?.code === 4429;\n this.emit(\"disconnect\", { event });\n if (isRateLimited) {\n this.emit(\"rateLimited\");\n }\n\n // trigger connect if no retry is running and we want to have a connection\n if (!this.cancelWebsocketRetry && this.shouldConnect) {\n // Apply a much longer delay for rate-limited closes to let the server window reset.\n const delay = isRateLimited ? 60_000 : this.configuration.delay;\n setTimeout(() => {\n this.connect();\n }, delay);\n }\n }\n\n destroy() {\n this.emit(\"destroy\");\n\n clearInterval(this.intervals.connectionChecker);\n\n // If there is still a connection attempt outstanding then we should stop\n // it before calling disconnect, otherwise it will be rejected in the onClose\n // handler and trigger a retry\n this.stopConnectionAttempt();\n\n this.disconnect();\n\n this.removeAllListeners();\n\n this.cleanupWebSocket();\n }\n}\n\n/** @deprecated Use AbracadabraWS */\nexport const HocuspocusProviderWebsocket = AbracadabraWS;\n/** @deprecated Use AbracadabraWS */\nexport type HocuspocusProviderWebsocket = AbracadabraWS;\n","import * as encoding from \"lib0/encoding\";\nimport * as decoding from \"lib0/decoding\";\nimport type { AuthorizedScope } from \"./types.ts\";\n\nexport enum AuthMessageType {\n\tToken = 0,\n\tPermissionDenied = 1,\n\tAuthenticated = 2,\n}\n\nexport const writeAuthentication = (\n\tencoder: encoding.Encoder,\n\tauth: string,\n) => {\n\tencoding.writeVarUint(encoder, AuthMessageType.Token);\n\tencoding.writeVarString(encoder, auth);\n};\n\nexport const writePermissionDenied = (\n\tencoder: encoding.Encoder,\n\treason: string,\n) => {\n\tencoding.writeVarUint(encoder, AuthMessageType.PermissionDenied);\n\tencoding.writeVarString(encoder, reason);\n};\n\nexport const writeAuthenticated = (\n\tencoder: encoding.Encoder,\n\tscope: AuthorizedScope,\n) => {\n\tencoding.writeVarUint(encoder, AuthMessageType.Authenticated);\n\tencoding.writeVarString(encoder, scope);\n};\n\nexport const writeTokenSyncRequest = (\n\tencoder: encoding.Encoder,\n) => {\n\tencoding.writeVarUint(encoder, AuthMessageType.Token);\n};\n\nexport const readAuthMessage = (\n\tdecoder: decoding.Decoder,\n\tsendToken: () => void,\n\tpermissionDeniedHandler: (reason: string) => void,\n\tauthenticatedHandler: (scope: string) => void,\n) => {\n\tswitch (decoding.readVarUint(decoder)) {\n\t\tcase AuthMessageType.Token: {\n\t\t\tsendToken();\n\t\t\tbreak;\n\t\t}\n\t\tcase AuthMessageType.PermissionDenied: {\n\t\t\tpermissionDeniedHandler(decoding.readVarString(decoder));\n\t\t\tbreak;\n\t\t}\n\t\tcase AuthMessageType.Authenticated: {\n\t\t\tauthenticatedHandler(decoding.readVarString(decoder));\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t}\n};\n","/**\n * @module sync-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as Y from 'yjs'\n\n/**\n * @typedef {Map<number, number>} StateMap\n */\n\n/**\n * Core Yjs defines two message types:\n * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.\n * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it\n * received all information from the remote client.\n *\n * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection\n * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both\n * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.\n *\n * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.\n * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies\n * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the\n * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can\n * easily be implemented on top of http and websockets. 2. The server should only reply to requests, and not initiate them.\n * Therefore it is necessary that the client initiates the sync.\n *\n * Construction of a message:\n * [messageType : varUint, message definition..]\n *\n * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!\n *\n * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)\n */\n\nexport const messageYjsSyncStep1 = 0\nexport const messageYjsSyncStep2 = 1\nexport const messageYjsUpdate = 2\n\n/**\n * Create a sync step 1 message based on the state of the current shared document.\n *\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n */\nexport const writeSyncStep1 = (encoder, doc) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep1)\n const sv = Y.encodeStateVector(doc)\n encoding.writeVarUint8Array(encoder, sv)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n * @param {Uint8Array} [encodedStateVector]\n */\nexport const writeSyncStep2 = (encoder, doc, encodedStateVector) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep2)\n encoding.writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector))\n}\n\n/**\n * Read SyncStep1 message and reply with SyncStep2.\n *\n * @param {decoding.Decoder} decoder The reply to the received message\n * @param {encoding.Encoder} encoder The received message\n * @param {Y.Doc} doc\n */\nexport const readSyncStep1 = (decoder, encoder, doc) =>\n writeSyncStep2(encoder, doc, decoding.readVarUint8Array(decoder))\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n * @param {(error:Error)=>any} [errorHandler]\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin, errorHandler) => {\n try {\n Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n } catch (error) {\n if (errorHandler != null) errorHandler(/** @type {Error} */ (error))\n // This catches errors that are thrown by event handlers\n console.error('Caught error while handling a Yjs update', error)\n }\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Uint8Array} update\n */\nexport const writeUpdate = (encoder, update) => {\n encoding.writeVarUint(encoder, messageYjsUpdate)\n encoding.writeVarUint8Array(encoder, update)\n}\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n * @param {(error:Error)=>any} [errorHandler]\n */\nexport const readUpdate = readSyncStep2\n\n/**\n * @param {decoding.Decoder} decoder A message received from another client\n * @param {encoding.Encoder} encoder The reply message. Does not need to be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n * @param {(error:Error)=>any} [errorHandler] Optional error handler that catches errors when reading Yjs messages.\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin, errorHandler) => {\n const messageType = decoding.readVarUint(decoder)\n switch (messageType) {\n case messageYjsSyncStep1:\n readSyncStep1(decoder, encoder, doc)\n break\n case messageYjsSyncStep2:\n readSyncStep2(decoder, doc, transactionOrigin, errorHandler)\n break\n case messageYjsUpdate:\n readUpdate(decoder, doc, transactionOrigin, errorHandler)\n break\n default:\n throw new Error('Unknown message type')\n }\n return messageType\n}\n","import { readAuthMessage } from \"./auth.ts\";\nimport { readVarInt, readVarString } from \"lib0/decoding\";\nimport type { CloseEvent } from \"ws\";\nimport * as awarenessProtocol from \"y-protocols/awareness\";\nimport { messageYjsSyncStep2, readSyncMessage } from \"y-protocols/sync\";\nimport type { AbracadabraBaseProvider } from \"./AbracadabraBaseProvider.ts\";\nimport type { IncomingMessage } from \"./IncomingMessage.ts\";\nimport { OutgoingMessage } from \"./OutgoingMessage.ts\";\nimport { MessageType } from \"./types.ts\";\n\nexport class MessageReceiver {\n message: IncomingMessage;\n\n constructor(message: IncomingMessage) {\n this.message = message;\n }\n\n public apply(provider: AbracadabraBaseProvider, emitSynced: boolean) {\n const { message } = this;\n const type = message.readVarUint();\n\n const emptyMessageLength = message.length();\n\n switch (type) {\n case MessageType.Sync:\n this.applySyncMessage(provider, emitSynced);\n break;\n\n case MessageType.Awareness:\n this.applyAwarenessMessage(provider);\n break;\n\n case MessageType.Auth:\n this.applyAuthMessage(provider);\n break;\n\n case MessageType.QueryAwareness:\n this.applyQueryAwarenessMessage(provider);\n break;\n\n case MessageType.Stateless:\n provider.receiveStateless(readVarString(message.decoder));\n break;\n\n case MessageType.SyncStatus:\n this.applySyncStatusMessage(provider, readVarInt(message.decoder) === 1);\n break;\n\n case MessageType.CLOSE:\n // eslint-disable-next-line no-case-declarations\n const event: CloseEvent = {\n code: 1000,\n reason: readVarString(message.decoder),\n // @ts-ignore\n target: provider.configuration.websocketProvider.webSocket!,\n type: \"close\",\n };\n provider.onClose();\n provider.configuration.onClose({ event });\n provider.forwardClose({ event });\n break;\n\n default:\n throw new Error(`Can’t apply message of unknown type: ${type}`);\n }\n\n // Reply\n if (message.length() > emptyMessageLength + 1) {\n // length of documentName (considered in emptyMessageLength plus length of yjs sync type, set in applySyncMessage)\n // @ts-ignore\n provider.send(OutgoingMessage, { encoder: message.encoder });\n }\n }\n\n private applySyncMessage(provider: AbracadabraBaseProvider, emitSynced: boolean) {\n const { message } = this;\n\n message.writeVarUint(MessageType.Sync);\n\n // Apply update\n const syncMessageType = readSyncMessage(\n message.decoder,\n message.encoder,\n provider.document,\n provider,\n );\n\n // Synced once we receive Step2\n if (emitSynced && syncMessageType === messageYjsSyncStep2) {\n provider.synced = true;\n }\n }\n\n applySyncStatusMessage(provider: AbracadabraBaseProvider, applied: boolean) {\n if (applied) {\n provider.decrementUnsyncedChanges();\n }\n }\n\n private applyAwarenessMessage(provider: AbracadabraBaseProvider) {\n if (!provider.awareness) return;\n\n const { message } = this;\n\n awarenessProtocol.applyAwarenessUpdate(\n provider.awareness,\n message.readVarUint8Array(),\n provider,\n );\n }\n\n private applyAuthMessage(provider: AbracadabraBaseProvider) {\n const { message } = this;\n\n readAuthMessage(\n message.decoder,\n provider.sendToken.bind(provider),\n provider.permissionDeniedHandler.bind(provider),\n provider.authenticatedHandler.bind(provider),\n );\n }\n\n private applyQueryAwarenessMessage(provider: AbracadabraBaseProvider) {\n if (!provider.awareness) return;\n\n const { message } = this;\n\n message.writeVarUint(MessageType.Awareness);\n message.writeVarUint8Array(\n awarenessProtocol.encodeAwarenessUpdate(\n provider.awareness,\n Array.from(provider.awareness.getStates().keys()),\n ),\n );\n }\n}\n","import type { Encoder } from \"lib0/encoding\";\nimport { toUint8Array } from \"lib0/encoding\";\nimport type { ConstructableOutgoingMessage } from \"./types.ts\";\n\nexport class MessageSender {\n\tencoder: Encoder;\n\n\tmessage: any;\n\n\tconstructor(Message: ConstructableOutgoingMessage, args: any = {}) {\n\t\tthis.message = new Message();\n\t\tthis.encoder = this.message.get(args);\n\t}\n\n\tcreate() {\n\t\treturn toUint8Array(this.encoder);\n\t}\n\n\tsend(webSocket: any) {\n\t\twebSocket?.send(this.create());\n\t}\n}\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport { writeAuthentication } from \"../auth.ts\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class AuthenticationMessage extends OutgoingMessage {\n type = MessageType.Auth;\n\n description = \"Authentication\";\n\n get(args: Partial<OutgoingMessageArguments>) {\n if (typeof args.token === \"undefined\") {\n throw new Error(\"The authentication message requires `token` as an argument.\");\n }\n\n writeVarString(this.encoder, args.documentName!);\n writeVarUint(this.encoder, this.type);\n writeAuthentication(this.encoder, args.token);\n\n return this.encoder;\n }\n}\n","import * as encoding from \"lib0/encoding\";\nimport { encodeAwarenessUpdate } from \"y-protocols/awareness\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class AwarenessMessage extends OutgoingMessage {\n\ttype = MessageType.Awareness;\n\n\tdescription = \"Awareness states update\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tif (typeof args.awareness === \"undefined\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"The awareness message requires awareness as an argument\",\n\t\t\t);\n\t\t}\n\n\t\tif (typeof args.clients === \"undefined\") {\n\t\t\tthrow new Error(\"The awareness message requires clients as an argument\");\n\t\t}\n\n\t\tencoding.writeVarString(this.encoder, args.documentName!);\n\t\tencoding.writeVarUint(this.encoder, this.type);\n\n\t\tlet awarenessUpdate;\n\t\tif (args.states === undefined) {\n\t\t\tawarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients);\n\t\t} else {\n\t\t\tawarenessUpdate = encodeAwarenessUpdate(\n\t\t\t\targs.awareness,\n\t\t\t\targs.clients,\n\t\t\t\targs.states,\n\t\t\t);\n\t\t}\n\n\t\tencoding.writeVarUint8Array(this.encoder, awarenessUpdate);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class StatelessMessage extends OutgoingMessage {\n\ttype = MessageType.Stateless;\n\n\tdescription = \"A stateless message\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\twriteVarString(this.encoder, args.documentName!);\n\t\twriteVarUint(this.encoder, this.type);\n\t\twriteVarString(this.encoder, args.payload ?? \"\");\n\n\t\treturn this.encoder;\n\t}\n}\n","import * as encoding from \"lib0/encoding\";\nimport * as syncProtocol from \"y-protocols/sync\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class SyncStepOneMessage extends OutgoingMessage {\n\ttype = MessageType.Sync;\n\n\tdescription = \"First sync step\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tif (typeof args.document === \"undefined\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"The sync step one message requires document as an argument\",\n\t\t\t);\n\t\t}\n\n\t\tencoding.writeVarString(this.encoder, args.documentName!);\n\t\tencoding.writeVarUint(this.encoder, this.type);\n\t\tsyncProtocol.writeSyncStep1(this.encoder, args.document);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport { writeUpdate } from \"y-protocols/sync\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class UpdateMessage extends OutgoingMessage {\n\ttype = MessageType.Sync;\n\n\tdescription = \"A document update\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\twriteVarString(this.encoder, args.documentName!);\n\t\twriteVarUint(this.encoder, this.type);\n\n\t\twriteUpdate(this.encoder, args.update);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { awarenessStatesToArray } from \"./awarenessStatesToArray.ts\";\nimport type { Event, MessageEvent } from \"ws\";\nimport { Awareness, removeAwarenessStates } from \"y-protocols/awareness\";\nimport * as Y from \"yjs\";\nimport EventEmitter from \"./EventEmitter.ts\";\nimport type { CompleteAbracadabraWSConfiguration } from \"./AbracadabraWS.ts\";\nimport { AbracadabraWS } from \"./AbracadabraWS.ts\";\nimport { IncomingMessage } from \"./IncomingMessage.ts\";\nimport { MessageReceiver } from \"./MessageReceiver.ts\";\nimport { MessageSender } from \"./MessageSender.ts\";\nimport { AuthenticationMessage } from \"./OutgoingMessages/AuthenticationMessage.ts\";\nimport { AwarenessMessage } from \"./OutgoingMessages/AwarenessMessage.ts\";\nimport { StatelessMessage } from \"./OutgoingMessages/StatelessMessage.ts\";\nimport { SyncStepOneMessage } from \"./OutgoingMessages/SyncStepOneMessage.ts\";\nimport { UpdateMessage } from \"./OutgoingMessages/UpdateMessage.ts\";\nimport type {\n AuthorizedScope,\n ConstructableOutgoingMessage,\n onAuthenticatedParameters,\n onAuthenticationFailedParameters,\n onAwarenessChangeParameters,\n onAwarenessUpdateParameters,\n onCloseParameters,\n onDisconnectParameters,\n onMessageParameters,\n onOpenParameters,\n onOutgoingMessageParameters,\n onStatelessParameters,\n onStatusParameters,\n onSyncedParameters,\n onUnsyncedChangesParameters,\n} from \"./types.ts\";\n\nexport type AbracadabraBaseProviderConfiguration = Required<\n Pick<CompleteAbracadabraBaseProviderConfiguration, \"name\">\n> &\n Partial<CompleteAbracadabraBaseProviderConfiguration> &\n (\n | (Required<Pick<CompleteAbracadabraWSConfiguration, \"url\">> &\n Partial<Pick<CompleteAbracadabraWSConfiguration, \"preserveTrailingSlash\">>)\n | Required<Pick<CompleteAbracadabraBaseProviderConfiguration, \"websocketProvider\">>\n );\n\n/** @deprecated Use AbracadabraBaseProviderConfiguration */\nexport type HocuspocusProviderConfiguration = AbracadabraBaseProviderConfiguration;\n\nexport interface CompleteAbracadabraBaseProviderConfiguration {\n /**\n * The identifier/name of your document\n */\n name: string;\n /**\n * The actual Y.js document\n */\n document: Y.Doc;\n\n /**\n * An Awareness instance to keep the presence state of all clients.\n *\n * You can disable sharing awareness information by passing `null`.\n * Note that having no awareness information shared across all connections will break our ping checks\n * and thus trigger reconnects. You should always have at least one Provider with enabled awareness per\n * socket connection, or ensure that the Provider receives messages before running into `AbracadabraWS.messageReconnectTimeout`.\n */\n awareness: Awareness | null;\n\n /**\n * A token that's sent to the backend for authentication purposes.\n */\n token: string | (() => string) | (() => Promise<string>) | null;\n\n /**\n * Abracadabra websocket provider\n */\n websocketProvider: AbracadabraWS;\n\n /**\n * Force syncing the document in the defined interval.\n */\n forceSyncInterval: false | number;\n\n onAuthenticated: (data: onAuthenticatedParameters) => void;\n onAuthenticationFailed: (data: onAuthenticationFailedParameters) => void;\n onRateLimited: () => void;\n onOpen: (data: onOpenParameters) => void;\n onConnect: () => void;\n onStatus: (data: onStatusParameters) => void;\n onMessage: (data: onMessageParameters) => void;\n onOutgoingMessage: (data: onOutgoingMessageParameters) => void;\n onSynced: (data: onSyncedParameters) => void;\n onDisconnect: (data: onDisconnectParameters) => void;\n onClose: (data: onCloseParameters) => void;\n onDestroy: () => void;\n onAwarenessUpdate: (data: onAwarenessUpdateParameters) => void;\n onAwarenessChange: (data: onAwarenessChangeParameters) => void;\n onStateless: (data: onStatelessParameters) => void;\n onUnsyncedChanges: (data: onUnsyncedChangesParameters) => void;\n}\n\n/** @deprecated Use CompleteAbracadabraBaseProviderConfiguration */\nexport type CompleteHocuspocusProviderConfiguration = CompleteAbracadabraBaseProviderConfiguration;\n\nexport class AwarenessError extends Error {\n code = 1001;\n}\n\nexport class AbracadabraBaseProvider extends EventEmitter {\n public configuration: CompleteAbracadabraBaseProviderConfiguration = {\n name: \"\",\n // @ts-ignore\n document: undefined,\n // @ts-ignore\n awareness: undefined,\n token: null,\n forceSyncInterval: false,\n onAuthenticated: () => null,\n onAuthenticationFailed: () => null,\n onRateLimited: () => null,\n onOpen: () => null,\n onConnect: () => null,\n onMessage: () => null,\n onOutgoingMessage: () => null,\n onSynced: () => null,\n onStatus: () => null,\n onDisconnect: () => null,\n onClose: () => null,\n onDestroy: () => null,\n onAwarenessUpdate: () => null,\n onAwarenessChange: () => null,\n onStateless: () => null,\n onUnsyncedChanges: () => null,\n };\n\n isSynced = false;\n\n unsyncedChanges = 0;\n\n isAuthenticated = false;\n\n authorizedScope: AuthorizedScope | undefined = undefined;\n\n // @internal\n manageSocket = false;\n\n private _isAttached = false;\n\n intervals: any = {\n forceSync: null,\n };\n\n constructor(configuration: AbracadabraBaseProviderConfiguration) {\n super();\n this.setConfiguration(configuration);\n\n this.configuration.document = configuration.document ? configuration.document : new Y.Doc();\n this.configuration.awareness =\n configuration.awareness !== undefined\n ? configuration.awareness\n : new Awareness(this.document);\n\n this.on(\"open\", this.configuration.onOpen);\n this.on(\"message\", this.configuration.onMessage);\n this.on(\"outgoingMessage\", this.configuration.onOutgoingMessage);\n this.on(\"synced\", this.configuration.onSynced);\n this.on(\"destroy\", this.configuration.onDestroy);\n this.on(\"awarenessUpdate\", this.configuration.onAwarenessUpdate);\n this.on(\"awarenessChange\", this.configuration.onAwarenessChange);\n this.on(\"stateless\", this.configuration.onStateless);\n this.on(\"unsyncedChanges\", this.configuration.onUnsyncedChanges);\n\n this.on(\"authenticated\", this.configuration.onAuthenticated);\n this.on(\"authenticationFailed\", this.configuration.onAuthenticationFailed);\n this.on(\"rateLimited\", this.configuration.onRateLimited);\n\n this.awareness?.on(\"update\", () => {\n this.emit(\"awarenessUpdate\", {\n states: awarenessStatesToArray(this.awareness!.getStates()),\n });\n });\n\n this.awareness?.on(\"change\", () => {\n this.emit(\"awarenessChange\", {\n states: awarenessStatesToArray(this.awareness!.getStates()),\n });\n });\n\n this.document.on(\"update\", this.boundDocumentUpdateHandler);\n this.awareness?.on(\"update\", this.boundAwarenessUpdateHandler);\n\n this.registerEventListeners();\n\n if (\n this.configuration.forceSyncInterval &&\n typeof this.configuration.forceSyncInterval === \"number\"\n ) {\n this.intervals.forceSync = setInterval(\n this.forceSync.bind(this),\n this.configuration.forceSyncInterval,\n );\n }\n\n if (this.manageSocket) {\n this.attach();\n }\n }\n\n boundDocumentUpdateHandler = this.documentUpdateHandler.bind(this);\n\n boundAwarenessUpdateHandler = this.awarenessUpdateHandler.bind(this);\n\n boundPageHide = this.pageHide.bind(this);\n\n boundOnOpen = this.onOpen.bind(this);\n\n boundOnClose = this.onClose.bind(this);\n\n forwardConnect = () => this.emit(\"connect\");\n\n forwardStatus = (e: onStatusParameters) => this.emit(\"status\", e);\n\n forwardClose = (e: onCloseParameters) => this.emit(\"close\", e);\n\n forwardDisconnect = (e: onDisconnectParameters) => this.emit(\"disconnect\", e);\n\n forwardDestroy = () => this.emit(\"destroy\");\n\n forwardRateLimited = () => this.emit(\"rateLimited\");\n\n public setConfiguration(configuration: Partial<AbracadabraBaseProviderConfiguration> = {}): void {\n if (!configuration.websocketProvider) {\n this.manageSocket = true;\n this.configuration.websocketProvider = new AbracadabraWS(\n configuration as CompleteAbracadabraWSConfiguration,\n );\n }\n\n this.configuration = { ...this.configuration, ...configuration };\n }\n\n get document() {\n return this.configuration.document;\n }\n\n public get isAttached() {\n return this._isAttached;\n }\n\n get awareness() {\n return this.configuration.awareness;\n }\n\n get hasUnsyncedChanges(): boolean {\n return this.unsyncedChanges > 0;\n }\n\n private resetUnsyncedChanges() {\n this.unsyncedChanges = 1;\n this.emit(\"unsyncedChanges\", { number: this.unsyncedChanges });\n }\n\n incrementUnsyncedChanges() {\n this.unsyncedChanges += 1;\n this.emit(\"unsyncedChanges\", { number: this.unsyncedChanges });\n }\n\n decrementUnsyncedChanges() {\n if (this.unsyncedChanges > 0) {\n this.unsyncedChanges -= 1;\n }\n\n if (this.unsyncedChanges === 0) {\n this.synced = true;\n }\n\n this.emit(\"unsyncedChanges\", { number: this.unsyncedChanges });\n }\n\n forceSync() {\n this.resetUnsyncedChanges();\n\n this.send(SyncStepOneMessage, {\n document: this.document,\n documentName: this.configuration.name,\n });\n }\n\n pageHide() {\n if (this.awareness) {\n removeAwarenessStates(this.awareness, [this.document.clientID], \"page hide\");\n }\n }\n\n registerEventListeners() {\n if (typeof window === \"undefined\" || !(\"addEventListener\" in window)) {\n return;\n }\n\n window.addEventListener(\"pagehide\", this.boundPageHide);\n }\n\n sendStateless(payload: string) {\n this.send(StatelessMessage, {\n documentName: this.configuration.name,\n payload,\n });\n }\n\n async sendToken() {\n let token: string | null;\n try {\n token = await this.getToken();\n } catch (error) {\n this.permissionDeniedHandler(`Failed to get token during sendToken(): ${error}`);\n return;\n }\n\n this.send(AuthenticationMessage, {\n token: token ?? \"\",\n documentName: this.configuration.name,\n });\n }\n\n documentUpdateHandler(update: Uint8Array, origin: any) {\n if (origin === this) {\n return;\n }\n\n this.incrementUnsyncedChanges();\n this.send(UpdateMessage, { update, documentName: this.configuration.name });\n }\n\n awarenessUpdateHandler({ added, updated, removed }: any, origin: any) {\n const changedClients = added.concat(updated).concat(removed);\n\n this.send(AwarenessMessage, {\n awareness: this.awareness,\n clients: changedClients,\n documentName: this.configuration.name,\n });\n }\n\n /**\n * Indicates whether a first handshake with the server has been established\n *\n * Note: this does not mean all updates from the client have been persisted to the backend. For this,\n * use `hasUnsyncedChanges`.\n */\n get synced(): boolean {\n return this.isSynced;\n }\n\n set synced(state) {\n if (this.isSynced === state) {\n return;\n }\n\n this.isSynced = state;\n\n if (state) {\n this.emit(\"synced\", { state });\n }\n }\n\n receiveStateless(payload: string) {\n this.emit(\"stateless\", { payload });\n }\n\n // not needed, but provides backward compatibility with e.g. lexical/yjs\n async connect() {\n if (this.manageSocket) {\n return this.configuration.websocketProvider.connect();\n }\n\n console.warn(\n \"AbracadabraBaseProvider::connect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.\",\n );\n }\n\n disconnect() {\n if (this.manageSocket) {\n return this.configuration.websocketProvider.disconnect();\n }\n\n console.warn(\n \"AbracadabraBaseProvider::disconnect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.\",\n );\n }\n\n async onOpen(event: Event) {\n this.isAuthenticated = false;\n\n this.emit(\"open\", { event });\n await this.sendToken();\n this.startSync();\n }\n\n async getToken() {\n if (typeof this.configuration.token === \"function\") {\n const token = await this.configuration.token();\n return token;\n }\n\n return this.configuration.token;\n }\n\n startSync() {\n this.resetUnsyncedChanges();\n\n this.send(SyncStepOneMessage, {\n document: this.document,\n documentName: this.configuration.name,\n });\n\n if (this.awareness && this.awareness.getLocalState() !== null) {\n this.send(AwarenessMessage, {\n awareness: this.awareness,\n clients: [this.document.clientID],\n documentName: this.configuration.name,\n });\n }\n }\n\n send(message: ConstructableOutgoingMessage, args: any) {\n if (!this._isAttached) return;\n\n const messageSender = new MessageSender(message, args);\n\n this.emit(\"outgoingMessage\", { message: messageSender.message });\n messageSender.send(this.configuration.websocketProvider);\n }\n\n onMessage(event: MessageEvent) {\n const message = new IncomingMessage(event.data);\n\n const documentName = message.readVarString();\n\n message.writeVarString(documentName);\n\n this.emit(\"message\", { event, message: new IncomingMessage(event.data) });\n\n new MessageReceiver(message).apply(this, true);\n }\n\n onClose() {\n this.isAuthenticated = false;\n this.synced = false;\n\n // update awareness (all users except local left)\n if (this.awareness) {\n removeAwarenessStates(\n this.awareness,\n Array.from(this.awareness.getStates().keys()).filter(\n (client) => client !== this.document.clientID,\n ),\n this,\n );\n }\n }\n\n destroy() {\n this.emit(\"destroy\");\n\n if (this.intervals.forceSync) {\n clearInterval(this.intervals.forceSync);\n }\n\n if (this.awareness) {\n removeAwarenessStates(this.awareness, [this.document.clientID], \"provider destroy\");\n this.awareness.off(\"update\", this.boundAwarenessUpdateHandler);\n this.awareness.destroy();\n }\n\n this.document.off(\"update\", this.boundDocumentUpdateHandler);\n\n this.removeAllListeners();\n\n this.detach();\n\n if (this.manageSocket) {\n this.configuration.websocketProvider.destroy();\n }\n\n if (typeof window === \"undefined\" || !(\"removeEventListener\" in window)) {\n return;\n }\n\n window.removeEventListener(\"pagehide\", this.boundPageHide);\n }\n\n detach() {\n this.configuration.websocketProvider.off(\"connect\", this.configuration.onConnect);\n this.configuration.websocketProvider.off(\"connect\", this.forwardConnect);\n\n this.configuration.websocketProvider.off(\"status\", this.forwardStatus);\n this.configuration.websocketProvider.off(\"status\", this.configuration.onStatus);\n\n this.configuration.websocketProvider.off(\"open\", this.boundOnOpen);\n this.configuration.websocketProvider.off(\"close\", this.boundOnClose);\n this.configuration.websocketProvider.off(\"close\", this.configuration.onClose);\n this.configuration.websocketProvider.off(\"close\", this.forwardClose);\n this.configuration.websocketProvider.off(\"disconnect\", this.configuration.onDisconnect);\n this.configuration.websocketProvider.off(\"disconnect\", this.forwardDisconnect);\n this.configuration.websocketProvider.off(\"destroy\", this.configuration.onDestroy);\n this.configuration.websocketProvider.off(\"destroy\", this.forwardDestroy);\n\n this.configuration.websocketProvider.off(\"rateLimited\", this.forwardRateLimited);\n\n this.configuration.websocketProvider.detach(this);\n\n this._isAttached = false;\n }\n\n attach() {\n if (this._isAttached) return;\n\n this.configuration.websocketProvider.on(\"connect\", this.configuration.onConnect);\n this.configuration.websocketProvider.on(\"connect\", this.forwardConnect);\n\n this.configuration.websocketProvider.on(\"status\", this.configuration.onStatus);\n this.configuration.websocketProvider.on(\"status\", this.forwardStatus);\n\n this.configuration.websocketProvider.on(\"open\", this.boundOnOpen);\n\n this.configuration.websocketProvider.on(\"close\", this.boundOnClose);\n this.configuration.websocketProvider.on(\"close\", this.configuration.onClose);\n this.configuration.websocketProvider.on(\"close\", this.forwardClose);\n\n this.configuration.websocketProvider.on(\"disconnect\", this.configuration.onDisconnect);\n this.configuration.websocketProvider.on(\"disconnect\", this.forwardDisconnect);\n\n this.configuration.websocketProvider.on(\"destroy\", this.configuration.onDestroy);\n this.configuration.websocketProvider.on(\"destroy\", this.forwardDestroy);\n\n this.configuration.websocketProvider.on(\"rateLimited\", this.forwardRateLimited);\n\n this.configuration.websocketProvider.attach(this);\n\n this._isAttached = true;\n }\n\n permissionDeniedHandler(reason: string) {\n this.emit(\"authenticationFailed\", { reason });\n this.isAuthenticated = false;\n }\n\n authenticatedHandler(scope: string) {\n this.isAuthenticated = true;\n this.authorizedScope = scope as AuthorizedScope;\n\n this.emit(\"authenticated\", { scope });\n }\n\n setAwarenessField(key: string, value: any) {\n if (!this.awareness) {\n throw new AwarenessError(\n `Cannot set awareness field \"${key}\" to ${JSON.stringify(value)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`,\n );\n }\n this.awareness.setLocalStateField(key, value);\n }\n}\n\n/** @deprecated Use AbracadabraBaseProvider */\nexport const HocuspocusProvider = AbracadabraBaseProvider;\n/** @deprecated Use AbracadabraBaseProvider */\nexport type HocuspocusProvider = AbracadabraBaseProvider;\n","/**\n * IndexedDB-backed offline store for a single Abracadabra document.\n *\n * Responsibilities:\n * - Persist CRDT updates locally so they survive page refreshes / network loss.\n * - Store the last-known state vector for fast reconnect diffs.\n * - Store a permission snapshot so the UI can gate writes without a network round-trip.\n * - Queue subdoc registration events created while offline.\n * - Store a full document snapshot so the app can load content without a server connection.\n *\n * Falls back to a silent no-op when IndexedDB is unavailable (e.g. SSR / Node.js).\n *\n * Database key is scoped by server origin to prevent cross-server data contamination\n * when the same docId is used on multiple servers.\n */\n\nexport interface PendingSubdoc {\n\tchildId: string;\n\tparentId: string;\n\tcreatedAt: number;\n}\n\nconst DB_VERSION = 2;\n\nfunction idbAvailable(): boolean {\n\treturn typeof globalThis !== \"undefined\" && \"indexedDB\" in globalThis;\n}\n\nfunction openDb(storeKey: string): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = globalThis.indexedDB.open(`abracadabra:${storeKey}`, DB_VERSION);\n\n\t\treq.onupgradeneeded = (event) => {\n\t\t\tconst db = (event.target as IDBOpenDBRequest).result;\n\n\t\t\tif (!db.objectStoreNames.contains(\"updates\")) {\n\t\t\t\tdb.createObjectStore(\"updates\", { autoIncrement: true });\n\t\t\t}\n\t\t\tif (!db.objectStoreNames.contains(\"meta\")) {\n\t\t\t\tdb.createObjectStore(\"meta\");\n\t\t\t}\n\t\t\tif (!db.objectStoreNames.contains(\"subdoc_queue\")) {\n\t\t\t\tdb.createObjectStore(\"subdoc_queue\", { keyPath: \"childId\" });\n\t\t\t}\n\t\t\t// v2: full document snapshot store\n\t\t\tif (!db.objectStoreNames.contains(\"doc_state\")) {\n\t\t\t\tdb.createObjectStore(\"doc_state\");\n\t\t\t}\n\t\t};\n\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nfunction txPromise<T>(\n\tstore: IDBObjectStore,\n\trequest: IDBRequest<T>,\n): Promise<T> {\n\treturn new Promise((resolve, reject) => {\n\t\trequest.onsuccess = () => resolve(request.result);\n\t\trequest.onerror = () => reject(request.error);\n\t});\n}\n\nexport class OfflineStore {\n\tprivate storeKey: string;\n\tprivate db: IDBDatabase | null = null;\n\n\t/**\n\t * @param docId The document UUID.\n\t * @param serverOrigin Hostname of the server (e.g. \"abra.cou.sh\").\n\t * When provided the IndexedDB database is namespaced\n\t * per-server, preventing cross-server data contamination.\n\t */\n\tconstructor(docId: string, serverOrigin?: string) {\n\t\tthis.storeKey = serverOrigin ? `${serverOrigin}/${docId}` : docId;\n\t}\n\n\tprivate dbPromise: Promise<IDBDatabase | null> | null = null;\n\n\tprivate getDb(): Promise<IDBDatabase | null> {\n\t\tif (!idbAvailable()) return Promise.resolve(null);\n\t\tif (!this.dbPromise) {\n\t\t\t// Cache the promise so concurrent callers share a single open operation.\n\t\t\tthis.dbPromise = openDb(this.storeKey).catch(() => null).then(db => {\n\t\t\t\tthis.db = db;\n\t\t\t\treturn db;\n\t\t\t});\n\t\t}\n\t\treturn this.dbPromise;\n\t}\n\n\t// ── Pending (unsynced) updates ────────────────────────────────────────────\n\n\tasync persistUpdate(update: Uint8Array): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"updates\", \"readwrite\");\n\t\tconst store = tx.objectStore(\"updates\");\n\t\tawait txPromise(store, store.add(update));\n\t}\n\n\tasync getPendingUpdates(): Promise<Uint8Array[]> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"updates\", \"readonly\");\n\t\t\tconst store = tx.objectStore(\"updates\");\n\t\t\tconst req = store.getAll();\n\t\t\treq.onsuccess = () => resolve(req.result as Uint8Array[]);\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\tasync clearPendingUpdates(): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"updates\", \"readwrite\");\n\t\tawait txPromise(tx.objectStore(\"updates\"), tx.objectStore(\"updates\").clear());\n\t}\n\n\t// ── Full document snapshot ────────────────────────────────────────────────\n\n\t/**\n\t * Persist a full Y.js state snapshot (Y.encodeStateAsUpdate output).\n\t * Replaces any previously stored snapshot.\n\t */\n\tasync saveDocSnapshot(snapshot: Uint8Array): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"doc_state\", \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(\"doc_state\"),\n\t\t\ttx.objectStore(\"doc_state\").put(snapshot, \"snapshot\"),\n\t\t);\n\t}\n\n\t/**\n\t * Retrieve the stored full document snapshot, or null if none exists.\n\t */\n\tasync getDocSnapshot(): Promise<Uint8Array | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(\"doc_state\", \"readonly\");\n\t\tconst result = await txPromise<Uint8Array | undefined>(\n\t\t\ttx.objectStore(\"doc_state\"),\n\t\t\ttx.objectStore(\"doc_state\").get(\"snapshot\"),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\t// ── State vector ─────────────────────────────────────────────────────────\n\n\tasync getStateVector(): Promise<Uint8Array | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(\"meta\", \"readonly\");\n\t\tconst result = await txPromise<Uint8Array | undefined>(\n\t\t\ttx.objectStore(\"meta\"),\n\t\t\ttx.objectStore(\"meta\").get(\"sv\"),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\tasync saveStateVector(sv: Uint8Array): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"meta\", \"readwrite\");\n\t\tawait txPromise(tx.objectStore(\"meta\"), tx.objectStore(\"meta\").put(sv, \"sv\"));\n\t}\n\n\t// ── Permission snapshot ──────────────────────────────────────────────────\n\n\tasync getPermissionSnapshot(): Promise<string | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(\"meta\", \"readonly\");\n\t\tconst result = await txPromise<string | undefined>(\n\t\t\ttx.objectStore(\"meta\"),\n\t\t\ttx.objectStore(\"meta\").get(\"role\"),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\tasync savePermissionSnapshot(role: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"meta\", \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(\"meta\"),\n\t\t\ttx.objectStore(\"meta\").put(role, \"role\"),\n\t\t);\n\t}\n\n\t// ── Subdoc registration queue ─────────────────────────────────────────────\n\n\tasync queueSubdoc(entry: PendingSubdoc): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"subdoc_queue\", \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(\"subdoc_queue\"),\n\t\t\ttx.objectStore(\"subdoc_queue\").put(entry),\n\t\t);\n\t}\n\n\tasync getPendingSubdocs(): Promise<PendingSubdoc[]> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"subdoc_queue\", \"readonly\");\n\t\t\tconst req = tx.objectStore(\"subdoc_queue\").getAll();\n\t\t\treq.onsuccess = () => resolve(req.result as PendingSubdoc[]);\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\tasync removeSubdocFromQueue(childId: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"subdoc_queue\", \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(\"subdoc_queue\"),\n\t\t\ttx.objectStore(\"subdoc_queue\").delete(childId),\n\t\t);\n\t}\n\n\t// ── Generic meta accessors ────────────────────────────────────────────────\n\n\tasync getMeta(key: string): Promise<string | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(\"meta\", \"readonly\");\n\t\tconst result = await txPromise<string | undefined>(\n\t\t\ttx.objectStore(\"meta\"),\n\t\t\ttx.objectStore(\"meta\").get(key),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\tasync setMeta(key: string, value: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"meta\", \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(\"meta\"),\n\t\t\ttx.objectStore(\"meta\").put(value, key),\n\t\t);\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\tdestroy() {\n\t\tthis.db?.close();\n\t\tthis.db = null;\n\t}\n}\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\n/**\n * Registers a new subdocument with the Abracadabra server.\n *\n * Wire format (consumed by handle_subdoc in sync.rs):\n * [ParentDocName: VarString] [MSG_SUBDOC(4): VarUint] [childDocumentName: VarString]\n *\n * The server responds with a MSG_STATELESS JSON frame:\n * { type: \"subdoc_registered\", child_id, parent_id }\n * which AbracadabraProvider intercepts in receiveStateless().\n */\nexport class SubdocMessage extends OutgoingMessage {\n\ttype = MessageType.Subdoc;\n\n\tdescription = \"SubdocRegistration\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tif (!args.documentName) {\n\t\t\tthrow new Error(\"SubdocMessage requires `documentName` (parent id).\");\n\t\t}\n\t\tif (!args.childDocumentName) {\n\t\t\tthrow new Error(\"SubdocMessage requires `childDocumentName`.\");\n\t\t}\n\n\t\twriteVarString(this.encoder, args.documentName);\n\t\twriteVarUint(this.encoder, this.type);\n\t\twriteVarString(this.encoder, args.childDocumentName);\n\n\t\treturn this.encoder;\n\t}\n}\n","import * as Y from \"yjs\";\nimport { AbracadabraBaseProvider } from \"./AbracadabraBaseProvider.ts\";\nimport type { AbracadabraBaseProviderConfiguration } from \"./AbracadabraBaseProvider.ts\";\nimport type { AbracadabraWS } from \"./AbracadabraWS.ts\";\nimport { OfflineStore } from \"./OfflineStore.ts\";\nimport { SubdocMessage } from \"./OutgoingMessages/SubdocMessage.ts\";\nimport { UpdateMessage } from \"./OutgoingMessages/UpdateMessage.ts\";\nimport type {\n\tCryptoIdentity,\n\tEffectiveRole,\n\tonSubdocRegisteredParameters,\n\tonSubdocLoadedParameters,\n} from \"./types.ts\";\nimport { AuthenticationMessage } from \"./OutgoingMessages/AuthenticationMessage.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport type { DocKeyManager } from \"./DocKeyManager.ts\";\nimport type { CryptoIdentityKeystore } from \"./CryptoIdentityKeystore.ts\";\n\nexport interface AbracadabraProviderConfiguration\n\textends Omit<AbracadabraBaseProviderConfiguration, \"url\" | \"websocketProvider\"> {\n\t/**\n\t * Subdocument loading strategy.\n\t * - \"lazy\" (default) – child providers are created only when explicitly requested.\n\t * - \"eager\" – all children returned by the server on connect are loaded automatically.\n\t */\n\tsubdocLoading?: \"lazy\" | \"eager\";\n\n\t/** Called when the server confirms a subdoc registration. */\n\tonSubdocRegistered?: (data: onSubdocRegisteredParameters) => void;\n\n\t/** Called when a child AbracadabraProvider has been created and attached. */\n\tonSubdocLoaded?: (data: onSubdocLoadedParameters) => void;\n\n\t/**\n\t * Disable the IndexedDB offline store. Useful for server-side rendering\n\t * or testing environments that lack IndexedDB.\n\t */\n\tdisableOfflineStore?: boolean;\n\n\t/**\n\t * Identity for passwordless crypto auth (Model B multi-key).\n\t * Mutually exclusive with token.\n\t */\n\tcryptoIdentity?: CryptoIdentity | (() => Promise<CryptoIdentity>);\n\n\t/**\n\t * Signs a base64url challenge and returns a base64url signature.\n\t * Required when cryptoIdentity is set.\n\t */\n\tsignChallenge?: (challenge: string) => Promise<string>;\n\n\t/**\n\t * AbracadabraClient instance for REST API access.\n\t * When provided, the provider automatically derives the WebSocket URL\n\t * and token from the client (unless explicitly overridden).\n\t */\n\tclient?: AbracadabraClient;\n\n\t/** WebSocket URL. Derived from client.wsUrl if client is provided. */\n\turl?: string;\n\n\t/** DocKeyManager for E2E/CSE encryption key management. */\n\tdocKeyManager?: DocKeyManager;\n\t/** Keystore for X25519 key derivation. */\n\tkeystore?: CryptoIdentityKeystore;\n\n\t/** Shared WebSocket connection (use when multiplexing multiple root documents). */\n\twebsocketProvider?: AbracadabraWS;\n}\n\n/** Validate that a string is a UUID acceptable by the server's DocId parser. */\nfunction isValidDocId(id: string): boolean {\n\treturn /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id);\n}\n\n/**\n * AbracadabraProvider extends AbracadabraBaseProvider with:\n *\n * 1. Subdocument lifecycle – intercepts Y.Doc subdoc events and syncs them\n * with the server via MSG_SUBDOC (4) frames. Child documents get their\n * own AbracadabraProvider instances sharing the same WebSocket connection.\n *\n * 2. Offline-first – persists CRDT updates to IndexedDB so they survive\n * page reloads and network outages. On startup, the last saved document\n * snapshot is applied immediately so the UI is usable without a server\n * connection. On reconnect, pending updates are flushed and a fresh\n * snapshot is saved.\n *\n * 3. Server-scoped storage – the IndexedDB database is keyed by server\n * hostname + docId, preventing cross-server data contamination when the\n * same docId is used on multiple servers.\n *\n * 4. Permission snapshotting – stores the resolved role locally so the UI\n * can gate write operations without a network round-trip. Role is\n * refreshed from the server on every reconnect.\n */\nexport class AbracadabraProvider extends AbracadabraBaseProvider {\n\tpublic effectiveRole: EffectiveRole = null;\n\n\tprivate _client: AbracadabraClient | null;\n\tprivate offlineStore: OfflineStore | null;\n\tprivate childProviders = new Map<string, AbracadabraProvider>();\n\tprivate pendingLoads = new Map<string, Promise<AbracadabraProvider>>();\n\tprivate subdocLoading: \"lazy\" | \"eager\";\n\n\tprivate abracadabraConfig: AbracadabraProviderConfiguration;\n\n\tprivate readonly boundHandleYSubdocsChange = this.handleYSubdocsChange.bind(this);\n\n\t/**\n\t * Resolves once the document has been pre-populated from the local\n\t * IndexedDB snapshot (if one exists). Await this before rendering UI\n\t * that depends on the document content — it resolves immediately when\n\t * the offline store is disabled or when no snapshot has been saved yet.\n\t */\n\tpublic readonly ready: Promise<void>;\n\n\tconstructor(configuration: AbracadabraProviderConfiguration) {\n\t\t// Derive URL and token from client when not explicitly set.\n\t\tconst resolved = { ...configuration } as AbracadabraBaseProviderConfiguration;\n\t\tconst client = configuration.client ?? null;\n\n\t\tif (client) {\n\t\t\tif (!resolved.url && !resolved.websocketProvider) {\n\t\t\t\t(resolved as any).url = client.wsUrl;\n\t\t\t}\n\t\t\tif (resolved.token === undefined && !configuration.cryptoIdentity) {\n\t\t\t\tresolved.token = () => client.token ?? \"\";\n\t\t\t}\n\t\t}\n\n\t\tsuper(resolved);\n\t\tthis._client = client;\n\t\tthis.abracadabraConfig = configuration;\n\t\tthis.subdocLoading = configuration.subdocLoading ?? \"lazy\";\n\n\t\tconst serverOrigin = AbracadabraProvider.deriveServerOrigin(configuration, client);\n\t\tthis.offlineStore = configuration.disableOfflineStore\n\t\t\t? null\n\t\t\t: new OfflineStore(configuration.name, serverOrigin);\n\n\t\tthis.on(\n\t\t\t\"subdocRegistered\",\n\t\t\tconfiguration.onSubdocRegistered ?? (() => null),\n\t\t);\n\t\tthis.on(\"subdocLoaded\", configuration.onSubdocLoaded ?? (() => null));\n\n\t\t// Intercept Y.Doc subdoc lifecycle events.\n\t\tthis.document.on(\"subdocs\", this.boundHandleYSubdocsChange);\n\n\t\t// Flush offline updates once we're back online and synced.\n\t\tthis.on(\"synced\", () => this.flushPendingUpdates());\n\n\t\t// Restore permission snapshot while offline.\n\t\tthis.restorePermissionSnapshot();\n\n\t\t// Pre-populate the Y.Doc from the local snapshot so the UI works offline.\n\t\tthis.ready = this._initFromOfflineStore();\n\t}\n\n\t// ── Server origin derivation ──────────────────────────────────────────────\n\n\t/**\n\t * Extract the server hostname from the provider configuration.\n\t * Used to namespace the IndexedDB key so docs from different servers\n\t * never share the same database.\n\t */\n\tprotected static deriveServerOrigin(\n\t\tconfig: AbracadabraProviderConfiguration,\n\t\tclient: AbracadabraClient | null,\n\t): string | undefined {\n\t\ttry {\n\t\t\tconst url =\n\t\t\t\tconfig.url ??\n\t\t\t\t(config.websocketProvider as AbracadabraWS | undefined)?.url ??\n\t\t\t\tclient?.wsUrl;\n\t\t\tif (url) return new URL(url).hostname;\n\t\t} catch {\n\t\t\t// Malformed URL — fall back to no scoping\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// ── Offline-first initialisation ──────────────────────────────────────────\n\n\t/**\n\t * Load the stored document snapshot (and any pending local edits) from\n\t * IndexedDB and apply them to the Y.Doc so the UI can render without a\n\t * server connection.\n\t *\n\t * Uses `this.offlineStore` as the Y.js update origin so that\n\t * `documentUpdateHandler` ignores these replayed updates and does not\n\t * attempt to re-persist or re-send them.\n\t */\n\tprivate async _initFromOfflineStore(): Promise<void> {\n\t\tif (!this.offlineStore) return;\n\n\t\t// Fetch snapshot and pending updates in parallel — each call opens the\n\t\t// IDB database, so running them concurrently roughly halves the latency.\n\t\tconst [snapshot, pending] = await Promise.all([\n\t\t\tthis.offlineStore.getDocSnapshot().catch(() => null),\n\t\t\tthis.offlineStore.getPendingUpdates().catch(() => []),\n\t\t]);\n\n\t\tif (snapshot) {\n\t\t\tY.applyUpdate(this.document, snapshot, this.offlineStore);\n\t\t}\n\t\tfor (const update of pending) {\n\t\t\tY.applyUpdate(this.document, update, this.offlineStore);\n\t\t}\n\t}\n\n\t// ── Auth / permission snapshot ────────────────────────────────────────────\n\n\toverride authenticatedHandler(scope: string) {\n\t\tsuper.authenticatedHandler(scope);\n\n\t\tconst roleMap: Record<string, import(\"./types.ts\").EffectiveRole> = {\n\t\t\tservice: \"service\",\n\t\t\tadmin: \"admin\",\n\t\t\towner: \"owner\",\n\t\t\teditor: \"editor\",\n\t\t\tviewer: \"viewer\",\n\t\t\t\"read-write\": \"editor\",\n\t\t\treadonly: \"viewer\",\n\t\t};\n\t\tthis.effectiveRole = roleMap[scope] ?? \"viewer\";\n\n\t\tthis.offlineStore?.savePermissionSnapshot(this.effectiveRole);\n\t}\n\n\t/**\n\t * Override sendToken to send a pubkey-only identity declaration instead of a\n\t * JWT when cryptoIdentity is configured.\n\t *\n\t * The public key is the sole identifier in the crypto auth handshake.\n\t * Username is decoupled from auth; it lives on the server as an immutable\n\t * internal field and is never sent in the challenge-response frames.\n\t */\n\toverride async sendToken() {\n\t\tconst { cryptoIdentity } = this.abracadabraConfig;\n\t\tif (cryptoIdentity) {\n\t\t\tconst id =\n\t\t\t\ttypeof cryptoIdentity === \"function\"\n\t\t\t\t\t? await cryptoIdentity()\n\t\t\t\t\t: cryptoIdentity;\n\t\t\tconst json = JSON.stringify({\n\t\t\t\ttype: \"identity\",\n\t\t\t\tpublicKey: id.publicKey,\n\t\t\t});\n\t\t\tthis.send(AuthenticationMessage, {\n\t\t\t\ttoken: json,\n\t\t\t\tdocumentName: this.configuration.name,\n\t\t\t});\n\t\t} else {\n\t\t\tawait super.sendToken();\n\t\t}\n\t}\n\n\t/** Handle an auth_challenge message from the server. */\n\tprivate async handleAuthChallenge(\n\t\tchallenge: string,\n\t\texpiresAt: number,\n\t): Promise<void> {\n\t\tconst { signChallenge, cryptoIdentity } = this.abracadabraConfig;\n\t\tif (!signChallenge || !cryptoIdentity) {\n\t\t\tthis.permissionDeniedHandler(\"No signChallenge callback configured\");\n\t\t\treturn;\n\t\t}\n\t\tif (Date.now() > expiresAt * 1000) {\n\t\t\tthis.permissionDeniedHandler(\"Challenge expired\");\n\t\t\treturn;\n\t\t}\n\t\tconst id =\n\t\t\ttypeof cryptoIdentity === \"function\"\n\t\t\t\t? await cryptoIdentity()\n\t\t\t\t: cryptoIdentity;\n\t\tconst signature = await signChallenge(challenge);\n\t\t// Proof frame sends only publicKey — username is fully decoupled from auth.\n\t\tconst proof = JSON.stringify({\n\t\t\ttype: \"proof\",\n\t\t\tpublicKey: id.publicKey,\n\t\t\tsignature,\n\t\t\tchallenge,\n\t\t});\n\t\tthis.send(AuthenticationMessage, {\n\t\t\ttoken: proof,\n\t\t\tdocumentName: this.configuration.name,\n\t\t});\n\t}\n\n\tprivate async restorePermissionSnapshot() {\n\t\tif (!this.offlineStore) return;\n\t\tconst role = await this.offlineStore.getPermissionSnapshot();\n\t\tif (role && !this.effectiveRole) {\n\t\t\tthis.effectiveRole = role as EffectiveRole;\n\t\t}\n\t}\n\n\tget canWrite(): boolean {\n\t\treturn this.effectiveRole != null && this.effectiveRole !== \"viewer\";\n\t}\n\n\t/** The AbracadabraClient instance for REST API access, if configured. */\n\tget client(): AbracadabraClient | null {\n\t\treturn this._client;\n\t}\n\n\t/** The OfflineStore instance, or null if offline storage is disabled. */\n\tget store(): OfflineStore | null {\n\t\treturn this.offlineStore;\n\t}\n\n\t// ── Stateless message interception ────────────────────────────────────────\n\n\t/**\n\t * Called when a MSG_STATELESS frame arrives from the server.\n\t * Abracadabra uses stateless frames to deliver subdoc confirmations\n\t * ({ type: \"subdoc_registered\", child_id, parent_id }).\n\t */\n\toverride receiveStateless(payload: string) {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(payload);\n\t\t} catch {\n\t\t\tsuper.receiveStateless(payload);\n\t\t\treturn;\n\t\t}\n\n\t\tconst msg = parsed as {\n\t\t\ttype?: string;\n\t\t\tchild_id?: string;\n\t\t\tparent_id?: string;\n\t\t\tchallenge?: string;\n\t\t\texpiresAt?: number;\n\t\t};\n\n\t\t// Intercept auth_challenge before subdoc handling.\n\t\tif (msg.type === \"auth_challenge\" && msg.challenge && msg.expiresAt) {\n\t\t\tthis.handleAuthChallenge(msg.challenge, msg.expiresAt).catch(() => null);\n\t\t\treturn;\n\t\t}\n\n\t\tif (msg.type === \"subdoc_registered\" && msg.child_id && msg.parent_id) {\n\t\t\tconst event: onSubdocRegisteredParameters = {\n\t\t\t\tchildId: msg.child_id,\n\t\t\t\tparentId: msg.parent_id,\n\t\t\t};\n\t\t\tthis.emit(\"subdocRegistered\", event);\n\n\t\t\t// Remove from the offline queue now the server confirmed.\n\t\t\tthis.offlineStore?.removeSubdocFromQueue(msg.child_id);\n\n\t\t\t// Eager mode: auto-load the confirmed child.\n\t\t\tif (this.subdocLoading === \"eager\") {\n\t\t\t\tthis.loadChild(msg.child_id);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Unknown stateless payload – pass through to base class.\n\t\tsuper.receiveStateless(payload);\n\t}\n\n\t// ── Subdocument support ───────────────────────────────────────────────────\n\n\t/**\n\t * Y.Doc emits 'subdocs' whenever subdocuments are added, removed, or loaded.\n\t * We intercept additions to register them with the Abracadabra server.\n\t */\n\tprivate handleYSubdocsChange({\n\t\tadded,\n\t\tremoved,\n\t}: {\n\t\tadded: Set<Y.Doc>;\n\t\tremoved: Set<Y.Doc>;\n\t\tloaded: Set<Y.Doc>;\n\t}) {\n\t\tfor (const subdoc of added) {\n\t\t\tif (!isValidDocId(subdoc.guid)) continue;\n\t\t\tthis.registerSubdoc(subdoc);\n\t\t}\n\t\tfor (const subdoc of removed) {\n\t\t\tthis.unloadChild(subdoc.guid);\n\t\t}\n\t}\n\n\t/**\n\t * Send a subdoc registration frame to the server.\n\t * If offline the event is queued in IndexedDB and replayed on reconnect.\n\t */\n\tprivate registerSubdoc(subdoc: Y.Doc) {\n\t\tconst childId = subdoc.guid;\n\n\t\tif (this.isConnected) {\n\t\t\tthis.send(SubdocMessage, {\n\t\t\t\tdocumentName: this.configuration.name,\n\t\t\t\tchildDocumentName: childId,\n\t\t\t} as any);\n\t\t} else {\n\t\t\t// Queue for later replay when we reconnect.\n\t\t\tthis.offlineStore?.queueSubdoc({\n\t\t\t\tchildId,\n\t\t\t\tparentId: this.configuration.name,\n\t\t\t\tcreatedAt: Date.now(),\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Create (or return cached) a child AbracadabraProvider for a given\n\t * child document id. Each child opens its own WebSocket connection because\n\t * the server is document-scoped (one WebSocket ↔ one document).\n\t */\n\tloadChild(childId: string): Promise<AbracadabraProvider> {\n\t\tif (!isValidDocId(childId)) {\n\t\t\treturn Promise.reject(\n\t\t\t\tnew Error(\n\t\t\t\t\t`loadChild: \"${childId}\" is not a valid document ID (must be a UUID). ` +\n\t\t\t\t\t`If this node was created with an older version of the app, delete it and recreate it.`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\tif (this.childProviders.has(childId)) {\n\t\t\treturn Promise.resolve(this.childProviders.get(childId)!);\n\t\t}\n\n\t\t// Deduplicate concurrent calls: return the same Promise so both callers\n\t\t// get the exact same AbracadabraProvider instance.\n\t\tif (this.pendingLoads.has(childId)) {\n\t\t\treturn this.pendingLoads.get(childId)!;\n\t\t}\n\n\t\tconst load = this._doLoadChild(childId);\n\t\tthis.pendingLoads.set(childId, load);\n\t\tload.finally(() => this.pendingLoads.delete(childId));\n\t\treturn load;\n\t}\n\n\tprivate async _doLoadChild(childId: string): Promise<AbracadabraProvider> {\n\t\tconst childDoc = new Y.Doc({ guid: childId });\n\n\t\t// Fire-and-forget: tell the server this child belongs to the parent.\n\t\t// The child provider's own WebSocket handshake (TCP + TLS + auth) is\n\t\t// slow enough that the server will have processed the registration\n\t\t// before the child's first SyncStep1 arrives. In the rare race the\n\t\t// child's built-in reconnect logic retries automatically.\n\t\tthis.registerSubdoc(childDoc);\n\n\t\t// Each child gets its own WebSocket connection. Omitting\n\t\t// websocketProvider lets AbracadabraBaseProvider create one automatically\n\t\t// (manageSocket = true), so we do NOT call attach() manually.\n\t\tconst childProvider = new AbracadabraProvider({\n\t\t\tname: childId,\n\t\t\tdocument: childDoc,\n\t\t\turl: this.abracadabraConfig.url ?? this.configuration.websocketProvider?.url,\n\t\t\ttoken: this.configuration.token,\n\t\t\tsubdocLoading: this.subdocLoading,\n\t\t\tdisableOfflineStore: this.abracadabraConfig.disableOfflineStore,\n\t\t\tclient: this._client ?? undefined,\n\t\t\tcryptoIdentity: this.abracadabraConfig.cryptoIdentity,\n\t\t\tsignChallenge: this.abracadabraConfig.signChallenge,\n\t\t\tdocKeyManager: this.abracadabraConfig.docKeyManager,\n\t\t\tkeystore: this.abracadabraConfig.keystore,\n\t\t});\n\n\t\tthis.childProviders.set(childId, childProvider);\n\n\t\tthis.emit(\"subdocLoaded\", { childId, provider: childProvider });\n\n\t\treturn childProvider;\n\t}\n\n\tprivate unloadChild(childId: string) {\n\t\tconst provider = this.childProviders.get(childId);\n\t\tif (provider) {\n\t\t\tprovider.destroy();\n\t\t\tthis.childProviders.delete(childId);\n\t\t}\n\t}\n\n\t/** Return all currently-loaded child providers. */\n\tget children(): Map<string, AbracadabraProvider> {\n\t\treturn this.childProviders;\n\t}\n\n\t// ── Offline-first update persistence ─────────────────────────────────────\n\n\t/**\n\t * Override to persist every local update to IndexedDB before sending it\n\t * over the wire, ensuring no work is lost during connection outages.\n\t *\n\t * Updates applied by the server (origin === this) and updates replayed\n\t * from the offline store (origin === this.offlineStore) are both skipped\n\t * to avoid loops.\n\t */\n\toverride documentUpdateHandler(update: Uint8Array, origin: unknown) {\n\t\tif (origin === this) return;\n\t\t// Only skip when the store exists AND origin matches it.\n\t\t// Without the null-guard, a null offlineStore would match any update\n\t\t// with origin=null (the default for user transactions), silently\n\t\t// dropping all local writes when disableOfflineStore is true.\n\t\tif (this.offlineStore !== null && origin === this.offlineStore) return;\n\n\t\t// Persist locally first (fire-and-forget; errors are non-fatal).\n\t\tthis.offlineStore?.persistUpdate(update).catch(() => null);\n\n\t\tsuper.documentUpdateHandler(update, origin);\n\t}\n\n\t/**\n\t * After reconnect + sync:\n\t * 1. Flush any updates that were generated while offline.\n\t * 2. Flush any queued subdoc registrations.\n\t * 3. Save a fresh full document snapshot for the next offline session.\n\t *\n\t * Uses a local `store` reference captured at the start so that a concurrent\n\t * `destroy()` call setting `offlineStore = null` does not cause null-ref\n\t * errors across async await boundaries.\n\t */\n\tprivate async flushPendingUpdates() {\n\t\tconst store = this.offlineStore;\n\t\tif (!store) return;\n\n\t\tconst updates = await store.getPendingUpdates();\n\t\tif (updates.length > 0) {\n\t\t\tfor (const update of updates) {\n\t\t\t\tthis.send(UpdateMessage, {\n\t\t\t\t\tupdate,\n\t\t\t\t\tdocumentName: this.configuration.name,\n\t\t\t\t});\n\t\t\t}\n\t\t\tawait store.clearPendingUpdates();\n\t\t}\n\n\t\tconst pendingSubdocs = await store.getPendingSubdocs();\n\t\tfor (const { childId } of pendingSubdocs) {\n\t\t\tthis.send(SubdocMessage, {\n\t\t\t\tdocumentName: this.configuration.name,\n\t\t\t\tchildDocumentName: childId,\n\t\t\t} as any);\n\t\t}\n\n\t\t// Snapshot the current merged state so the next offline load sees it.\n\t\tconst snapshot = Y.encodeStateAsUpdate(this.document);\n\t\tawait store.saveDocSnapshot(snapshot).catch(() => null);\n\t}\n\n\tget isConnected(): boolean {\n\t\treturn (\n\t\t\t(this.configuration.websocketProvider as AbracadabraWS)\n\t\t\t\t.status === \"connected\"\n\t\t);\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\toverride destroy() {\n\t\tthis.document.off(\"subdocs\", this.boundHandleYSubdocsChange);\n\n\t\tfor (const provider of this.childProviders.values()) {\n\t\t\tprovider.destroy();\n\t\t}\n\t\tthis.childProviders.clear();\n\n\t\tthis.offlineStore?.destroy();\n\t\tthis.offlineStore = null;\n\n\t\tsuper.destroy();\n\t}\n}\n","import type {\n\tUserProfile,\n\tDocumentMeta,\n\tUploadMeta,\n\tUploadInfo,\n\tPublicKeyInfo,\n\tPermissionEntry,\n\tHealthStatus,\n\tServerInfo,\n\tInviteRow,\n\tSpaceMeta,\n} from \"./types.ts\";\nimport type { DocEncryptionInfo } from \"./types.ts\";\nimport type { DocumentCache } from \"./DocumentCache.ts\";\n\nfunction fromBase64(b64: string): Uint8Array {\n\treturn Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n}\n\nexport interface AbracadabraClientConfig {\n\t/** Server base URL (http or https). WebSocket URL is derived automatically. */\n\turl: string;\n\t/** Initial JWT token. If omitted and persistAuth is true, loads from storage. */\n\ttoken?: string;\n\t/** Persist JWT to localStorage for stay-logged-in. Default: true in browser. */\n\tpersistAuth?: boolean;\n\t/** localStorage key for token persistence. Default: \"abracadabra:auth\". */\n\tstorageKey?: string;\n\t/** Custom fetch implementation (useful for Node.js or testing). */\n\tfetch?: typeof globalThis.fetch;\n\t/**\n\t * Optional metadata cache. When provided, read methods (getDoc, listChildren,\n\t * getMe, listPermissions, listUploads) check the cache before hitting the\n\t * network. Write methods (deleteDoc, upload, deleteUpload) invalidate affected\n\t * cache entries automatically.\n\t */\n\tcache?: DocumentCache;\n}\n\nexport class AbracadabraClient {\n\tprivate _token: string | null;\n\tprivate readonly baseUrl: string;\n\tprivate readonly persistAuth: boolean;\n\tprivate readonly storageKey: string;\n\tprivate readonly _fetch: typeof globalThis.fetch;\n\treadonly cache: DocumentCache | null;\n\n\tconstructor(config: AbracadabraClientConfig) {\n\t\tthis.baseUrl = config.url.replace(/\\/+$/, \"\");\n\t\tthis.persistAuth = config.persistAuth ?? typeof localStorage !== \"undefined\";\n\t\tthis.storageKey = config.storageKey ?? \"abracadabra:auth\";\n\t\tthis._fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n\t\tthis.cache = config.cache ?? null;\n\n\t\t// Load token: explicit > persisted > null\n\t\tthis._token = config.token ?? this.loadPersistedToken() ?? null;\n\t}\n\n\t// ── Token management ─────────────────────────────────────────────────────\n\n\tget token(): string | null {\n\t\treturn this._token;\n\t}\n\n\tset token(value: string | null) {\n\t\tthis._token = value;\n\t\tif (this.persistAuth) {\n\t\t\tif (value) {\n\t\t\t\tthis.persistToken(value);\n\t\t\t} else {\n\t\t\t\tthis.clearPersistedToken();\n\t\t\t}\n\t\t}\n\t}\n\n\tget isAuthenticated(): boolean {\n\t\treturn this._token !== null;\n\t}\n\n\t/** Derives ws:// or wss:// URL from the http(s) base URL. */\n\tget wsUrl(): string {\n\t\treturn this.baseUrl\n\t\t\t.replace(/^https:\\/\\//, \"wss://\")\n\t\t\t.replace(/^http:\\/\\//, \"ws://\") + \"/ws\";\n\t}\n\n\t// ── Auth ─────────────────────────────────────────────────────────────────\n\n\t/** Register a new user with password. */\n\tasync register(opts: {\n\t\tusername: string;\n\t\tpassword: string;\n\t\temail?: string;\n\t\tdisplayName?: string;\n\t\tinviteCode?: string;\n\t}): Promise<UserProfile> {\n\t\treturn this.request<UserProfile>(\"POST\", \"/auth/register\", {\n\t\t\tbody: opts,\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t/**\n\t * Register a new user with an Ed25519 public key (crypto auth).\n\t * Username is optional — if omitted, a short identifier is derived from the key.\n\t */\n\tasync registerWithKey(opts: {\n\t\tpublicKey: string;\n\t\tusername?: string;\n\t\tdeviceName?: string;\n\t\tdisplayName?: string;\n\t\temail?: string;\n\t\tinviteCode?: string;\n\t}): Promise<UserProfile> {\n\t\tconst username = opts.username ?? `user-${opts.publicKey.slice(0, 8)}`;\n\t\treturn this.request<UserProfile>(\"POST\", \"/auth/register\", {\n\t\t\tbody: {\n\t\t\t\tusername,\n\t\t\t\tidentityPublicKey: opts.publicKey,\n\t\t\t\tdeviceName: opts.deviceName,\n\t\t\t\tdisplayName: opts.displayName,\n\t\t\t\temail: opts.email,\n\t\t\t\tinviteCode: opts.inviteCode,\n\t\t\t},\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t/** Login with username + password. Auto-persists returned token. */\n\tasync login(opts: { username: string; password: string }): Promise<string> {\n\t\tconst res = await this.request<{ token: string }>(\"POST\", \"/auth/login\", {\n\t\t\tbody: opts,\n\t\t\tauth: false,\n\t\t});\n\t\tthis.token = res.token;\n\t\treturn res.token;\n\t}\n\n\t/** Request an Ed25519 crypto auth challenge for the given public key. */\n\tasync challenge(publicKey: string): Promise<{ challenge: string; expiresAt: number }> {\n\t\treturn this.request(\"POST\", \"/auth/challenge\", {\n\t\t\tbody: { publicKey },\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t/** Verify an Ed25519 signature to complete crypto auth. Auto-persists token. */\n\tasync verify(opts: {\n\t\tpublicKey: string;\n\t\tsignature: string;\n\t\tchallenge: string;\n\t}): Promise<string> {\n\t\tconst res = await this.request<{ token: string }>(\"POST\", \"/auth/verify\", {\n\t\t\tbody: opts,\n\t\t\tauth: false,\n\t\t});\n\t\tthis.token = res.token;\n\t\treturn res.token;\n\t}\n\n\t/**\n\t * Full crypto auth flow: challenge → sign → verify.\n\t * Convenience method combining challenge() + external signing + verify().\n\t */\n\tasync loginWithKey(\n\t\tpublicKey: string,\n\t\tsignChallenge: (challenge: string) => Promise<string>,\n\t): Promise<string> {\n\t\tconst { challenge } = await this.challenge(publicKey);\n\t\tconst signature = await signChallenge(challenge);\n\t\treturn this.verify({ publicKey, signature, challenge });\n\t}\n\n\t/** Add a new Ed25519 public key to the current user (multi-device). */\n\tasync addKey(opts: { publicKey: string; deviceName?: string; x25519Key?: string }): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/keys\", { body: { publicKey: opts.publicKey, deviceName: opts.deviceName, x25519Key: opts.x25519Key } });\n\t}\n\n\t/** List all registered public keys for the current user. */\n\tasync listKeys(): Promise<PublicKeyInfo[]> {\n\t\tconst res = await this.request<{ keys: PublicKeyInfo[] }>(\"GET\", \"/auth/keys\");\n\t\treturn res.keys;\n\t}\n\n\t/** Revoke a public key by its ID. */\n\tasync revokeKey(keyId: string): Promise<void> {\n\t\tawait this.request(\"DELETE\", `/auth/keys/${encodeURIComponent(keyId)}`);\n\t}\n\n\t// ── Encryption ───────────────────────────────────────────────────────────\n\n\t/** Get encryption info for a document. */\n\tasync getDocEncryption(docId: string): Promise<DocEncryptionInfo> {\n\t\treturn this.request<DocEncryptionInfo>(\"GET\", `/docs/${encodeURIComponent(docId)}/encryption`);\n\t}\n\n\t/** Set the encryption mode for a document (no downgrade). */\n\tasync setDocEncryption(docId: string, mode: \"none\" | \"cse\" | \"e2e\"): Promise<void> {\n\t\tawait this.request(\"PATCH\", `/docs/${encodeURIComponent(docId)}/encryption`, { body: { mode } });\n\t}\n\n\t/** Get the caller's key envelope for a document (for decrypting the DocKey). */\n\tasync getMyKeyEnvelope(docId: string): Promise<{ encrypted_key: string; key_epoch: number } | null> {\n\t\ttry {\n\t\t\treturn await this.request<{ encrypted_key: string; key_epoch: number }>(\n\t\t\t\t\"GET\",\n\t\t\t\t`/docs/${encodeURIComponent(docId)}/key-envelope`,\n\t\t\t);\n\t\t} catch (e: unknown) {\n\t\t\tif (typeof e === \"object\" && e !== null && \"status\" in e && (e as { status: number }).status === 404) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t/** Upload key envelopes for a document (Owner only). */\n\tasync uploadKeyEnvelopes(\n\t\tdocId: string,\n\t\topts: { key_epoch: number; envelopes: { recipient_key_id: string; encrypted_key: string }[] },\n\t): Promise<void> {\n\t\tawait this.request(\"POST\", `/docs/${encodeURIComponent(docId)}/key-envelopes`, { body: opts });\n\t}\n\n\t/** Get the X25519 public key for a user. */\n\tasync getUserX25519Key(userId: string): Promise<string | null> {\n\t\ttry {\n\t\t\tconst res = await this.request<{ x25519_key: string }>(\n\t\t\t\t\"GET\",\n\t\t\t\t`/users/${encodeURIComponent(userId)}/x25519-key`,\n\t\t\t);\n\t\t\treturn res.x25519_key;\n\t\t} catch (e: unknown) {\n\t\t\tif (typeof e === \"object\" && e !== null && \"status\" in e && (e as { status: number }).status === 404) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t/** List all non-revoked keys for a user (Owner/Admin or self). */\n\tasync listUserKeys(userId: string): Promise<{ id: string; publicKey: string; x25519Key: string | null }[]> {\n\t\tconst res = await this.request<{ keys: { id: string; publicKey: string; x25519Key: string | null }[] }>(\n\t\t\t\"GET\",\n\t\t\t`/users/${encodeURIComponent(userId)}/keys`,\n\t\t);\n\t\treturn res.keys;\n\t}\n\n\t/** Fetch encrypted E2E update blobs since a given sequence number. */\n\tasync getE2EUpdatesSince(docId: string, sinceSeq: number): Promise<{ seq: number; data: Uint8Array }[]> {\n\t\tconst res = await this.request<{ updates: { seq: number; data: string }[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/e2e-updates?since_seq=${sinceSeq}`,\n\t\t);\n\t\treturn res.updates.map((u) => ({\n\t\t\tseq: u.seq,\n\t\t\tdata: fromBase64(u.data),\n\t\t}));\n\t}\n\n\t/** Clear token from memory and storage. */\n\tlogout(): void {\n\t\tthis.token = null;\n\t}\n\n\t// ── User ─────────────────────────────────────────────────────────────────\n\n\t/** Get the current user's profile. */\n\tasync getMe(): Promise<UserProfile> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getCurrentProfile();\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst profile = await this.request<UserProfile>(\"GET\", \"/users/me\");\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setCurrentProfile(profile).catch(() => null);\n\t\t}\n\t\treturn profile;\n\t}\n\n\t/** Update the current user's display name. */\n\tasync updateMe(opts: { displayName?: string }): Promise<void> {\n\t\tawait this.request(\"PATCH\", \"/users/me\", { body: opts });\n\t}\n\n\t// ── Documents ────────────────────────────────────────────────────────────\n\n\t/** Create a new root document. Returns its metadata. */\n\tasync createDoc(opts?: { id?: string }): Promise<DocumentMeta> {\n\t\treturn this.request<DocumentMeta>(\"POST\", \"/docs\", { body: opts ?? {} });\n\t}\n\n\t/** Get document metadata. */\n\tasync getDoc(docId: string): Promise<DocumentMeta> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getDoc(docId);\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst meta = await this.request<DocumentMeta>(\"GET\", `/docs/${encodeURIComponent(docId)}`);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setDoc(meta).catch(() => null);\n\t\t}\n\t\treturn meta;\n\t}\n\n\t/** Delete a document (requires Owner role). Cascades to children and uploads. */\n\tasync deleteDoc(docId: string): Promise<void> {\n\t\tawait this.request(\"DELETE\", `/docs/${encodeURIComponent(docId)}`);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.invalidateDoc(docId).catch(() => null);\n\t\t}\n\t}\n\n\t/** List immediate child documents. */\n\tasync listChildren(docId: string): Promise<string[]> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getChildren(docId);\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst res = await this.request<{ children: string[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/children`,\n\t\t);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setChildren(docId, res.children).catch(() => null);\n\t\t}\n\t\treturn res.children;\n\t}\n\n\t/** Create a child document under a parent (requires write permission). */\n\tasync createChild(docId: string, opts?: { child_id?: string }): Promise<DocumentMeta> {\n\t\treturn this.request<DocumentMeta>(\n\t\t\t\"POST\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/children`,\n\t\t\t{ body: opts ?? {} },\n\t\t);\n\t}\n\n\t// ── Permissions ──────────────────────────────────────────────────────────\n\n\t/** List all permissions for a document (requires read access). */\n\tasync listPermissions(docId: string): Promise<PermissionEntry[]> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getPermissions(docId);\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst res = await this.request<{ permissions: PermissionEntry[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/permissions`,\n\t\t);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setPermissions(docId, res.permissions).catch(() => null);\n\t\t}\n\t\treturn res.permissions;\n\t}\n\n\t/** Grant or change a user's role on a document (requires Owner). */\n\tasync setPermission(\n\t\tdocId: string,\n\t\topts: { user_id: string; role: \"owner\" | \"editor\" | \"viewer\" | \"observer\" },\n\t): Promise<void> {\n\t\tawait this.request(\n\t\t\t\"POST\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/permissions`,\n\t\t\t{ body: opts },\n\t\t);\n\t}\n\n\t/** Revoke a user's permission on a document (requires Owner). */\n\tasync removePermission(docId: string, opts: { user_id: string }): Promise<void> {\n\t\tawait this.request(\n\t\t\t\"DELETE\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/permissions`,\n\t\t\t{ body: opts },\n\t\t);\n\t}\n\n\t// ── Uploads ──────────────────────────────────────────────────────────────\n\n\t/** Upload a file to a document (requires write permission). */\n\tasync upload(\n\t\tdocId: string,\n\t\tfile: File | Blob,\n\t\tfilename?: string,\n\t): Promise<UploadMeta> {\n\t\tconst formData = new FormData();\n\t\tformData.append(\"file\", file, filename);\n\n\t\tconst headers: Record<string, string> = {};\n\t\tif (this._token) {\n\t\t\theaders[\"Authorization\"] = `Bearer ${this._token}`;\n\t\t}\n\n\t\tconst res = await this._fetch(\n\t\t\t`${this.baseUrl}/docs/${encodeURIComponent(docId)}/uploads`,\n\t\t\t{ method: \"POST\", headers, body: formData },\n\t\t);\n\t\tif (!res.ok) {\n\t\t\tthrow await this.toError(res);\n\t\t}\n\t\tconst meta = await res.json() as UploadMeta;\n\t\tif (this.cache) {\n\t\t\tawait this.cache.invalidateUploads(docId).catch(() => null);\n\t\t}\n\t\treturn meta;\n\t}\n\n\t/** List all uploads for a document. */\n\tasync listUploads(docId: string): Promise<UploadInfo[]> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getUploads(docId);\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst res = await this.request<{ uploads: UploadInfo[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/uploads`,\n\t\t);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setUploads(docId, res.uploads).catch(() => null);\n\t\t}\n\t\treturn res.uploads;\n\t}\n\n\t/** Download an upload as a Blob. */\n\tasync getUpload(docId: string, uploadId: string): Promise<Blob> {\n\t\tconst headers: Record<string, string> = {};\n\t\tif (this._token) {\n\t\t\theaders[\"Authorization\"] = `Bearer ${this._token}`;\n\t\t}\n\n\t\tconst res = await this._fetch(\n\t\t\t`${this.baseUrl}/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}`,\n\t\t\t{ method: \"GET\", headers },\n\t\t);\n\t\tif (!res.ok) {\n\t\t\tthrow await this.toError(res);\n\t\t}\n\t\treturn res.blob();\n\t}\n\n\t/** Delete an upload (requires uploader or document Owner). */\n\tasync deleteUpload(docId: string, uploadId: string): Promise<void> {\n\t\tawait this.request(\n\t\t\t\"DELETE\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}`,\n\t\t);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.invalidateUploads(docId).catch(() => null);\n\t\t}\n\t}\n\n\t// ── Invites ──────────────────────────────────────────────────────────────\n\n\t/** Create an invite code (requires permission per server config). */\n\tasync createInvite(opts?: { role?: string; maxUses?: number; expiresIn?: number }): Promise<InviteRow> {\n\t\treturn this.request<InviteRow>(\"POST\", \"/invites\", { body: opts ?? {} });\n\t}\n\n\t/** List invite codes visible to the current user. */\n\tasync listInvites(): Promise<InviteRow[]> {\n\t\tconst res = await this.request<{ invites: InviteRow[] }>(\"GET\", \"/invites\");\n\t\treturn res.invites;\n\t}\n\n\t/** Revoke an invite by its code. */\n\tasync revokeInvite(code: string): Promise<void> {\n\t\tawait this.request(\"DELETE\", `/invites/${encodeURIComponent(code)}`);\n\t}\n\n\t/** Redeem an invite code for the currently authenticated user. */\n\tasync redeemInvite(code: string): Promise<void> {\n\t\tawait this.request(\"POST\", \"/invites/redeem\", { body: { code } });\n\t}\n\n\t// ── Spaces ───────────────────────────────────────────────────────────────\n\n\t/** List spaces visible to the caller. No auth required for public spaces. */\n\tasync listSpaces(): Promise<SpaceMeta[]> {\n\t\tconst res = await this.request<{ spaces: SpaceMeta[] }>(\"GET\", \"/spaces\", { auth: false });\n\t\treturn res.spaces;\n\t}\n\n\t/** Get a single space by ID. */\n\tasync getSpace(spaceId: string): Promise<SpaceMeta> {\n\t\treturn this.request<SpaceMeta>(\"GET\", `/spaces/${encodeURIComponent(spaceId)}`, { auth: false });\n\t}\n\n\t/** Get the hub space, or null if none is configured. */\n\tasync getHubSpace(): Promise<SpaceMeta | null> {\n\t\ttry {\n\t\t\treturn await this.request<SpaceMeta>(\"GET\", \"/spaces/hub\", { auth: false });\n\t\t} catch (e: unknown) {\n\t\t\tif (typeof e === \"object\" && e !== null && \"status\" in e && (e as { status: number }).status === 404) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t/** Create a new space (auth required). */\n\tasync createSpace(opts: {\n\t\tname: string;\n\t\tdescription?: string;\n\t\tvisibility?: SpaceMeta[\"visibility\"];\n\t\tid?: string;\n\t}): Promise<SpaceMeta> {\n\t\treturn this.request<SpaceMeta>(\"POST\", \"/spaces\", { body: opts });\n\t}\n\n\t/** Update an existing space (Owner or admin required). */\n\tasync updateSpace(\n\t\tspaceId: string,\n\t\topts: Partial<Pick<SpaceMeta, \"name\" | \"description\" | \"visibility\" | \"is_hub\">>,\n\t): Promise<SpaceMeta> {\n\t\treturn this.request<SpaceMeta>(\"PATCH\", `/spaces/${encodeURIComponent(spaceId)}`, { body: opts });\n\t}\n\n\t/** Delete a space and its root document (Owner or admin required). */\n\tasync deleteSpace(spaceId: string): Promise<void> {\n\t\tawait this.request(\"DELETE\", `/spaces/${encodeURIComponent(spaceId)}`);\n\t}\n\n\t// ── System ───────────────────────────────────────────────────────────────\n\n\t/** Health check — no auth required. */\n\tasync health(): Promise<HealthStatus> {\n\t\treturn this.request<HealthStatus>(\"GET\", \"/health\", { auth: false });\n\t}\n\n\t/**\n\t * Fetch server metadata including the optional `index_doc_id` entry point.\n\t * No auth required.\n\t */\n\tasync serverInfo(): Promise<ServerInfo> {\n\t\treturn this.request<ServerInfo>(\"GET\", \"/info\", { auth: false });\n\t}\n\n\t// ── Internals ────────────────────────────────────────────────────────────\n\n\tprivate async request<T = void>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\topts?: { body?: unknown; auth?: boolean },\n\t): Promise<T> {\n\t\tconst auth = opts?.auth ?? true;\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (auth && this._token) {\n\t\t\theaders[\"Authorization\"] = `Bearer ${this._token}`;\n\t\t}\n\n\t\tconst init: RequestInit = { method, headers };\n\n\t\tif (opts?.body !== undefined) {\n\t\t\theaders[\"Content-Type\"] = \"application/json\";\n\t\t\tinit.body = JSON.stringify(opts.body);\n\t\t}\n\n\t\tconst res = await this._fetch(`${this.baseUrl}${path}`, init);\n\n\t\tif (!res.ok) {\n\t\t\tthrow await this.toError(res);\n\t\t}\n\n\t\t// 204 No Content\n\t\tif (res.status === 204) {\n\t\t\treturn undefined as T;\n\t\t}\n\n\t\treturn res.json() as Promise<T>;\n\t}\n\n\tprivate async toError(res: Response): Promise<Error> {\n\t\tlet message: string;\n\t\ttry {\n\t\t\tconst body = await res.json() as { error?: string };\n\t\t\tmessage = body.error ?? res.statusText;\n\t\t} catch {\n\t\t\tmessage = res.statusText;\n\t\t}\n\t\tconst err = new Error(message);\n\t\t(err as any).status = res.status;\n\t\treturn err;\n\t}\n\n\tprivate loadPersistedToken(): string | null {\n\t\ttry {\n\t\t\treturn localStorage.getItem(this.storageKey);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate persistToken(token: string): void {\n\t\ttry {\n\t\t\tlocalStorage.setItem(this.storageKey, token);\n\t\t} catch {\n\t\t\t// localStorage unavailable (SSR / Node.js)\n\t\t}\n\t}\n\n\tprivate clearPersistedToken(): void {\n\t\ttry {\n\t\t\tlocalStorage.removeItem(this.storageKey);\n\t\t} catch {\n\t\t\t// localStorage unavailable\n\t\t}\n\t}\n}\n","export interface CloseEvent {\n\tcode: number;\n\treason: string;\n}\n\n/**\n * The server is terminating the connection because a data frame was received\n * that is too large.\n * See: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code\n */\nexport const MessageTooBig: CloseEvent = {\n\tcode: 1009,\n\treason: \"Message Too Big\",\n};\n\n/**\n * The server successfully processed the request, asks that the requester reset\n * its document view, and is not returning any content.\n */\nexport const ResetConnection: CloseEvent = {\n\tcode: 4205,\n\treason: \"Reset Connection\",\n};\n\n/**\n * Similar to Forbidden, but specifically for use when authentication is required and has\n * failed or has not yet been provided.\n */\nexport const Unauthorized: CloseEvent = {\n\tcode: 4401,\n\treason: \"Unauthorized\",\n};\n\n/**\n * The request contained valid data and was understood by the server, but the server\n * is refusing action.\n */\nexport const Forbidden: CloseEvent = {\n\tcode: 4403,\n\treason: \"Forbidden\",\n};\n\n/**\n * The server timed out waiting for the request.\n */\nexport const ConnectionTimeout: CloseEvent = {\n\tcode: 4408,\n\treason: \"Connection Timeout\",\n};\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, Hash, toBytes } from \"./utils.js\";\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n ahash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n abytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/**\n * HKDF (RFC 5869): extract + expand in one step.\n * See https://soatok.blog/2021/11/17/understanding-hkdf/.\n * @module\n */\nimport { hmac } from \"./hmac.js\";\nimport { ahash, anumber, clean, toBytes } from \"./utils.js\";\n/**\n * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n */\nexport function extract(hash, ikm, salt) {\n ahash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen);\n return hmac(hash, toBytes(salt), toBytes(ikm));\n}\nconst HKDF_COUNTER = /* @__PURE__ */ Uint8Array.from([0]);\nconst EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();\n/**\n * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`\n * @param hash - hash function that would be used (e.g. sha256)\n * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes\n */\nexport function expand(hash, prk, info, length = 32) {\n ahash(hash);\n anumber(length);\n const olen = hash.outputLen;\n if (length > 255 * olen)\n throw new Error('Length should be <= 255*HashLen');\n const blocks = Math.ceil(length / olen);\n if (info === undefined)\n info = EMPTY_BUFFER;\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * olen);\n // Re-use HMAC instance between blocks\n const HMAC = hmac.create(hash, prk);\n const HMACTmp = HMAC._cloneInto();\n const T = new Uint8Array(HMAC.outputLen);\n for (let counter = 0; counter < blocks; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)\n .update(info)\n .update(HKDF_COUNTER)\n .digestInto(T);\n okm.set(T, olen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n clean(T, HKDF_COUNTER);\n return okm.slice(0, length);\n}\n/**\n * HKDF (RFC 5869): derive keys from an initial input.\n * Combines hkdf_extract + hkdf_expand in one step\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes\n * @example\n * import { hkdf } from '@noble/hashes/hkdf';\n * import { sha256 } from '@noble/hashes/sha2';\n * import { randomBytes } from '@noble/hashes/utils';\n * const inputKey = randomBytes(32);\n * const salt = randomBytes(32);\n * const info = 'application-key';\n * const hk1 = hkdf(sha256, inputKey, salt, info, 32);\n */\nexport const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);\n//# sourceMappingURL=hkdf.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\nexport class SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = SHA224_IV[0] | 0;\n this.B = SHA224_IV[1] | 0;\n this.C = SHA224_IV[2] | 0;\n this.D = SHA224_IV[3] | 0;\n this.E = SHA224_IV[4] | 0;\n this.F = SHA224_IV[5] | 0;\n this.G = SHA224_IV[6] | 0;\n this.H = SHA224_IV[7] | 0;\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = SHA512_IV[0] | 0;\n this.Al = SHA512_IV[1] | 0;\n this.Bh = SHA512_IV[2] | 0;\n this.Bl = SHA512_IV[3] | 0;\n this.Ch = SHA512_IV[4] | 0;\n this.Cl = SHA512_IV[5] | 0;\n this.Dh = SHA512_IV[6] | 0;\n this.Dl = SHA512_IV[7] | 0;\n this.Eh = SHA512_IV[8] | 0;\n this.El = SHA512_IV[9] | 0;\n this.Fh = SHA512_IV[10] | 0;\n this.Fl = SHA512_IV[11] | 0;\n this.Gh = SHA512_IV[12] | 0;\n this.Gl = SHA512_IV[13] | 0;\n this.Hh = SHA512_IV[14] | 0;\n this.Hl = SHA512_IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = SHA384_IV[0] | 0;\n this.Al = SHA384_IV[1] | 0;\n this.Bh = SHA384_IV[2] | 0;\n this.Bl = SHA384_IV[3] | 0;\n this.Ch = SHA384_IV[4] | 0;\n this.Cl = SHA384_IV[5] | 0;\n this.Dh = SHA384_IV[6] | 0;\n this.Dl = SHA384_IV[7] | 0;\n this.Eh = SHA384_IV[8] | 0;\n this.El = SHA384_IV[9] | 0;\n this.Fh = SHA384_IV[10] | 0;\n this.Fl = SHA384_IV[11] | 0;\n this.Gh = SHA384_IV[12] | 0;\n this.Gl = SHA384_IV[13] | 0;\n this.Hh = SHA384_IV[14] | 0;\n this.Hl = SHA384_IV[15] | 0;\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport { SHA224 as SHA224n, sha224 as sha224n, SHA256 as SHA256n, sha256 as sha256n, } from \"./sha2.js\";\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256 = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256 = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224 = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224 = sha224n;\n//# sourceMappingURL=sha256.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n, title = '') {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(value, length, title = '') {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/** Merges default options and passed options. */\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** Creates function with outputLen, blockLen, create properties from a class constructor. */\nexport function createHasher(hashCons, info = {}) {\n const hashC = (msg, opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */\nexport const oidNist = (suffix) => ({\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView } from \"./utils.js\";\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD {\n blockLen;\n outputLen;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to ||= new this.constructor();\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://www.rfc-editor.org/rfc/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal 32-byte base SHA2 hash class. */\nclass SHA2_32B extends HashMD {\n constructor(outputLen) {\n super(64, outputLen, 8, false);\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA2-256 hash class. */\nexport class _SHA256 extends SHA2_32B {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n/** Internal SHA2-224 hash class. */\nexport class _SHA224 extends SHA2_32B {\n A = SHA224_IV[0] | 0;\n B = SHA224_IV[1] | 0;\n C = SHA224_IV[2] | 0;\n D = SHA224_IV[3] | 0;\n E = SHA224_IV[4] | 0;\n F = SHA224_IV[5] | 0;\n G = SHA224_IV[6] | 0;\n H = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal 64-byte base SHA2 hash class. */\nclass SHA2_64B extends HashMD {\n constructor(outputLen) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/** Internal SHA2-512 hash class. */\nexport class _SHA512 extends SHA2_64B {\n Ah = SHA512_IV[0] | 0;\n Al = SHA512_IV[1] | 0;\n Bh = SHA512_IV[2] | 0;\n Bl = SHA512_IV[3] | 0;\n Ch = SHA512_IV[4] | 0;\n Cl = SHA512_IV[5] | 0;\n Dh = SHA512_IV[6] | 0;\n Dl = SHA512_IV[7] | 0;\n Eh = SHA512_IV[8] | 0;\n El = SHA512_IV[9] | 0;\n Fh = SHA512_IV[10] | 0;\n Fl = SHA512_IV[11] | 0;\n Gh = SHA512_IV[12] | 0;\n Gl = SHA512_IV[13] | 0;\n Hh = SHA512_IV[14] | 0;\n Hl = SHA512_IV[15] | 0;\n constructor() {\n super(64);\n }\n}\n/** Internal SHA2-384 hash class. */\nexport class _SHA384 extends SHA2_64B {\n Ah = SHA384_IV[0] | 0;\n Al = SHA384_IV[1] | 0;\n Bh = SHA384_IV[2] | 0;\n Bl = SHA384_IV[3] | 0;\n Ch = SHA384_IV[4] | 0;\n Cl = SHA384_IV[5] | 0;\n Dh = SHA384_IV[6] | 0;\n Dl = SHA384_IV[7] | 0;\n Eh = SHA384_IV[8] | 0;\n El = SHA384_IV[9] | 0;\n Fh = SHA384_IV[10] | 0;\n Fl = SHA384_IV[11] | 0;\n Gh = SHA384_IV[12] | 0;\n Gl = SHA384_IV[13] | 0;\n Hh = SHA384_IV[14] | 0;\n Hl = SHA384_IV[15] | 0;\n constructor() {\n super(48);\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA2-512/224 hash class. */\nexport class _SHA512_224 extends SHA2_64B {\n Ah = T224_IV[0] | 0;\n Al = T224_IV[1] | 0;\n Bh = T224_IV[2] | 0;\n Bl = T224_IV[3] | 0;\n Ch = T224_IV[4] | 0;\n Cl = T224_IV[5] | 0;\n Dh = T224_IV[6] | 0;\n Dl = T224_IV[7] | 0;\n Eh = T224_IV[8] | 0;\n El = T224_IV[9] | 0;\n Fh = T224_IV[10] | 0;\n Fl = T224_IV[11] | 0;\n Gh = T224_IV[12] | 0;\n Gl = T224_IV[13] | 0;\n Hh = T224_IV[14] | 0;\n Hl = T224_IV[15] | 0;\n constructor() {\n super(28);\n }\n}\n/** Internal SHA2-512/256 hash class. */\nexport class _SHA512_256 extends SHA2_64B {\n Ah = T256_IV[0] | 0;\n Al = T256_IV[1] | 0;\n Bh = T256_IV[2] | 0;\n Bl = T256_IV[3] | 0;\n Ch = T256_IV[4] | 0;\n Cl = T256_IV[5] | 0;\n Dh = T256_IV[6] | 0;\n Dl = T256_IV[7] | 0;\n Eh = T256_IV[8] | 0;\n El = T256_IV[9] | 0;\n Fh = T256_IV[10] | 0;\n Fl = T256_IV[11] | 0;\n Gh = T256_IV[12] | 0;\n Gl = T256_IV[13] | 0;\n Hh = T256_IV[14] | 0;\n Hl = T256_IV[15] | 0;\n constructor() {\n super(32);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n//# sourceMappingURL=sha2.js.map","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes as abytes_, anumber, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, } from '@noble/hashes/utils.js';\nexport { abytes, anumber, bytesToHex, concatBytes, hexToBytes, isBytes, randomBytes, } from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n// Used in weierstrass, der\nfunction abignumber(n) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n))\n throw new Error('positive bigint expected, got ' + n);\n }\n else\n anumber(n);\n return n;\n}\nexport function asafenumber(value, title = '') {\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected safe integer, got type=' + typeof value);\n }\n}\nexport function numberToHexUnpadded(num) {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n anumber(len);\n n = abignumber(n);\n const res = hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n if (res.length !== len)\n throw new Error('number too large');\n return res;\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes_(numberToHexUnpadded(abignumber(n)));\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes) {\n return Uint8Array.from(bytes);\n}\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n */\nexport function asciiToBytes(ascii) {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_1n << BigInt(n)) - _1n;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n anumber(hashLen, 'hashLen');\n anumber(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n const u8n = (len) => new Uint8Array(len); // creates Uint8Array\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...msgs) => hmacFn(k, concatBytes_(v, ...msgs)); // hmac(k)(v, ...values)\n const reseed = (seed = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= _maxDrbgIters)\n throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\nexport function validateObject(object, fields = {}, optFields = {}) {\n if (!object || typeof object !== 'object')\n throw new Error('expected valid options object');\n function checkField(fieldName, expectedType, isOpt) {\n const val = object[fieldName];\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn) {\n const map = new WeakMap();\n return (arg, ...args) => {\n const val = map.get(arg);\n if (val !== undefined)\n return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n//# sourceMappingURL=utils.js.map","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes, anumber, bytesToNumberBE, bytesToNumberLE, numberToBytesBE, numberToBytesLE, validateObject, } from \"../utils.js\";\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _16n = /* @__PURE__ */ BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num, power, modulo) {\n return FpPow(Field(modulo), num, power);\n}\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n if (modulo <= _0n)\n throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\nfunction assertIsSquare(Fp, root, n) {\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n}\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp, n) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\nfunction sqrt5mod8(Fp, n) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n assertIsSquare(Fp, root, n);\n return root;\n}\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P) {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return (Fp, n) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n)\n throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000)\n throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1)\n return sqrt3mod4;\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n if (Fp.is0(n))\n return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1)\n throw new Error('Cannot find square root');\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t))\n return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M)\n throw new Error('Cannot find square root');\n }\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P) {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n)\n return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n)\n return sqrt5mod8;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n)\n return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(Fp, num, power) {\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return Fp.ONE;\n if (power === _1n)\n return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp, nums, passZero = false) {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num))\n return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num))\n return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n// TODO: remove\nexport function FpDiv(Fp, lhs, rhs) {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n */\nexport function FpLegendre(Fp, n) {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no)\n throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp, n) {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined)\n anumber(nBitLength);\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\nclass _Field {\n ORDER;\n BITS;\n BYTES;\n isLE;\n ZERO = _0n;\n ONE = _1n;\n _lengths;\n _sqrt; // cached sqrt\n _mod;\n constructor(ORDER, opts = {}) {\n if (ORDER <= _0n)\n throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n if (typeof opts.BITS === 'number')\n _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function')\n this.sqrt = opts.sqrt;\n if (typeof opts.isLE === 'boolean')\n this.isLE = opts.isLE;\n if (opts.allowedLengths)\n this._lengths = opts.allowedLengths?.slice();\n if (typeof opts.modFromBytes === 'boolean')\n this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048)\n throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n this._sqrt = undefined;\n Object.preventExtensions(this);\n }\n create(num) {\n return mod(num, this.ORDER);\n }\n isValid(num) {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num) {\n return (num & _1n) === _1n;\n }\n neg(num) {\n return mod(-num, this.ORDER);\n }\n eql(lhs, rhs) {\n return lhs === rhs;\n }\n sqr(num) {\n return mod(num * num, this.ORDER);\n }\n add(lhs, rhs) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs, rhs) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs, rhs) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num, power) {\n return FpPow(this, num, power);\n }\n div(lhs, rhs) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n // Same as above, but doesn't normalize\n sqrN(num) {\n return num * num;\n }\n addN(lhs, rhs) {\n return lhs + rhs;\n }\n subN(lhs, rhs) {\n return lhs - rhs;\n }\n mulN(lhs, rhs) {\n return lhs * rhs;\n }\n inv(num) {\n return invert(num, this.ORDER);\n }\n sqrt(num) {\n // Caching _sqrt speeds up sqrt9mod16 by 5x and tonneli-shanks by 10%\n if (!this._sqrt)\n this._sqrt = FpSqrt(this.ORDER);\n return this._sqrt(this, num);\n }\n toBytes(num) {\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes)\n scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst) {\n return FpInvertBatch(this, lst);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a, b, condition) {\n return condition ? b : a;\n }\n}\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, opts = {}) {\n return new _Field(ORDER, opts);\n}\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.Point.Fn.ORDER)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n abytes(key);\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask } from \"../utils.js\";\nimport { Field, FpInvertBatch, validateField } from \"./modular.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport function negateCt(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\n}\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\nexport function normalizeZ(c, points) {\n const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\nfunction validateW(W, bits) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\nfunction calcWOpts(W, scalarBits) {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\nfunction calcOffsets(n, window, wOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\nfunction validateMSMPoints(points, c) {\n if (!Array.isArray(points))\n throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars, field) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error('invalid scalar at index ' + i);\n });\n}\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\nfunction getW(P) {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\nfunction assert0(n) {\n if (n !== _0n)\n throw new Error('invalid wNAF');\n}\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF {\n BASE;\n ZERO;\n Fn;\n bits;\n // Parametrized with a given Point class (not individual point)\n constructor(Point, bits) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n // non-const time multiplication ladder\n _unsafeLadder(elm, n, p = this.ZERO) {\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(point, W) {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points = [];\n let p = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n))\n throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n }\n else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n }\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n)\n break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n }\n else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n getPrecomputes(W, point, transform) {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W);\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function')\n comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n cached(point, scalar, transform) {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n unsafe(point, scalar, transform, prev) {\n const W = getW(point);\n if (W === 1)\n return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P, W) {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n hasCache(elm) {\n return getW(elm) !== 1;\n }\n}\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe(Point, point, k1, k2) {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n p1 = p1.add(acc);\n if (k2 & _1n)\n p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka secret keys / bigints)\n */\nexport function pippenger(c, points, scalars) {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength)\n throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12)\n windowSize = wbits - 3;\n else if (wbits > 4)\n windowSize = wbits - 2;\n else if (wbits > 0)\n windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe(c, points, windowSize) {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n const fieldN = c.Fn;\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero)\n for (let j = 0; j < windowSize; j++)\n res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr)\n continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\nfunction createField(order, field, isLE) {\n if (field) {\n if (field.ORDER !== order)\n throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n }\n else {\n return Field(order, { isLE });\n }\n}\n/** Validates CURVE opts and creates fields */\nexport function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {\n if (FpFnLE === undefined)\n FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object')\n throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h']) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b];\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\nexport function createKeygen(randomSecretKey, getPublicKey) {\n return function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n };\n}\n//# sourceMappingURL=curve.js.map","/**\n * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abool, abytes, aInRange, bytesToHex, bytesToNumberLE, concatBytes, copyBytes, hexToBytes, isBytes, memoized, notImplemented, validateObject, randomBytes as wcRandomBytes, } from \"../utils.js\";\nimport { createCurveFields, createKeygen, normalizeZ, wNAF, } from \"./curve.js\";\nimport {} from \"./modular.js\";\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\nfunction isEdValidXY(Fp, CURVE, x, y) {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\nexport function edwards(params, extraOpts = {}) {\n const validated = createCurveFields('edwards', params, extraOpts, extraOpts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE;\n const { h: cofactor } = CURVE;\n validateObject(extraOpts, {}, { uvRatio: 'function' });\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);\n const modP = (n) => Fp.create(n); // Function overrides\n // sqrt(u/v)\n const uvRatio = extraOpts.uvRatio ||\n ((u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n // Validate whether the passed curve params are valid.\n // equation ax² + y² = 1 + dx²y² should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title, n, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n function aedpoint(other) {\n if (!(other instanceof Point))\n throw new Error('EdwardsPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p, iz) => {\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? _8n : Fp.inv(Z); // 8 was chosen arbitrarily\n const x = modP(X * iz);\n const y = modP(Y * iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: _0n, y: _1n };\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return { x, y };\n });\n const assertValidMemo = memoized((p) => {\n const { a, d } = CURVE;\n if (p.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { X, Y, Z, T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n return true;\n });\n // Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n // base / generator point\n static BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n // zero / infinity / identity point\n static ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n // math field\n static Fp = Fp;\n // scalar field\n static Fn = Fn;\n X;\n Y;\n Z;\n T;\n constructor(X, Y, Z, T) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n acoord('x', x);\n acoord('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes, zip215 = false) {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('point.y', y, _0n, max);\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('bad point: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('bad point: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromHex(hex, zip215 = false) {\n return Point.fromBytes(hexToBytes(hex), zip215);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n precompute(windowSize = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy)\n this.multiply(_2n); // random number\n return this;\n }\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity() {\n assertValidMemo(this);\n }\n // Compare one point to another.\n equals(other) {\n aedpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { a } = CURVE;\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n aedpoint(other);\n const { a, d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n // Constant-time multiplication.\n multiply(scalar) {\n // 1 <= scalar < L\n if (!Fn.isValidNot0(scalar))\n throw new Error('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));\n return normalizeZ(Point, [p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n // Accepts optional accumulator to merge with multiply (important for sparse scalars)\n multiplyUnsafe(scalar, acc = Point.ZERO) {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar))\n throw new Error('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n)\n return Point.ZERO;\n if (this.is0() || scalar === _1n)\n return this;\n return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.multiplyUnsafe(cofactor).is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.unsafe(this, CURVE.n).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ) {\n return toAffineMemo(this, invertedZ);\n }\n clearCofactor() {\n if (cofactor === _1n)\n return this;\n return this.multiplyUnsafe(cofactor);\n }\n toBytes() {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;\n return bytes;\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const wnaf = new wNAF(Point, Fn.BITS);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points.\n */\nexport class PrimeEdwardsPoint {\n static BASE;\n static ZERO;\n static Fp;\n static Fn;\n ep;\n constructor(ep) {\n this.ep = ep;\n }\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes) {\n notImplemented();\n }\n static fromHex(_hex) {\n notImplemented();\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n // Common implementations\n clearCofactor() {\n // no-op for prime-order groups\n return this;\n }\n assertValidity() {\n this.ep.assertValidity();\n }\n toAffine(invertedZ) {\n return this.ep.toAffine(invertedZ);\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return this.toHex();\n }\n isTorsionFree() {\n return true;\n }\n isSmallOrder() {\n return false;\n }\n add(other) {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n subtract(other) {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return this.init(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return this.init(this.ep.double());\n }\n negate() {\n return this.init(this.ep.negate());\n }\n precompute(windowSize, isLazy) {\n return this.init(this.ep.precompute(windowSize, isLazy));\n }\n}\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n */\nexport function eddsa(Point, cHash, eddsaOpts = {}) {\n if (typeof cHash !== 'function')\n throw new Error('\"hash\" function param is required');\n validateObject(eddsaOpts, {}, {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n mapToCurve: 'function',\n });\n const { prehash } = eddsaOpts;\n const { BASE, Fp, Fn } = Point;\n const randomBytes = eddsaOpts.randomBytes || wcRandomBytes;\n const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);\n const domain = eddsaOpts.domain ||\n ((data, ctx, phflag) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n // Little-endian SHA512 with modulo n\n function modN_LE(hash) {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key) {\n const len = lengths.secretKey;\n abytes(key, lengths.secretKey, 'secretKey');\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = abytes(cHash(key), 2 * len, 'hashedSecretKey');\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n return { head, prefix, scalar };\n }\n /** Convenience method that creates public key from scalar. RFC8032 5.1.5 */\n function getExtendedPublicKey(secretKey) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes();\n return { head, prefix, scalar, point, pointBytes };\n }\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey) {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {\n const msg = concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, abytes(context, undefined, 'context'), !!prehash)));\n }\n /** Signs message with secret key. RFC8032 5.1.6 */\n function sign(msg, secretKey, options = {}) {\n msg = abytes(msg, undefined, 'message');\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s))\n throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result');\n }\n // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\n const verifyOpts = { zip215: true };\n /**\n * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n * An extended group equation is checked.\n */\n function verify(sig, msg, publicKey, options = verifyOpts) {\n const { context, zip215 } = options;\n const len = lengths.signature;\n sig = abytes(sig, len, 'signature');\n msg = abytes(msg, undefined, 'message');\n publicKey = abytes(publicKey, lengths.publicKey, 'publicKey');\n if (zip215 !== undefined)\n abool(zip215, 'zip215');\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder())\n return false; // zip215 allows public keys of small order\n const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed = randomBytes(lengths.seed)) {\n return abytes(seed, lengths.seed, 'seed');\n }\n function isValidSecretKey(key) {\n return isBytes(key) && key.length === Fn.BYTES;\n }\n function isValidPublicKey(key, zip215) {\n try {\n return !!Point.fromBytes(key, zip215);\n }\n catch (error) {\n return false;\n }\n }\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /**\n * Converts ed public key to x public key. Uses formula:\n * - ed25519:\n * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * - ed448:\n * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n */\n toMontgomery(publicKey) {\n const { y } = Point.fromBytes(publicKey);\n const size = lengths.publicKey;\n const is25519 = size === 32;\n if (!is25519 && size !== 57)\n throw new Error('only defined for 25519 and 448');\n const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);\n return Fp.toBytes(u);\n },\n toMontgomerySecret(secretKey) {\n const size = lengths.secretKey;\n abytes(secretKey, size);\n const hashed = cHash(secretKey.subarray(0, size));\n return adjustScalarBytes(hashed).subarray(0, size);\n },\n };\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n });\n}\n//# sourceMappingURL=edwards.js.map","import { abytes, asafenumber, asciiToBytes, bytesToNumberBE, concatBytes, isBytes, validateObject, } from \"../utils.js\";\nimport { FpInvertBatch, mod } from \"./modular.js\";\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = bytesToNumberBE;\n// Integer to Octet Stream (numberToBytesBE)\nfunction i2osp(value, length) {\n asafenumber(value);\n asafenumber(length);\n if (value < 0 || value >= 1 << (8 * length))\n throw new Error('invalid I2OSP input: ' + value);\n const res = Array.from({ length }).fill(0);\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res);\n}\nfunction strxor(a, b) {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr;\n}\n// User can always use utf8 if they want, by passing Uint8Array.\n// If string is passed, we treat it as ASCII: other formats are likely a mistake.\nfunction normDST(DST) {\n if (!isBytes(DST) && typeof DST !== 'string')\n throw new Error('DST must be Uint8Array or ascii string');\n return typeof DST === 'string' ? asciiToBytes(DST) : DST;\n}\n/**\n * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.\n * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).\n */\nexport function expand_message_xmd(msg, DST, lenInBytes, H) {\n abytes(msg);\n asafenumber(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255)\n DST = H(concatBytes(asciiToBytes('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (lenInBytes > 65535 || ell > 255)\n throw new Error('expand_message_xmd: invalid lenInBytes');\n const DST_prime = concatBytes(DST, i2osp(DST.length, 1));\n const Z_pad = i2osp(0, r_in_bytes);\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array(ell);\n const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));\n for (let i = 1; i <= ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H(concatBytes(...args));\n }\n const pseudo_random_bytes = concatBytes(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n/**\n * Produces a uniformly random byte string using an extendable-output function (XOF) H.\n * 1. The collision resistance of H MUST be at least k bits.\n * 2. H MUST be an XOF that has been proved indifferentiable from\n * a random oracle under a reasonable cryptographic assumption.\n * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).\n */\nexport function expand_message_xof(msg, DST, lenInBytes, k, H) {\n abytes(msg);\n asafenumber(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update(asciiToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest());\n}\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).\n * @param msg a byte string containing the message to hash\n * @param count the number of elements of F to output\n * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above\n * @returns [u_0, ..., u_(count - 1)], a list of field elements.\n */\nexport function hash_to_field(msg, count, options) {\n validateObject(options, {\n p: 'bigint',\n m: 'number',\n k: 'number',\n hash: 'function',\n });\n const { p, k, m, hash, expand, DST } = options;\n asafenumber(hash.outputLen, 'valid hash');\n abytes(msg);\n asafenumber(count);\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n }\n else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n }\n else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n }\n else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = mod(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\nexport function isogenyMap(field, map) {\n // Make same order as in spec\n const coeff = map.map((i) => Array.from(i).reverse());\n return (x, y) => {\n const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));\n // 6.6.3\n // Exceptional cases of iso_map are inputs that cause the denominator of\n // either rational function to evaluate to zero; such cases MUST return\n // the identity point on E.\n const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);\n x = field.mul(xn, xd_inv); // xNum / xDen\n y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)\n return { x, y };\n };\n}\nexport const _DST_scalar = asciiToBytes('HashToScalar-');\n/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */\nexport function createHasher(Point, mapToCurve, defaults) {\n if (typeof mapToCurve !== 'function')\n throw new Error('mapToCurve() must be defined');\n function map(num) {\n return Point.fromAffine(mapToCurve(num));\n }\n function clear(initial) {\n const P = initial.clearCofactor();\n if (P.equals(Point.ZERO))\n return Point.ZERO; // zero will throw in assert\n P.assertValidity();\n return P;\n }\n return {\n defaults: Object.freeze(defaults),\n Point,\n hashToCurve(msg, options) {\n const opts = Object.assign({}, defaults, options);\n const u = hash_to_field(msg, 2, opts);\n const u0 = map(u[0]);\n const u1 = map(u[1]);\n return clear(u0.add(u1));\n },\n encodeToCurve(msg, options) {\n const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};\n const opts = Object.assign({}, defaults, optsDst, options);\n const u = hash_to_field(msg, 1, opts);\n const u0 = map(u[0]);\n return clear(u0);\n },\n /** See {@link H2CHasher} */\n mapToCurve(scalars) {\n // Curves with m=1 accept only single scalar\n if (defaults.m === 1) {\n if (typeof scalars !== 'bigint')\n throw new Error('expected bigint (m=1)');\n return clear(map([scalars]));\n }\n if (!Array.isArray(scalars))\n throw new Error('expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint')\n throw new Error('expected array of bigints');\n return clear(map(scalars));\n },\n // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393\n // RFC 9380, draft-irtf-cfrg-bbs-signatures-08\n hashToScalar(msg, options) {\n // @ts-ignore\n const N = Point.Fn.ORDER;\n const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);\n return hash_to_field(msg, 1, opts)[0][0];\n },\n };\n}\n//# sourceMappingURL=hash-to-curve.js.map","/**\n * Montgomery curve methods. It's not really whole montgomery curve,\n * just bunch of very specific methods for X25519 / X448 from\n * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes, aInRange, bytesToNumberLE, copyBytes, numberToBytesLE, randomBytes, validateObject, } from \"../utils.js\";\nimport { createKeygen } from \"./curve.js\";\nimport { mod } from \"./modular.js\";\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nfunction validateOpts(curve) {\n validateObject(curve, {\n adjustScalarBytes: 'function',\n powPminus2: 'function',\n });\n return Object.freeze({ ...curve });\n}\nexport function montgomery(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = CURVE;\n const is25519 = type === 'x25519';\n if (!is25519 && type !== 'x448')\n throw new Error('invalid type');\n const randomBytes_ = rand || randomBytes;\n const montgomeryBits = is25519 ? 255 : 448;\n const fieldLen = is25519 ? 32 : 56;\n const Gu = is25519 ? BigInt(9) : BigInt(5);\n // RFC 7748 #5:\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 and\n // (156326 - 2) / 4 = 39081 for curve448/X448\n // const a = is25519 ? 156326n : 486662n;\n const a24 = is25519 ? BigInt(121665) : BigInt(39081);\n // RFC: x25519 \"the resulting integer is of the form 2^254 plus\n // eight times a value between 0 and 2^251 - 1 (inclusive)\"\n // x448: \"2^447 plus four times a value between 0 and 2^445 - 1 (inclusive)\"\n const minScalar = is25519 ? _2n ** BigInt(254) : _2n ** BigInt(447);\n const maxAdded = is25519\n ? BigInt(8) * _2n ** BigInt(251) - _1n\n : BigInt(4) * _2n ** BigInt(445) - _1n;\n const maxScalar = minScalar + maxAdded + _1n; // (inclusive)\n const modP = (n) => mod(n, P);\n const GuBytes = encodeU(Gu);\n function encodeU(u) {\n return numberToBytesLE(modP(u), fieldLen);\n }\n function decodeU(u) {\n const _u = copyBytes(abytes(u, fieldLen, 'uCoordinate'));\n // RFC: When receiving such an array, implementations of X25519\n // (but not X448) MUST mask the most significant bit in the final byte.\n if (is25519)\n _u[31] &= 127; // 0b0111_1111\n // RFC: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime. The non-canonical\n // values are 2^255 - 19 through 2^255 - 1 for X25519 and 2^448 - 2^224\n // - 1 through 2^448 - 1 for X448.\n return modP(bytesToNumberLE(_u));\n }\n function decodeScalar(scalar) {\n return bytesToNumberLE(adjustScalarBytes(copyBytes(abytes(scalar, fieldLen, 'scalar'))));\n }\n function scalarMult(scalar, u) {\n const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));\n // Some public keys are useless, of low-order. Curve author doesn't think\n // it needs to be validated, but we do it nonetheless.\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n)\n throw new Error('invalid private or public key received');\n return encodeU(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n function scalarMultBase(scalar) {\n return scalarMult(scalar, GuBytes);\n }\n const getPublicKey = scalarMultBase;\n const getSharedSecret = scalarMult;\n // cswap from RFC7748 \"example code\"\n function cswap(swap, x_2, x_3) {\n // dummy = mask(swap) AND (x_2 XOR x_3)\n // Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n // and x_3, computed, e.g., as mask(swap) = 0 - swap.\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy); // x_2 = x_2 XOR dummy\n x_3 = modP(x_3 + dummy); // x_3 = x_3 XOR dummy\n return { x_2, x_3 };\n }\n /**\n * Montgomery x-only multiplication ladder.\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(u, scalar) {\n aInRange('u', u, _0n, P);\n aInRange('scalar', scalar, minScalar, maxScalar);\n const k = scalar;\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n ({ x_2, x_3 } = cswap(swap, x_2, x_3));\n ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));\n swap = k_t;\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n ({ x_2, x_3 } = cswap(swap, x_2, x_3));\n ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));\n const z2 = powPminus2(z_2); // `Fp.pow(x, P - _2n)` is much slower equivalent\n return modP(x_2 * z2); // Return x_2 * (z_2^(p - 2))\n }\n const lengths = {\n secretKey: fieldLen,\n publicKey: fieldLen,\n seed: fieldLen,\n };\n const randomSecretKey = (seed = randomBytes_(fieldLen)) => {\n abytes(seed, lengths.seed, 'seed');\n return seed;\n };\n const utils = { randomSecretKey };\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getSharedSecret,\n getPublicKey,\n scalarMult,\n scalarMultBase,\n utils,\n GuBytes: GuBytes.slice(),\n lengths,\n });\n}\n//# sourceMappingURL=montgomery.js.map","/**\n * RFC 9497: Oblivious Pseudorandom Functions (OPRFs) Using Prime-Order Groups.\n * https://www.rfc-editor.org/rfc/rfc9497\n *\n\nOPRF allows to interactively create an `Output = PRF(Input, serverSecretKey)`:\n\n- Server cannot calculate Output by itself: it doesn't know Input\n- Client cannot calculate Output by itself: it doesn't know server secretKey\n- An attacker interception the communication can't restore Input/Output/serverSecretKey and can't\n link Input to some value.\n\n## Issues\n\n- Low-entropy inputs (e.g. password '123') enable brute-forced dictionary attacks by the server\n (solveable by domain separation in POPRF)\n- High-level protocol needs to be constructed on top, because OPRF is low-level\n\n## Use cases\n\n1. **Password-Authenticated Key Exchange (PAKE):** Enables secure password login (e.g., OPAQUE)\n without revealing the password to the server.\n2. **Private Set Intersection (PSI):** Allows two parties to compute the intersection of their\n private sets without revealing non-intersecting elements.\n3. **Anonymous Credential Systems:** Supports issuance of anonymous, unlinkable credentials\n (e.g., Privacy Pass) using blind OPRF evaluation.\n4. **Private Information Retrieval (PIR):** Helps users query databases without revealing which\n item they accessed.\n5. **Encrypted Search / Secure Indexing:** Enables keyword search over encrypted data while keeping\n queries private.\n6. **Spam Prevention and Rate-Limiting:** Issues anonymous tokens to prevent abuse\n (e.g., CAPTCHA bypass) without compromising user privacy.\n\n## Modes\n\n- OPRF: simple mode, client doesn't need to know server public key\n- VOPRF: verifable mode, allows client to verify that server used secret key corresponding to known public key\n- POPRF: partially oblivious mode, VOPRF + domain separation\n\nThere is also non-interactive mode (Evaluate) that supports creating Output in non-interactive mode with knowledge of secret key.\n\nFlow:\n- (once) Server generates secret and public keys, distributes public keys to clients\n - deterministically: `deriveKeyPair` or just random: `generateKeyPair`\n- Client blinds input: `blind(secretInput)`\n- Server evaluates blinded input: `blindEvaluate` generated by client, sends result to client\n- Client creates output using result of evaluation via 'finalize'\n\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes, asciiToBytes, bytesToNumberBE, bytesToNumberLE, concatBytes, numberToBytesBE, randomBytes, validateObject, } from \"../utils.js\";\nimport { pippenger } from \"./curve.js\";\nimport { _DST_scalar } from \"./hash-to-curve.js\";\nimport { getMinHashLength, mapHashToField } from \"./modular.js\";\n// welcome to generic hell\nexport function createORPF(opts) {\n validateObject(opts, {\n name: 'string',\n hash: 'function',\n hashToScalar: 'function',\n hashToGroup: 'function',\n });\n // TODO\n // Point: 'point',\n const { name, Point, hash } = opts;\n const { Fn } = Point;\n const hashToGroup = (msg, ctx) => opts.hashToGroup(msg, {\n DST: concatBytes(asciiToBytes('HashToGroup-'), ctx),\n });\n const hashToScalarPrefixed = (msg, ctx) => opts.hashToScalar(msg, { DST: concatBytes(_DST_scalar, ctx) });\n const randomScalar = (rng = randomBytes) => {\n const t = mapHashToField(rng(getMinHashLength(Fn.ORDER)), Fn.ORDER, Fn.isLE);\n // We cannot use Fn.fromBytes here, because field\n // can have different number of bytes (like ed448)\n return Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t);\n };\n const msm = (points, scalars) => pippenger(Point, points, scalars);\n const getCtx = (mode) => concatBytes(asciiToBytes('OPRFV1-'), new Uint8Array([mode]), asciiToBytes('-' + name));\n const ctxOPRF = getCtx(0x00);\n const ctxVOPRF = getCtx(0x01);\n const ctxPOPRF = getCtx(0x02);\n function encode(...args) {\n const res = [];\n for (const a of args) {\n if (typeof a === 'number')\n res.push(numberToBytesBE(a, 2));\n else if (typeof a === 'string')\n res.push(asciiToBytes(a));\n else {\n abytes(a);\n res.push(numberToBytesBE(a.length, 2), a);\n }\n }\n // No wipe here, since will modify actual bytes\n return concatBytes(...res);\n }\n const hashInput = (...bytes) => hash(encode(...bytes, 'Finalize'));\n function getTranscripts(B, C, D, ctx) {\n const Bm = B.toBytes();\n const seed = hash(encode(Bm, concatBytes(asciiToBytes('Seed-'), ctx)));\n const res = [];\n for (let i = 0; i < C.length; i++) {\n const Ci = C[i].toBytes();\n const Di = D[i].toBytes();\n const di = hashToScalarPrefixed(encode(seed, i, Ci, Di, 'Composite'), ctx);\n res.push(di);\n }\n return res;\n }\n function computeComposites(B, C, D, ctx) {\n const T = getTranscripts(B, C, D, ctx);\n const M = msm(C, T);\n const Z = msm(D, T);\n return { M, Z };\n }\n function computeCompositesFast(k, B, C, D, ctx) {\n const T = getTranscripts(B, C, D, ctx);\n const M = msm(C, T);\n const Z = M.multiply(k);\n return { M, Z };\n }\n function challengeTranscript(B, M, Z, t2, t3, ctx) {\n const [Bm, a0, a1, a2, a3] = [B, M, Z, t2, t3].map((i) => i.toBytes());\n return hashToScalarPrefixed(encode(Bm, a0, a1, a2, a3, 'Challenge'), ctx);\n }\n function generateProof(ctx, k, B, C, D, rng) {\n const { M, Z } = computeCompositesFast(k, B, C, D, ctx);\n const r = randomScalar(rng);\n const t2 = Point.BASE.multiply(r);\n const t3 = M.multiply(r);\n const c = challengeTranscript(B, M, Z, t2, t3, ctx);\n const s = Fn.sub(r, Fn.mul(c, k)); // r - c*k\n return concatBytes(...[c, s].map((i) => Fn.toBytes(i)));\n }\n function verifyProof(ctx, B, C, D, proof) {\n abytes(proof, 2 * Fn.BYTES);\n const { M, Z } = computeComposites(B, C, D, ctx);\n const [c, s] = [proof.subarray(0, Fn.BYTES), proof.subarray(Fn.BYTES)].map((f) => Fn.fromBytes(f));\n const t2 = Point.BASE.multiply(s).add(B.multiply(c)); // s*G + c*B\n const t3 = M.multiply(s).add(Z.multiply(c)); // s*M + c*Z\n const expectedC = challengeTranscript(B, M, Z, t2, t3, ctx);\n if (!Fn.eql(c, expectedC))\n throw new Error('proof verification failed');\n }\n function generateKeyPair() {\n const skS = randomScalar();\n const pkS = Point.BASE.multiply(skS);\n return { secretKey: Fn.toBytes(skS), publicKey: pkS.toBytes() };\n }\n function deriveKeyPair(ctx, seed, info) {\n const dst = concatBytes(asciiToBytes('DeriveKeyPair'), ctx);\n const msg = concatBytes(seed, encode(info), Uint8Array.of(0));\n for (let counter = 0; counter <= 255; counter++) {\n msg[msg.length - 1] = counter;\n const skS = opts.hashToScalar(msg, { DST: dst });\n if (Fn.is0(skS))\n continue; // should not happen\n return { secretKey: Fn.toBytes(skS), publicKey: Point.BASE.multiply(skS).toBytes() };\n }\n throw new Error('Cannot derive key');\n }\n function blind(ctx, input, rng = randomBytes) {\n const blind = randomScalar(rng);\n const inputPoint = hashToGroup(input, ctx);\n if (inputPoint.equals(Point.ZERO))\n throw new Error('Input point at infinity');\n const blinded = inputPoint.multiply(blind);\n return { blind: Fn.toBytes(blind), blinded: blinded.toBytes() };\n }\n function evaluate(ctx, secretKey, input) {\n const skS = Fn.fromBytes(secretKey);\n const inputPoint = hashToGroup(input, ctx);\n if (inputPoint.equals(Point.ZERO))\n throw new Error('Input point at infinity');\n const unblinded = inputPoint.multiply(skS).toBytes();\n return hashInput(input, unblinded);\n }\n const oprf = {\n generateKeyPair,\n deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxOPRF, seed, keyInfo),\n blind: (input, rng = randomBytes) => blind(ctxOPRF, input, rng),\n blindEvaluate(secretKey, blindedPoint) {\n const skS = Fn.fromBytes(secretKey);\n const elm = Point.fromBytes(blindedPoint);\n return elm.multiply(skS).toBytes();\n },\n finalize(input, blindBytes, evaluatedBytes) {\n const blind = Fn.fromBytes(blindBytes);\n const evalPoint = Point.fromBytes(evaluatedBytes);\n const unblinded = evalPoint.multiply(Fn.inv(blind)).toBytes();\n return hashInput(input, unblinded);\n },\n evaluate: (secretKey, input) => evaluate(ctxOPRF, secretKey, input),\n };\n const voprf = {\n generateKeyPair,\n deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxVOPRF, seed, keyInfo),\n blind: (input, rng = randomBytes) => blind(ctxVOPRF, input, rng),\n blindEvaluateBatch(secretKey, publicKey, blinded, rng = randomBytes) {\n if (!Array.isArray(blinded))\n throw new Error('expected array');\n const skS = Fn.fromBytes(secretKey);\n const pkS = Point.fromBytes(publicKey);\n const blindedPoints = blinded.map(Point.fromBytes);\n const evaluated = blindedPoints.map((i) => i.multiply(skS));\n const proof = generateProof(ctxVOPRF, skS, pkS, blindedPoints, evaluated, rng);\n return { evaluated: evaluated.map((i) => i.toBytes()), proof };\n },\n blindEvaluate(secretKey, publicKey, blinded, rng = randomBytes) {\n const res = this.blindEvaluateBatch(secretKey, publicKey, [blinded], rng);\n return { evaluated: res.evaluated[0], proof: res.proof };\n },\n finalizeBatch(items, publicKey, proof) {\n if (!Array.isArray(items))\n throw new Error('expected array');\n const pkS = Point.fromBytes(publicKey);\n const blindedPoints = items.map((i) => i.blinded).map(Point.fromBytes);\n const evalPoints = items.map((i) => i.evaluated).map(Point.fromBytes);\n verifyProof(ctxVOPRF, pkS, blindedPoints, evalPoints, proof);\n return items.map((i) => oprf.finalize(i.input, i.blind, i.evaluated));\n },\n finalize(input, blind, evaluated, blinded, publicKey, proof) {\n return this.finalizeBatch([{ input, blind, evaluated, blinded }], publicKey, proof)[0];\n },\n evaluate: (secretKey, input) => evaluate(ctxVOPRF, secretKey, input),\n };\n // NOTE: info is domain separation\n const poprf = (info) => {\n const m = hashToScalarPrefixed(encode('Info', info), ctxPOPRF);\n const T = Point.BASE.multiply(m);\n return {\n generateKeyPair,\n deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxPOPRF, seed, keyInfo),\n blind(input, publicKey, rng = randomBytes) {\n const pkS = Point.fromBytes(publicKey);\n const tweakedKey = T.add(pkS);\n if (tweakedKey.equals(Point.ZERO))\n throw new Error('tweakedKey point at infinity');\n const blind = randomScalar(rng);\n const inputPoint = hashToGroup(input, ctxPOPRF);\n if (inputPoint.equals(Point.ZERO))\n throw new Error('Input point at infinity');\n const blindedPoint = inputPoint.multiply(blind);\n return {\n blind: Fn.toBytes(blind),\n blinded: blindedPoint.toBytes(),\n tweakedKey: tweakedKey.toBytes(),\n };\n },\n blindEvaluateBatch(secretKey, blinded, rng = randomBytes) {\n if (!Array.isArray(blinded))\n throw new Error('expected array');\n const skS = Fn.fromBytes(secretKey);\n const t = Fn.add(skS, m);\n // \"Hence, this error can be a signal for the server to replace its private key\". We throw inside,\n // should be impossible.\n const invT = Fn.inv(t);\n const blindedPoints = blinded.map(Point.fromBytes);\n const evalPoints = blindedPoints.map((i) => i.multiply(invT));\n const tweakedKey = Point.BASE.multiply(t);\n const proof = generateProof(ctxPOPRF, t, tweakedKey, evalPoints, blindedPoints, rng);\n return { evaluated: evalPoints.map((i) => i.toBytes()), proof };\n },\n blindEvaluate(secretKey, blinded, rng = randomBytes) {\n const res = this.blindEvaluateBatch(secretKey, [blinded], rng);\n return { evaluated: res.evaluated[0], proof: res.proof };\n },\n finalizeBatch(items, proof, tweakedKey) {\n if (!Array.isArray(items))\n throw new Error('expected array');\n const evalPoints = items.map((i) => i.evaluated).map(Point.fromBytes);\n verifyProof(ctxPOPRF, Point.fromBytes(tweakedKey), evalPoints, items.map((i) => i.blinded).map(Point.fromBytes), proof);\n return items.map((i, j) => {\n const blind = Fn.fromBytes(i.blind);\n const point = evalPoints[j].multiply(Fn.inv(blind)).toBytes();\n return hashInput(i.input, info, point);\n });\n },\n finalize(input, blind, evaluated, blinded, proof, tweakedKey) {\n return this.finalizeBatch([{ input, blind, evaluated, blinded }], proof, tweakedKey)[0];\n },\n evaluate(secretKey, input) {\n const skS = Fn.fromBytes(secretKey);\n const inputPoint = hashToGroup(input, ctxPOPRF);\n if (inputPoint.equals(Point.ZERO))\n throw new Error('Input point at infinity');\n const t = Fn.add(skS, m);\n const invT = Fn.inv(t);\n const unblinded = inputPoint.multiply(invT).toBytes();\n return hashInput(input, info, unblinded);\n },\n };\n };\n return Object.freeze({ name, oprf, voprf, poprf, __tests: { Fn } });\n}\n//# sourceMappingURL=oprf.js.map","/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, hexToBytes } from '@noble/hashes/utils.js';\nimport {} from \"./abstract/curve.js\";\nimport { eddsa, edwards, PrimeEdwardsPoint, } from \"./abstract/edwards.js\";\nimport { _DST_scalar, createHasher, expand_message_xmd, } from \"./abstract/hash-to-curve.js\";\nimport { FpInvertBatch, FpSqrtEven, isNegativeLE, mod, pow2, } from \"./abstract/modular.js\";\nimport { montgomery } from \"./abstract/montgomery.js\";\nimport { createORPF } from \"./abstract/oprf.js\";\nimport { asciiToBytes, bytesToNumberLE, equalBytes } from \"./utils.js\";\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n// P = 2n**255n - 19n\nconst ed25519_CURVE_p = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed');\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\nfunction ed25519_pow_2_252_3(x) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ed25519_CURVE_p;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\nfunction adjustScalarBytes(bytes) {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n// √(-1) aka √(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');\n// sqrt(u/v)\nfunction uvRatio(u, v) {\n const P = ed25519_CURVE_p;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P))\n x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\nconst ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });\nconst Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();\nconst Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();\nfunction ed25519_domain(data, ctx, phflag) {\n if (ctx.length > 255)\n throw new Error('Context is too big');\n return concatBytes(asciiToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n}\nfunction ed(opts) {\n return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes }, opts));\n}\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * ```js\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * const { secretKey, publicKey } = ed25519.keygen();\n * // const publicKey = ed25519.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519.sign(msg, secretKey);\n * const isValid = ed25519.verify(sig, msg, pub); // ZIP215\n * // RFC8032 / FIPS 186-5\n * const isValid2 = ed25519.verify(sig, msg, pub, { zip215: false });\n * ```\n */\nexport const ed25519 = /* @__PURE__ */ ed({});\n/** Context version of ed25519 (ctx for domain separation). See {@link ed25519} */\nexport const ed25519ctx = /* @__PURE__ */ ed({ domain: ed25519_domain });\n/** Prehashed version of ed25519. See {@link ed25519} */\nexport const ed25519ph = /* @__PURE__ */ ed({ domain: ed25519_domain, prehash: sha512 });\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * ```js\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const alice = x25519.keygen();\n * const bob = x25519.keygen();\n * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey);\n * ```\n */\nexport const x25519 = /* @__PURE__ */ (() => {\n const P = ed25519_CURVE_p;\n return montgomery({\n P,\n type: 'x25519',\n powPminus2: (x) => {\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n });\n})();\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n/**\n * RFC 9380 method `map_to_curve_elligator2_curve25519`. Experimental name: may be renamed later.\n * @private\n */\n// prettier-ignore\nexport function _map_to_curve_elligator2_curve25519(u) {\n const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u) {\n const { xMn, xMd, yMn, yMd } = _map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n/** Hashing to ed25519 points / field. RFC 9380 methods. */\nexport const ed25519_hasher = /* @__PURE__ */ (() => createHasher(ed25519_Point, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n}))();\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');\n// Calculates 1/√(number)\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_255B = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n/**\n * Computes Elligator map for Ristretto255.\n * Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B) and on\n * the [website](https://ristretto.group/formulas/elligator.html).\n */\nfunction calcElligatorRistrettoMap(r0) {\n const { d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n) => Fp.create(n);\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P))\n s_ = mod(-s_);\n if (!Ns_D_is_sq)\n s = s_; // 7\n if (!Ns_D_is_sq)\n c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519_Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/EdwardsPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like EdwardsPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint {\n // Do NOT change syntax: the following gymnastics is done,\n // because typescript strips comments, which makes bundlers disable tree-shaking.\n // prettier-ignore\n static BASE = \n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))();\n // prettier-ignore\n static ZERO = \n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))();\n // prettier-ignore\n static Fp = \n /* @__PURE__ */ (() => Fp)();\n // prettier-ignore\n static Fn = \n /* @__PURE__ */ (() => Fn)();\n constructor(ep) {\n super(ep);\n }\n static fromAffine(ap) {\n return new _RistrettoPoint(ed25519_Point.fromAffine(ap));\n }\n assertSame(other) {\n if (!(other instanceof _RistrettoPoint))\n throw new Error('RistrettoPoint expected');\n }\n init(ep) {\n return new _RistrettoPoint(ep);\n }\n static fromBytes(bytes) {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n) => Fp.create(n);\n const s = bytes255ToNumberLE(bytes);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P))\n x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n)\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519_Point(x, y, _1n, t));\n }\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex) {\n return _RistrettoPoint.fromBytes(hexToBytes(hex));\n }\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes() {\n let { X, Y, Z, T } = this.ep;\n const P = ed25519_CURVE_p;\n const mod = (n) => Fp.create(n);\n const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1\n const u2 = mod(X * Y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * T); // 6\n let D; // 7\n if (isNegativeLE(T * zInv, P)) {\n let _x = mod(Y * SQRT_M1);\n let _y = mod(X * SQRT_M1);\n X = _x;\n Y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n }\n else {\n D = D2; // 8\n }\n if (isNegativeLE(X * zInv, P))\n Y = mod(-Y); // 9\n let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P))\n s = mod(-s);\n return Fp.toBytes(s); // 11\n }\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other) {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n const mod = (n) => Fp.create(n);\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n is0() {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\nexport const ristretto255 = { Point: _RistrettoPoint };\n/** Hashing to ristretto255 points / field. RFC 9380 methods. */\nexport const ristretto255_hasher = {\n Point: _RistrettoPoint,\n /**\n * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:\n * * There are no test vectors\n * * encodeToCurve / mapToCurve is undefined\n * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!\n * * hashToScalar is undefined too, so we just use OPRF implementation\n * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC\n (os2ip -> bytes255ToNumberLE)\n * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map\n * * hashToScalar is undefined in RFC9380 for ristretto, we are using version from OPRF here, using bytes255ToNumblerLE will create different result if we use bytes255ToNumberLE as os2ip\n * * current version is closest to spec.\n */\n hashToCurve(msg, options) {\n // == 'hash_to_ristretto255'\n const DST = options?.DST || 'ristretto255_XMD:SHA-512_R255MAP_RO_';\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n // NOTE: RFC 9380 incorrectly calls this function 'ristretto255_map', in RFC 9496 map was function inside (per point)\n // That also lead to confustion that ristretto255_map is mapToCurve (it is not! it is old hashToCurve)\n return ristretto255_hasher.deriveToCurve(xmd);\n },\n hashToScalar(msg, options = { DST: _DST_scalar }) {\n const xmd = expand_message_xmd(msg, options.DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n /**\n * HashToCurve-like construction based on RFC 9496 (Element Derivation).\n * Converts 64 uniform random bytes into a curve point.\n *\n * WARNING: This represents an older hash-to-curve construction, preceding the finalization of RFC 9380.\n * It was later reused as a component in the newer `hash_to_ristretto255` function defined in RFC 9380.\n */\n deriveToCurve(bytes) {\n // https://www.rfc-editor.org/rfc/rfc9496.html#name-element-derivation\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n },\n};\n/** ristretto255 OPRF, defined in RFC 9497. */\nexport const ristretto255_oprf = /* @__PURE__ */ (() => createORPF({\n name: 'ristretto255-SHA512',\n Point: _RistrettoPoint,\n hash: sha512,\n hashToGroup: ristretto255_hasher.hashToCurve,\n hashToScalar: ristretto255_hasher.hashToScalar,\n}))();\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * ⟨T⟩ = { O, T, 2T, 3T, 4T, 5T, 6T, 7T }\n */\nexport const ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n//# sourceMappingURL=ed25519.js.map","/**\n * CryptoIdentityKeystore\n *\n * Per-device Ed25519 keypair, private key protected by WebAuthn PRF + AES-256-GCM.\n * Stored in IndexedDB under \"abracadabra:identity\" / \"identity\" / key \"current\".\n *\n * No private key is ever shared between devices. Each device generates its own\n * keypair, encrypts the private key with the PRF output from its own WebAuthn\n * credential, and stores the ciphertext in IndexedDB.\n *\n * Dependencies: @noble/ed25519, @noble/hashes (for HKDF)\n */\n\nimport * as ed from \"@noble/ed25519\";\nimport { hkdf } from \"@noble/hashes/hkdf\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { ed25519 as nobleEd25519Curves } from \"@noble/curves/ed25519.js\";\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\ninterface StoredIdentity {\n\t/**\n\t * Internal label stored locally. NOT sent to the server during the\n\t * challenge-response handshake — the public key is the sole auth identifier.\n\t * This may be used as a hint when calling POST /auth/register (first device)\n\t * or displayed to the user before they set a real display name.\n\t */\n\tusername: string;\n\t/** base64url-encoded Ed25519 public key (32 bytes). Primary auth identifier. */\n\tpublicKey: string;\n\t/** AES-GCM ciphertext of the 32-byte private key */\n\tencryptedPrivateKey: ArrayBuffer;\n\t/** 12-byte AES-GCM nonce */\n\tiv: Uint8Array;\n\t/** 32-byte constant PRF input salt (per-enrollment) */\n\tsalt: Uint8Array;\n\t/** WebAuthn credential ID */\n\tcredentialId: ArrayBuffer;\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────\n\nfunction toBase64url(bytes: Uint8Array): string {\n\treturn btoa(String.fromCharCode(...bytes))\n\t\t.replace(/\\+/g, \"-\")\n\t\t.replace(/\\//g, \"_\")\n\t\t.replace(/=/g, \"\");\n}\n\nfunction fromBase64url(b64: string): Uint8Array {\n\tconst padded = b64.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\tconst padLen = (4 - (padded.length % 4)) % 4;\n\tconst padded2 = padded + \"=\".repeat(padLen);\n\treturn Uint8Array.from(atob(padded2), (c) => c.charCodeAt(0));\n}\n\nconst DB_NAME = \"abracadabra:identity\";\nconst STORE_NAME = \"identity\";\nconst RECORD_KEY = \"current\";\nconst HKDF_INFO = new TextEncoder().encode(\"abracadabra-identity-v1\");\n\n// ── IndexedDB helpers ─────────────────────────────────────────────────────────\n\nfunction openDb(): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = indexedDB.open(DB_NAME, 1);\n\t\treq.onupgradeneeded = () => {\n\t\t\treq.result.createObjectStore(STORE_NAME);\n\t\t};\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nasync function dbGet(db: IDBDatabase): Promise<StoredIdentity | undefined> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst tx = db.transaction(STORE_NAME, \"readonly\");\n\t\tconst req = tx.objectStore(STORE_NAME).get(RECORD_KEY);\n\t\treq.onsuccess = () => resolve(req.result as StoredIdentity | undefined);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nasync function dbPut(db: IDBDatabase, value: StoredIdentity): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst tx = db.transaction(STORE_NAME, \"readwrite\");\n\t\tconst req = tx.objectStore(STORE_NAME).put(value, RECORD_KEY);\n\t\treq.onsuccess = () => resolve();\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nasync function dbDelete(db: IDBDatabase): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst tx = db.transaction(STORE_NAME, \"readwrite\");\n\t\tconst req = tx.objectStore(STORE_NAME).delete(RECORD_KEY);\n\t\treq.onsuccess = () => resolve();\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\n// ── Key derivation ────────────────────────────────────────────────────────────\n\nasync function deriveAesKey(prfOutput: ArrayBuffer, salt: Uint8Array): Promise<CryptoKey> {\n\tconst ikm = new Uint8Array(prfOutput);\n\tconst keyBytes = hkdf(sha256, ikm, salt, HKDF_INFO, 32);\n\treturn crypto.subtle.importKey(\"raw\", keyBytes, { name: \"AES-GCM\" }, false, [\n\t\t\"encrypt\",\n\t\t\"decrypt\",\n\t]);\n}\n\n// ── Main class ───────────────────────────────────────────────────────────────\n\nexport class CryptoIdentityKeystore {\n\t/**\n\t * One-time setup for a device: generates an Ed25519 keypair, creates a\n\t * WebAuthn credential with PRF extension, encrypts the private key, and\n\t * stores everything in IndexedDB.\n\t *\n\t * Returns the base64url-encoded public key. The caller must register this\n\t * key with the server via POST /auth/register (first device) or\n\t * POST /auth/keys (additional device).\n\t *\n\t * @param username - The user's account name.\n\t * @param rpId - WebAuthn relying party ID (e.g. \"example.com\").\n\t * @param rpName - Human-readable relying party name.\n\t */\n\tasync register(username: string, rpId: string, rpName: string): Promise<{publicKey: string; x25519PublicKey: string}> {\n\t\t// 1. Generate Ed25519 keypair\n\t\tconst privateKey = ed.utils.randomPrivateKey();\n\t\tconst publicKey = await ed.getPublicKeyAsync(privateKey);\n\n\t\t// 2. Generate per-enrollment salt\n\t\tconst salt = crypto.getRandomValues(new Uint8Array(32));\n\n\t\t// 3. Create WebAuthn credential with PRF extension\n\t\tconst credential = await navigator.credentials.create({\n\t\t\tpublicKey: {\n\t\t\t\tchallenge: crypto.getRandomValues(new Uint8Array(32)),\n\t\t\t\trp: { id: rpId, name: rpName },\n\t\t\t\tuser: {\n\t\t\t\t\tid: new TextEncoder().encode(username),\n\t\t\t\t\tname: username,\n\t\t\t\t\tdisplayName: username,\n\t\t\t\t},\n\t\t\t\tpubKeyCredParams: [\n\t\t\t\t\t{ alg: -7, type: \"public-key\" }, // ES256\n\t\t\t\t\t{ alg: -257, type: \"public-key\" }, // RS256\n\t\t\t\t],\n\t\t\t\tauthenticatorSelection: {\n\t\t\t\t\tuserVerification: \"required\",\n\t\t\t\t},\n\t\t\t\textensions: {\n\t\t\t\t\tprf: { eval: { first: salt.buffer } },\n\t\t\t\t} as AuthenticationExtensionsClientInputs,\n\t\t\t},\n\t\t}) as PublicKeyCredential | null;\n\n\t\tif (!credential) {\n\t\t\tthrow new Error(\"WebAuthn credential creation failed\");\n\t\t}\n\n\t\tconst extResults = credential.getClientExtensionResults() as {\n\t\t\tprf?: { results?: { first?: ArrayBuffer } };\n\t\t};\n\t\tconst prfOutput = extResults?.prf?.results?.first;\n\t\tif (!prfOutput) {\n\t\t\tthrow new Error(\n\t\t\t\t\"WebAuthn PRF extension not available on this authenticator. \" +\n\t\t\t\t\t\"A PRF-capable authenticator (e.g. platform authenticator with PRF support) is required.\",\n\t\t\t);\n\t\t}\n\n\t\t// 4. Derive AES key from PRF output via HKDF\n\t\tconst aesKey = await deriveAesKey(prfOutput, salt);\n\n\t\t// 5. Encrypt private key\n\t\tconst iv = crypto.getRandomValues(new Uint8Array(12));\n\t\tconst encryptedPrivateKey = await crypto.subtle.encrypt(\n\t\t\t{ name: \"AES-GCM\", iv },\n\t\t\taesKey,\n\t\t\tprivateKey,\n\t\t);\n\n\t\t// 6. Store in IndexedDB\n\t\tconst db = await openDb();\n\t\tawait dbPut(db, {\n\t\t\tusername,\n\t\t\tpublicKey: toBase64url(publicKey),\n\t\t\tencryptedPrivateKey,\n\t\t\tiv,\n\t\t\tsalt,\n\t\t\tcredentialId: credential.rawId,\n\t\t});\n\t\tdb.close();\n\n\t\tconst x25519Pub = nobleEd25519Curves.utils.toMontgomery(publicKey);\n\t\treturn { publicKey: toBase64url(publicKey), x25519PublicKey: toBase64url(x25519Pub) };\n\t}\n\n\t/**\n\t * Sign a base64url-encoded challenge using the stored Ed25519 private key.\n\t *\n\t * This triggers a WebAuthn assertion (biometric / PIN prompt) to unlock the\n\t * private key via PRF → HKDF → AES-GCM decryption. The private key is\n\t * wiped from memory after signing.\n\t *\n\t * @param challengeB64 - base64url-encoded challenge bytes from the server.\n\t * @returns base64url-encoded Ed25519 signature (64 bytes).\n\t */\n\tasync sign(challengeB64: string): Promise<string> {\n\t\tconst db = await openDb();\n\t\tconst stored = await dbGet(db);\n\t\tdb.close();\n\n\t\tif (!stored) {\n\t\t\tthrow new Error(\"No identity stored. Call register() first.\");\n\t\t}\n\n\t\t// WebAuthn assertion with PRF\n\t\tconst assertion = await navigator.credentials.get({\n\t\t\tpublicKey: {\n\t\t\t\tchallenge: crypto.getRandomValues(new Uint8Array(32)),\n\t\t\t\tallowCredentials: [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: stored.credentialId,\n\t\t\t\t\t\ttype: \"public-key\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tuserVerification: \"required\",\n\t\t\t\textensions: {\n\t\t\t\t\tprf: { eval: { first: stored.salt.buffer } },\n\t\t\t\t} as AuthenticationExtensionsClientInputs,\n\t\t\t},\n\t\t}) as PublicKeyCredential | null;\n\n\t\tif (!assertion) {\n\t\t\tthrow new Error(\"WebAuthn assertion failed\");\n\t\t}\n\n\t\tconst extResults = assertion.getClientExtensionResults() as {\n\t\t\tprf?: { results?: { first?: ArrayBuffer } };\n\t\t};\n\t\tconst prfOutput = extResults?.prf?.results?.first;\n\t\tif (!prfOutput) {\n\t\t\tthrow new Error(\"PRF output not available from authenticator\");\n\t\t}\n\n\t\t// Derive the same AES key\n\t\tconst aesKey = await deriveAesKey(prfOutput, stored.salt);\n\n\t\t// Decrypt private key\n\t\tconst privateKeyBytes = await crypto.subtle.decrypt(\n\t\t\t{ name: \"AES-GCM\", iv: stored.iv },\n\t\t\taesKey,\n\t\t\tstored.encryptedPrivateKey,\n\t\t);\n\n\t\tconst privateKey = new Uint8Array(privateKeyBytes);\n\n\t\t// Sign the challenge\n\t\tconst challengeBytes = fromBase64url(challengeB64);\n\t\tconst signature = await ed.signAsync(challengeBytes, privateKey);\n\n\t\t// Wipe private key from memory\n\t\tprivateKey.fill(0);\n\n\t\treturn toBase64url(signature);\n\t}\n\n\t/** Returns the stored base64url public key, or null if no identity exists. */\n\tasync getPublicKey(): Promise<string | null> {\n\t\tconst db = await openDb();\n\t\tconst stored = await dbGet(db);\n\t\tdb.close();\n\t\treturn stored?.publicKey ?? null;\n\t}\n\n\t/**\n\t * Returns the locally-stored internal username label, or null if no identity exists.\n\t *\n\t * This is NOT the auth identifier (the public key is). It can be used as a\n\t * hint when calling POST /auth/register, or displayed before the user sets\n\t * a real display name via PATCH /users/me.\n\t */\n\tasync getUsername(): Promise<string | null> {\n\t\tconst db = await openDb();\n\t\tconst stored = await dbGet(db);\n\t\tdb.close();\n\t\treturn stored?.username ?? null;\n\t}\n\n\t/** Returns true if an identity is stored in IndexedDB. */\n\tasync hasIdentity(): Promise<boolean> {\n\t\tconst db = await openDb();\n\t\tconst stored = await dbGet(db);\n\t\tdb.close();\n\t\treturn stored !== undefined;\n\t}\n\n\t/** Remove the stored identity from IndexedDB. */\n\tasync clear(): Promise<void> {\n\t\tconst db = await openDb();\n\t\tawait dbDelete(db);\n\t\tdb.close();\n\t}\n\n\t/**\n\t * Returns the X25519 public key derived from the stored Ed25519 private key.\n\t * Does NOT require WebAuthn — computed from the stored encrypted key... actually\n\t * we derive from the Ed25519 public key directly (Montgomery form), no decryption needed\n\t * since nobleEd25519Curves.utils.toMontgomery only needs the public key.\n\t * Returns null if no identity is stored.\n\t */\n\tasync getX25519PublicKey(): Promise<Uint8Array | null> {\n\t\tconst db = await openDb();\n\t\tconst stored = await dbGet(db);\n\t\tdb.close();\n\t\tif (!stored) return null;\n\t\tconst edPub = fromBase64url(stored.publicKey);\n\t\treturn nobleEd25519Curves.utils.toMontgomery(edPub);\n\t}\n\n\t/**\n\t * Returns the X25519 private key derived from the stored Ed25519 private key.\n\t * Requires WebAuthn assertion to decrypt the private key.\n\t * The caller MUST wipe the returned Uint8Array after use.\n\t */\n\tasync getX25519PrivateKey(): Promise<Uint8Array> {\n\t\tconst db = await openDb();\n\t\tconst stored = await dbGet(db);\n\t\tdb.close();\n\n\t\tif (!stored) {\n\t\t\tthrow new Error(\"No identity stored. Call register() first.\");\n\t\t}\n\n\t\tconst assertion = await navigator.credentials.get({\n\t\t\tpublicKey: {\n\t\t\t\tchallenge: crypto.getRandomValues(new Uint8Array(32)),\n\t\t\t\tallowCredentials: [{ id: stored.credentialId, type: \"public-key\" }],\n\t\t\t\tuserVerification: \"required\",\n\t\t\t\textensions: {\n\t\t\t\t\tprf: { eval: { first: stored.salt.buffer } },\n\t\t\t\t} as AuthenticationExtensionsClientInputs,\n\t\t\t},\n\t\t}) as PublicKeyCredential | null;\n\n\t\tif (!assertion) throw new Error(\"WebAuthn assertion failed\");\n\n\t\tconst extResults = assertion.getClientExtensionResults() as {\n\t\t\tprf?: { results?: { first?: ArrayBuffer } };\n\t\t};\n\t\tconst prfOutput = extResults?.prf?.results?.first;\n\t\tif (!prfOutput) throw new Error(\"PRF output not available from authenticator\");\n\n\t\tconst aesKey = await deriveAesKey(prfOutput, stored.salt);\n\t\tconst privateKeyBytes = await crypto.subtle.decrypt(\n\t\t\t{ name: \"AES-GCM\", iv: stored.iv },\n\t\t\taesKey,\n\t\t\tstored.encryptedPrivateKey,\n\t\t);\n\t\tconst edPrivKey = new Uint8Array(privateKeyBytes);\n\t\tconst x25519Priv = nobleEd25519Curves.utils.toMontgomerySecret(edPrivKey);\n\t\tedPrivKey.fill(0);\n\t\treturn x25519Priv;\n\t}\n}\n","/**\n * IndexedDB-backed cache for REST API metadata (documents, children, profiles,\n * permissions, uploads). Provides offline-first read access to data fetched\n * from the server.\n *\n * Each entry carries a `cachedAt` timestamp; reads return null once the TTL\n * has elapsed. The cache is scoped by server origin so the same app can work\n * against multiple backends without cross-contamination.\n *\n * Designed to be passed to AbracadabraClientConfig.cache so the client\n * automatically checks the cache before hitting the network.\n */\n\nimport type {\n\tDocumentMeta,\n\tUserProfile,\n\tPermissionEntry,\n\tUploadInfo,\n} from \"./types.ts\";\n\nconst DB_VERSION = 1;\nconst DEFAULT_TTL_MS = 5 * 60 * 1000; // 5 minutes\n\nfunction idbAvailable(): boolean {\n\treturn typeof globalThis !== \"undefined\" && \"indexedDB\" in globalThis;\n}\n\nfunction openDb(origin: string): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = globalThis.indexedDB.open(\n\t\t\t`abracadabra:meta-cache:${origin}`,\n\t\t\tDB_VERSION,\n\t\t);\n\n\t\treq.onupgradeneeded = (event) => {\n\t\t\tconst db = (event.target as IDBOpenDBRequest).result;\n\t\t\tfor (const name of [\"doc_meta\", \"children\", \"user_profile\", \"permissions\", \"uploads\"]) {\n\t\t\t\tif (!db.objectStoreNames.contains(name)) {\n\t\t\t\t\tdb.createObjectStore(name);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nfunction txPromise<T>(store: IDBObjectStore, request: IDBRequest<T>): Promise<T> {\n\treturn new Promise((resolve, reject) => {\n\t\trequest.onsuccess = () => resolve(request.result);\n\t\trequest.onerror = () => reject(request.error);\n\t});\n}\n\nexport interface DocumentCacheOptions {\n\t/** How long cached entries remain valid. Default: 5 minutes. */\n\tttlMs?: number;\n}\n\nexport class DocumentCache {\n\tprivate readonly origin: string;\n\tprivate readonly ttlMs: number;\n\tprivate dbPromise: Promise<IDBDatabase | null> | null = null;\n\tprivate db: IDBDatabase | null = null;\n\n\tconstructor(serverOrigin: string, opts?: DocumentCacheOptions) {\n\t\tthis.origin = serverOrigin;\n\t\tthis.ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;\n\t}\n\n\tprivate getDb(): Promise<IDBDatabase | null> {\n\t\tif (!idbAvailable()) return Promise.resolve(null);\n\t\tif (!this.dbPromise) {\n\t\t\tthis.dbPromise = openDb(this.origin)\n\t\t\t\t.catch(() => null)\n\t\t\t\t.then((db) => {\n\t\t\t\t\tthis.db = db;\n\t\t\t\t\treturn db;\n\t\t\t\t});\n\t\t}\n\t\treturn this.dbPromise;\n\t}\n\n\tprivate isExpired(cachedAt: number): boolean {\n\t\treturn Date.now() - cachedAt > this.ttlMs;\n\t}\n\n\t// ── Generic TTL helpers ───────────────────────────────────────────────────\n\n\tprivate async getWithTtl<T>(\n\t\tstoreName: string,\n\t\tkey: string,\n\t): Promise<T | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(storeName, \"readonly\");\n\t\tconst result = await txPromise<{ value: T; cachedAt: number } | undefined>(\n\t\t\ttx.objectStore(storeName),\n\t\t\ttx.objectStore(storeName).get(key),\n\t\t);\n\t\tif (!result) return null;\n\t\tif (this.isExpired(result.cachedAt)) {\n\t\t\t// Stale — evict asynchronously and signal miss\n\t\t\tthis.deleteKey(storeName, key).catch(() => null);\n\t\t\treturn null;\n\t\t}\n\t\treturn result.value;\n\t}\n\n\tprivate async setWithTtl<T>(storeName: string, key: string, value: T): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst entry = { value, cachedAt: Date.now() };\n\t\tconst tx = db.transaction(storeName, \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(storeName),\n\t\t\ttx.objectStore(storeName).put(entry, key),\n\t\t);\n\t}\n\n\tprivate async deleteKey(storeName: string, key: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(storeName, \"readwrite\");\n\t\tawait txPromise(tx.objectStore(storeName), tx.objectStore(storeName).delete(key));\n\t}\n\n\t// ── Document metadata ─────────────────────────────────────────────────────\n\n\tasync getDoc(docId: string): Promise<DocumentMeta | null> {\n\t\treturn this.getWithTtl<DocumentMeta>(\"doc_meta\", docId);\n\t}\n\n\tasync setDoc(meta: DocumentMeta): Promise<void> {\n\t\treturn this.setWithTtl(\"doc_meta\", meta.id, meta);\n\t}\n\n\tasync invalidateDoc(docId: string): Promise<void> {\n\t\tawait this.deleteKey(\"doc_meta\", docId).catch(() => null);\n\t}\n\n\t// ── Children list ─────────────────────────────────────────────────────────\n\n\tasync getChildren(parentId: string): Promise<string[] | null> {\n\t\treturn this.getWithTtl<string[]>(\"children\", parentId);\n\t}\n\n\tasync setChildren(parentId: string, items: string[]): Promise<void> {\n\t\treturn this.setWithTtl(\"children\", parentId, items);\n\t}\n\n\tasync invalidateChildren(parentId: string): Promise<void> {\n\t\tawait this.deleteKey(\"children\", parentId).catch(() => null);\n\t}\n\n\t// ── User profile ──────────────────────────────────────────────────────────\n\n\tasync getProfile(userId: string): Promise<UserProfile | null> {\n\t\treturn this.getWithTtl<UserProfile>(\"user_profile\", userId);\n\t}\n\n\tasync setProfile(profile: UserProfile): Promise<void> {\n\t\treturn this.setWithTtl(\"user_profile\", profile.id, profile);\n\t}\n\n\t/** Get the cached profile for the currently authenticated user. */\n\tasync getCurrentProfile(): Promise<UserProfile | null> {\n\t\treturn this.getWithTtl<UserProfile>(\"user_profile\", \"__current__\");\n\t}\n\n\t/** Cache a profile both by its ID and as the current user. */\n\tasync setCurrentProfile(profile: UserProfile): Promise<void> {\n\t\tawait Promise.all([\n\t\t\tthis.setWithTtl(\"user_profile\", profile.id, profile),\n\t\t\tthis.setWithTtl(\"user_profile\", \"__current__\", profile),\n\t\t]);\n\t}\n\n\t// ── Permissions ───────────────────────────────────────────────────────────\n\n\tasync getPermissions(docId: string): Promise<PermissionEntry[] | null> {\n\t\treturn this.getWithTtl<PermissionEntry[]>(\"permissions\", docId);\n\t}\n\n\tasync setPermissions(docId: string, items: PermissionEntry[]): Promise<void> {\n\t\treturn this.setWithTtl(\"permissions\", docId, items);\n\t}\n\n\t// ── Uploads list ──────────────────────────────────────────────────────────\n\n\tasync getUploads(docId: string): Promise<UploadInfo[] | null> {\n\t\treturn this.getWithTtl<UploadInfo[]>(\"uploads\", docId);\n\t}\n\n\tasync setUploads(docId: string, items: UploadInfo[]): Promise<void> {\n\t\treturn this.setWithTtl(\"uploads\", docId, items);\n\t}\n\n\tasync invalidateUploads(docId: string): Promise<void> {\n\t\tawait this.deleteKey(\"uploads\", docId).catch(() => null);\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\tdestroy(): void {\n\t\tthis.db?.close();\n\t\tthis.db = null;\n\t}\n}\n","/**\n * IndexedDB-backed trigram full-text search index.\n *\n * Generic: caller passes (docId, texts[]) — works for Y.Doc text content,\n * file names, document titles, or any other text. No Y.js coupling.\n *\n * Algorithm: trigram inverted index.\n * - Each document is decomposed into overlapping 3-character windows.\n * - The \"postings\" store maps trigram → [docId, ...].\n * - The \"doc_trigrams\" store maps docId → [trigram, ...] for efficient removal.\n * - search() scores by number of query trigrams that match.\n *\n * IDB transactions that touch multiple stores use the callback-only pattern\n * (not async/await inside a transaction) to avoid the transaction auto-commit\n * issue across microtask boundaries.\n */\n\nimport type { SearchResult } from \"./types.ts\";\n\nconst DB_VERSION = 1;\n\nfunction idbAvailable(): boolean {\n\treturn typeof globalThis !== \"undefined\" && \"indexedDB\" in globalThis;\n}\n\nfunction openDb(origin: string): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = globalThis.indexedDB.open(`abracadabra:search:${origin}`, DB_VERSION);\n\n\t\treq.onupgradeneeded = (event) => {\n\t\t\tconst db = (event.target as IDBOpenDBRequest).result;\n\t\t\tif (!db.objectStoreNames.contains(\"postings\")) {\n\t\t\t\tdb.createObjectStore(\"postings\");\n\t\t\t}\n\t\t\tif (!db.objectStoreNames.contains(\"doc_trigrams\")) {\n\t\t\t\tdb.createObjectStore(\"doc_trigrams\");\n\t\t\t}\n\t\t};\n\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\n/** Extract the set of trigrams for a piece of text. */\nfunction extractTrigrams(text: string): Set<string> {\n\tconst trigrams = new Set<string>();\n\tconst padded = ` ${text.toLowerCase()} `;\n\tfor (let i = 0; i <= padded.length - 3; i++) {\n\t\ttrigrams.add(padded.slice(i, i + 3));\n\t}\n\treturn trigrams;\n}\n\n/** Merge trigrams from multiple texts into a single set. */\nfunction extractAllTrigrams(texts: string[]): Set<string> {\n\tconst result = new Set<string>();\n\tfor (const t of texts) {\n\t\tfor (const trigram of extractTrigrams(t)) {\n\t\t\tresult.add(trigram);\n\t\t}\n\t}\n\treturn result;\n}\n\nexport class SearchIndex {\n\tprivate readonly origin: string;\n\tprivate dbPromise: Promise<IDBDatabase | null> | null = null;\n\tprivate db: IDBDatabase | null = null;\n\n\tconstructor(serverOrigin: string) {\n\t\tthis.origin = serverOrigin;\n\t}\n\n\tprivate getDb(): Promise<IDBDatabase | null> {\n\t\tif (!idbAvailable()) return Promise.resolve(null);\n\t\tif (!this.dbPromise) {\n\t\t\tthis.dbPromise = openDb(this.origin)\n\t\t\t\t.catch(() => null)\n\t\t\t\t.then((db) => {\n\t\t\t\t\tthis.db = db;\n\t\t\t\t\treturn db;\n\t\t\t\t});\n\t\t}\n\t\treturn this.dbPromise;\n\t}\n\n\t/**\n\t * Replace the index for docId with the given texts.\n\t * Old trigram associations are removed before new ones are added.\n\t */\n\tasync index(docId: string, texts: string[]): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\n\t\tconst newTrigrams = extractAllTrigrams(texts);\n\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst tx = db.transaction([\"postings\", \"doc_trigrams\"], \"readwrite\");\n\t\t\ttx.oncomplete = () => resolve();\n\t\t\ttx.onerror = () => reject(tx.error);\n\n\t\t\tconst postings = tx.objectStore(\"postings\");\n\t\t\tconst docTrigramsStore = tx.objectStore(\"doc_trigrams\");\n\n\t\t\t// Step 1: read old trigrams for this doc\n\t\t\tconst oldReq = docTrigramsStore.get(docId);\n\t\t\toldReq.onsuccess = () => {\n\t\t\t\tconst oldTrigrams: string[] = oldReq.result ?? [];\n\t\t\t\tlet pending = oldTrigrams.length + newTrigrams.size + 1; // +1 for doc_trigrams write\n\n\t\t\t\tfunction done() {\n\t\t\t\t\tpending--;\n\t\t\t\t\t// tx.oncomplete fires naturally once all requests settle\n\t\t\t\t}\n\n\t\t\t\t// Step 2: remove docId from each old trigram's posting list\n\t\t\t\tfor (const trigram of oldTrigrams) {\n\t\t\t\t\tconst req = postings.get(trigram);\n\t\t\t\t\treq.onsuccess = () => {\n\t\t\t\t\t\tconst list: string[] = req.result ?? [];\n\t\t\t\t\t\tconst updated = list.filter((id) => id !== docId);\n\t\t\t\t\t\tif (updated.length === 0) {\n\t\t\t\t\t\t\tpostings.delete(trigram);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpostings.put(updated, trigram);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdone();\n\t\t\t\t\t};\n\t\t\t\t\treq.onerror = done;\n\t\t\t\t}\n\n\t\t\t\t// Step 3: add docId to each new trigram's posting list\n\t\t\t\tfor (const trigram of newTrigrams) {\n\t\t\t\t\tconst req = postings.get(trigram);\n\t\t\t\t\treq.onsuccess = () => {\n\t\t\t\t\t\tconst list: string[] = req.result ?? [];\n\t\t\t\t\t\tif (!list.includes(docId)) {\n\t\t\t\t\t\t\tlist.push(docId);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpostings.put(list, trigram);\n\t\t\t\t\t\tdone();\n\t\t\t\t\t};\n\t\t\t\t\treq.onerror = done;\n\t\t\t\t}\n\n\t\t\t\t// Step 4: save new trigram set for this doc\n\t\t\t\tconst writeReq = docTrigramsStore.put([...newTrigrams], docId);\n\t\t\t\twriteReq.onsuccess = done;\n\t\t\t\twriteReq.onerror = done;\n\t\t\t};\n\t\t\toldReq.onerror = () => reject(oldReq.error);\n\t\t});\n\t}\n\n\t/** Remove all indexed content for a document. */\n\tasync remove(docId: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst tx = db.transaction([\"postings\", \"doc_trigrams\"], \"readwrite\");\n\t\t\ttx.oncomplete = () => resolve();\n\t\t\ttx.onerror = () => reject(tx.error);\n\n\t\t\tconst postings = tx.objectStore(\"postings\");\n\t\t\tconst docTrigramsStore = tx.objectStore(\"doc_trigrams\");\n\n\t\t\tconst oldReq = docTrigramsStore.get(docId);\n\t\t\toldReq.onsuccess = () => {\n\t\t\t\tconst oldTrigrams: string[] = oldReq.result ?? [];\n\n\t\t\t\tfor (const trigram of oldTrigrams) {\n\t\t\t\t\tconst req = postings.get(trigram);\n\t\t\t\t\treq.onsuccess = () => {\n\t\t\t\t\t\tconst list: string[] = req.result ?? [];\n\t\t\t\t\t\tconst updated = list.filter((id) => id !== docId);\n\t\t\t\t\t\tif (updated.length === 0) {\n\t\t\t\t\t\t\tpostings.delete(trigram);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpostings.put(updated, trigram);\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tdocTrigramsStore.delete(docId);\n\t\t\t};\n\t\t\toldReq.onerror = () => reject(oldReq.error);\n\t\t});\n\t}\n\n\t/**\n\t * Search for documents matching the query.\n\t * Returns results sorted by score (matching trigram count) descending.\n\t */\n\tasync search(query: string, limit = 20): Promise<SearchResult[]> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\n\t\tconst queryTrigrams = [...extractTrigrams(query)];\n\t\tif (queryTrigrams.length === 0) return [];\n\n\t\treturn new Promise<SearchResult[]>((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"postings\", \"readonly\");\n\t\t\tconst postings = tx.objectStore(\"postings\");\n\t\t\tconst scores = new Map<string, number>();\n\t\t\tlet remaining = queryTrigrams.length;\n\n\t\t\tfor (const trigram of queryTrigrams) {\n\t\t\t\tconst req = postings.get(trigram);\n\t\t\t\treq.onsuccess = () => {\n\t\t\t\t\tconst docIds: string[] = req.result ?? [];\n\t\t\t\t\tfor (const docId of docIds) {\n\t\t\t\t\t\tscores.set(docId, (scores.get(docId) ?? 0) + 1);\n\t\t\t\t\t}\n\t\t\t\t\tremaining--;\n\t\t\t\t\tif (remaining === 0) {\n\t\t\t\t\t\tconst results: SearchResult[] = [...scores.entries()]\n\t\t\t\t\t\t\t.map(([docId, score]) => ({ docId, score }))\n\t\t\t\t\t\t\t.sort((a, b) => b.score - a.score)\n\t\t\t\t\t\t\t.slice(0, limit);\n\t\t\t\t\t\tresolve(results);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\treq.onerror = () => {\n\t\t\t\t\tremaining--;\n\t\t\t\t\tif (remaining === 0) {\n\t\t\t\t\t\tconst results: SearchResult[] = [...scores.entries()]\n\t\t\t\t\t\t\t.map(([docId, score]) => ({ docId, score }))\n\t\t\t\t\t\t\t.sort((a, b) => b.score - a.score)\n\t\t\t\t\t\t\t.slice(0, limit);\n\t\t\t\t\t\tresolve(results);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\n\t\t\ttx.onerror = () => reject(tx.error);\n\t\t});\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\tdestroy(): void {\n\t\tthis.db?.close();\n\t\tthis.db = null;\n\t}\n}\n","/**\n * IndexedDB-backed file blob cache with an offline-tolerant upload queue.\n *\n * Responsibilities:\n * - Cache downloaded file blobs locally so they can be served offline via\n * object URLs (URL.createObjectURL).\n * - Queue file uploads when the network is unavailable. The queue persists\n * across page reloads (IndexedDB-backed).\n * - Auto-flush the upload queue when the browser reports it is back online,\n * and expose flushQueue() for manual flushing.\n *\n * Events:\n * - \"upload:queued\" — entry added to queue\n * - \"upload:started\" — upload attempt started\n * - \"upload:done\" — upload succeeded\n * - \"upload:error\" — upload attempt failed\n *\n * Falls back to a silent no-op when IndexedDB is unavailable (SSR / Node.js).\n */\n\nimport type { UploadQueueEntry } from \"./types.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport EventEmitter from \"./EventEmitter.ts\";\n\nconst DB_VERSION = 1;\n\nfunction idbAvailable(): boolean {\n\treturn typeof globalThis !== \"undefined\" && \"indexedDB\" in globalThis;\n}\n\nfunction openDb(origin: string): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = globalThis.indexedDB.open(`abracadabra:files:${origin}`, DB_VERSION);\n\n\t\treq.onupgradeneeded = (event) => {\n\t\t\tconst db = (event.target as IDBOpenDBRequest).result;\n\t\t\tif (!db.objectStoreNames.contains(\"blobs\")) {\n\t\t\t\tdb.createObjectStore(\"blobs\");\n\t\t\t}\n\t\t\tif (!db.objectStoreNames.contains(\"upload_queue\")) {\n\t\t\t\tdb.createObjectStore(\"upload_queue\", { keyPath: \"id\" });\n\t\t\t}\n\t\t};\n\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nfunction txPromise<T>(store: IDBObjectStore, request: IDBRequest<T>): Promise<T> {\n\treturn new Promise((resolve, reject) => {\n\t\trequest.onsuccess = () => resolve(request.result);\n\t\trequest.onerror = () => reject(request.error);\n\t});\n}\n\ninterface BlobCacheEntry {\n\tblob: Blob;\n\tmime_type: string;\n\tfilename: string;\n\tcachedAt: number;\n}\n\nexport class FileBlobStore extends EventEmitter {\n\tprivate readonly origin: string;\n\tprivate readonly client: AbracadabraClient;\n\tprivate dbPromise: Promise<IDBDatabase | null> | null = null;\n\tprivate db: IDBDatabase | null = null;\n\n\t/** Tracks active object URLs so we can revoke them on destroy. */\n\tprivate readonly objectUrls = new Map<string, string>();\n\n\t/** Prevents concurrent flush runs. */\n\tprivate _flushing = false;\n\n\tprivate readonly _onlineHandler: () => void;\n\n\tconstructor(serverOrigin: string, client: AbracadabraClient) {\n\t\tsuper();\n\t\tthis.origin = serverOrigin;\n\t\tthis.client = client;\n\n\t\tthis._onlineHandler = () => { this.flushQueue().catch(() => null); };\n\t\tif (typeof window !== \"undefined\") {\n\t\t\twindow.addEventListener(\"online\", this._onlineHandler);\n\t\t}\n\t}\n\n\tprivate getDb(): Promise<IDBDatabase | null> {\n\t\tif (!idbAvailable()) return Promise.resolve(null);\n\t\tif (!this.dbPromise) {\n\t\t\tthis.dbPromise = openDb(this.origin)\n\t\t\t\t.catch(() => null)\n\t\t\t\t.then((db) => {\n\t\t\t\t\tthis.db = db;\n\t\t\t\t\treturn db;\n\t\t\t\t});\n\t\t}\n\t\treturn this.dbPromise;\n\t}\n\n\tprivate blobKey(docId: string, uploadId: string): string {\n\t\treturn `${docId}/${uploadId}`;\n\t}\n\n\t// ── Blob cache ────────────────────────────────────────────────────────────\n\n\t/**\n\t * Return a local object URL for a file.\n\t * On first call the blob is downloaded from the server and cached in IDB.\n\t * Returns null when offline and the blob is not yet cached, or when\n\t * URL.createObjectURL is unavailable (e.g. Node.js / SSR).\n\t */\n\tasync getBlobUrl(docId: string, uploadId: string): Promise<string | null> {\n\t\t// Object URLs are only meaningful in browser environments.\n\t\tif (typeof window === \"undefined\") return null;\n\n\t\tconst key = this.blobKey(docId, uploadId);\n\n\t\t// Reuse existing in-memory object URL if available\n\t\tconst existing = this.objectUrls.get(key);\n\t\tif (existing) return existing;\n\n\t\tconst db = await this.getDb();\n\t\tif (db) {\n\t\t\tconst tx = db.transaction(\"blobs\", \"readonly\");\n\t\t\tconst entry = await txPromise<BlobCacheEntry | undefined>(\n\t\t\t\ttx.objectStore(\"blobs\"),\n\t\t\t\ttx.objectStore(\"blobs\").get(key),\n\t\t\t);\n\t\t\tif (entry) {\n\t\t\t\tconst url = URL.createObjectURL(entry.blob);\n\t\t\t\tthis.objectUrls.set(key, url);\n\t\t\t\treturn url;\n\t\t\t}\n\t\t}\n\n\t\t// Not cached — try downloading\n\t\tlet blob: Blob;\n\t\ttry {\n\t\t\tblob = await this.client.getUpload(docId, uploadId);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Cache the blob\n\t\tif (db) {\n\t\t\tconst entry: BlobCacheEntry = {\n\t\t\t\tblob,\n\t\t\t\tmime_type: blob.type,\n\t\t\t\tfilename: uploadId,\n\t\t\t\tcachedAt: Date.now(),\n\t\t\t};\n\t\t\tconst tx = db.transaction(\"blobs\", \"readwrite\");\n\t\t\ttx.objectStore(\"blobs\").put(entry, key);\n\t\t}\n\n\t\tconst url = URL.createObjectURL(blob);\n\t\tthis.objectUrls.set(key, url);\n\t\treturn url;\n\t}\n\n\t/**\n\t * Store a blob directly into the cache under the given (docId, uploadId) key\n\t * and return its object URL. Use this to pre-populate the cache for files\n\t * that haven't been uploaded to the server yet (e.g. offline upload queue).\n\t */\n\tasync putBlob(\n\t\tdocId: string,\n\t\tuploadId: string,\n\t\tblob: Blob,\n\t\tfilename: string,\n\t): Promise<string> {\n\t\tif (typeof window === \"undefined\") return URL.createObjectURL(blob);\n\n\t\tconst key = this.blobKey(docId, uploadId);\n\n\t\t// Return existing URL if already cached in-memory\n\t\tconst existing = this.objectUrls.get(key);\n\t\tif (existing) return existing;\n\n\t\tconst db = await this.getDb();\n\t\tif (db) {\n\t\t\tconst entry: BlobCacheEntry = {\n\t\t\t\tblob,\n\t\t\t\tmime_type: blob.type || \"application/octet-stream\",\n\t\t\t\tfilename,\n\t\t\t\tcachedAt: Date.now(),\n\t\t\t};\n\t\t\tconst tx = db.transaction(\"blobs\", \"readwrite\");\n\t\t\ttx.objectStore(\"blobs\").put(entry, key);\n\t\t}\n\n\t\tconst url = URL.createObjectURL(blob);\n\t\tthis.objectUrls.set(key, url);\n\t\treturn url;\n\t}\n\n\t/** Revoke the object URL and remove the blob from cache. */\n\tasync evictBlob(docId: string, uploadId: string): Promise<void> {\n\t\tconst key = this.blobKey(docId, uploadId);\n\n\t\tconst url = this.objectUrls.get(key);\n\t\tif (url) {\n\t\t\tURL.revokeObjectURL(url);\n\t\t\tthis.objectUrls.delete(key);\n\t\t}\n\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"blobs\", \"readwrite\");\n\t\tawait txPromise(tx.objectStore(\"blobs\"), tx.objectStore(\"blobs\").delete(key));\n\t}\n\n\t// ── Upload queue ──────────────────────────────────────────────────────────\n\n\t/**\n\t * Queue a file for upload. Works offline — the entry is persisted to IDB\n\t * and flushed the next time the queue is flushed.\n\t * Returns the generated queue entry id.\n\t */\n\tasync queueUpload(\n\t\tdocId: string,\n\t\tfile: File | Blob,\n\t\tfilename?: string,\n\t): Promise<string> {\n\t\tconst id = crypto.randomUUID();\n\t\tconst resolvedFilename =\n\t\t\tfile instanceof File ? file.name : (filename ?? \"file\");\n\n\t\tconst entry: UploadQueueEntry = {\n\t\t\tid,\n\t\t\tdocId,\n\t\t\tfile,\n\t\t\tfilename: resolvedFilename,\n\t\t\tstatus: \"pending\",\n\t\t\tcreatedAt: Date.now(),\n\t\t};\n\n\t\tconst db = await this.getDb();\n\t\tif (db) {\n\t\t\tconst tx = db.transaction(\"upload_queue\", \"readwrite\");\n\t\t\tawait txPromise(\n\t\t\t\ttx.objectStore(\"upload_queue\"),\n\t\t\t\ttx.objectStore(\"upload_queue\").put(entry),\n\t\t\t);\n\t\t}\n\n\t\tthis.emit(\"upload:queued\", entry);\n\t\treturn id;\n\t}\n\n\t/** Return all upload queue entries. */\n\tasync getQueue(): Promise<UploadQueueEntry[]> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"upload_queue\", \"readonly\");\n\t\t\tconst req = tx.objectStore(\"upload_queue\").getAll();\n\t\t\treq.onsuccess = () => resolve(req.result as UploadQueueEntry[]);\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\t/**\n\t * Upload all pending queue entries via AbracadabraClient.\n\t * Safe to call repeatedly — a concurrent call is a no-op.\n\t * Entries that fail are marked with status \"error\" and left in the queue.\n\t */\n\tasync flushQueue(): Promise<void> {\n\t\tif (this._flushing) return;\n\t\tthis._flushing = true;\n\n\t\ttry {\n\t\t\tconst all = await this.getQueue();\n\t\t\tconst pending = all.filter((e) => e.status === \"pending\");\n\n\t\t\tfor (const entry of pending) {\n\t\t\t\tawait this._updateQueueEntry(entry.id, { status: \"uploading\" });\n\t\t\t\tthis.emit(\"upload:started\", { ...entry, status: \"uploading\" });\n\n\t\t\t\ttry {\n\t\t\t\t\tawait this.client.upload(entry.docId, entry.file, entry.filename);\n\t\t\t\t\tawait this._updateQueueEntry(entry.id, { status: \"done\" });\n\t\t\t\t\tthis.emit(\"upload:done\", { ...entry, status: \"done\" });\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tawait this._updateQueueEntry(entry.id, { status: \"error\", error: message });\n\t\t\t\t\tthis.emit(\"upload:error\", { ...entry, status: \"error\", error: message });\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._flushing = false;\n\t\t}\n\t}\n\n\tprivate async _updateQueueEntry(\n\t\tid: string,\n\t\tpatch: Partial<UploadQueueEntry>,\n\t): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"upload_queue\", \"readwrite\");\n\t\t\tconst store = tx.objectStore(\"upload_queue\");\n\t\t\tconst req = store.get(id);\n\t\t\treq.onsuccess = () => {\n\t\t\t\tif (!req.result) { resolve(); return; }\n\t\t\t\tconst updated = { ...req.result, ...patch };\n\t\t\t\tstore.put(updated);\n\t\t\t\ttx.oncomplete = () => resolve();\n\t\t\t\ttx.onerror = () => reject(tx.error);\n\t\t\t};\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\tdestroy(): void {\n\t\tif (typeof window !== \"undefined\") {\n\t\t\twindow.removeEventListener(\"online\", this._onlineHandler);\n\t\t}\n\n\t\t// Revoke all tracked object URLs\n\t\tfor (const url of this.objectUrls.values()) {\n\t\t\tURL.revokeObjectURL(url);\n\t\t}\n\t\tthis.objectUrls.clear();\n\n\t\tthis.db?.close();\n\t\tthis.db = null;\n\t\tthis.removeAllListeners();\n\t}\n}\n","/**\n * DocKeyManager\n *\n * Manages AES-256-GCM document keys for CSE and E2E encrypted documents.\n * Keys are wrapped per-user using X25519 ECDH + HKDF-SHA256 + AES-256-GCM.\n */\n\nimport { x25519 } from \"@noble/curves/ed25519.js\";\nimport { hkdf } from \"@noble/hashes/hkdf\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport type { CryptoIdentityKeystore } from \"./CryptoIdentityKeystore.ts\";\n\nconst HKDF_INFO = new TextEncoder().encode(\"abracadabra-dockey-v1\");\n\nfunction fromBase64(b64: string): Uint8Array {\n\treturn Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n}\n\nexport class DocKeyManager {\n\tprivate cache = new Map<string, { key: CryptoKey; epoch: number }>();\n\n\t/** Generate a new random AES-256-GCM document key. */\n\tstatic async generateDocKey(): Promise<CryptoKey> {\n\t\treturn crypto.subtle.generateKey(\n\t\t\t{ name: \"AES-GCM\", length: 256 },\n\t\t\ttrue,\n\t\t\t[\"encrypt\", \"decrypt\"],\n\t\t);\n\t}\n\n\t/**\n\t * Get (or fetch) the DocKey for a document.\n\t * Returns null if no envelope exists (user not provisioned).\n\t */\n\tasync getDocKey(\n\t\tdocId: string,\n\t\tclient: AbracadabraClient,\n\t\tkeystore: CryptoIdentityKeystore,\n\t): Promise<CryptoKey | null> {\n\t\tconst cached = this.cache.get(docId);\n\t\tif (cached) return cached.key;\n\n\t\tconst envelope = await client.getMyKeyEnvelope(docId);\n\t\tif (!envelope) return null;\n\n\t\tconst x25519PrivKey = await keystore.getX25519PrivateKey();\n\t\ttry {\n\t\t\tconst wrapped = fromBase64(envelope.encrypted_key);\n\t\t\tconst docKey = await this._unwrapKey(wrapped, x25519PrivKey, docId);\n\t\t\tthis.cache.set(docId, { key: docKey, epoch: envelope.key_epoch });\n\t\t\treturn docKey;\n\t\t} finally {\n\t\t\tx25519PrivKey.fill(0);\n\t\t}\n\t}\n\n\t/**\n\t * Wrap a DocKey for a recipient.\n\t * Output: [ephemeralPub(32) || nonce(12) || ciphertext(~48)] bytes\n\t */\n\tasync wrapKeyForRecipient(\n\t\tdocKey: CryptoKey,\n\t\trecipientX25519PubKey: Uint8Array,\n\t\tdocId: string,\n\t): Promise<Uint8Array> {\n\t\tconst ephemeralPriv = crypto.getRandomValues(new Uint8Array(32));\n\t\tconst ephemeralPub = x25519.getPublicKey(ephemeralPriv);\n\t\tconst sharedSecret = x25519.getSharedSecret(ephemeralPriv, recipientX25519PubKey);\n\n\t\tconst salt = new TextEncoder().encode(docId);\n\t\tconst keyBytes = hkdf(sha256, sharedSecret, salt, HKDF_INFO, 32);\n\t\tconst wrapKey = await crypto.subtle.importKey(\"raw\", keyBytes, { name: \"AES-GCM\" }, false, [\"encrypt\"]);\n\n\t\tconst rawDocKey = await crypto.subtle.exportKey(\"raw\", docKey);\n\t\tconst nonce = crypto.getRandomValues(new Uint8Array(12));\n\t\tconst ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv: nonce }, wrapKey, rawDocKey));\n\n\t\tconst result = new Uint8Array(32 + 12 + ciphertext.length);\n\t\tresult.set(ephemeralPub, 0);\n\t\tresult.set(nonce, 32);\n\t\tresult.set(ciphertext, 44);\n\t\treturn result;\n\t}\n\n\tprivate async _unwrapKey(wrapped: Uint8Array, recipientX25519PrivKey: Uint8Array, docId: string): Promise<CryptoKey> {\n\t\tconst ephemeralPub = wrapped.slice(0, 32);\n\t\tconst nonce = wrapped.slice(32, 44);\n\t\tconst ciphertext = wrapped.slice(44);\n\n\t\tconst sharedSecret = x25519.getSharedSecret(recipientX25519PrivKey, ephemeralPub);\n\t\tconst salt = new TextEncoder().encode(docId);\n\t\tconst keyBytes = hkdf(sha256, sharedSecret, salt, HKDF_INFO, 32);\n\t\tconst wrapKey = await crypto.subtle.importKey(\"raw\", keyBytes, { name: \"AES-GCM\" }, false, [\"decrypt\"]);\n\t\tconst rawDocKey = await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: nonce }, wrapKey, ciphertext);\n\t\treturn crypto.subtle.importKey(\"raw\", rawDocKey, { name: \"AES-GCM\" }, true, [\"encrypt\", \"decrypt\"]);\n\t}\n\n\t/** Clear the cached key for a document (or all if docId omitted). */\n\tclearCache(docId?: string): void {\n\t\tif (docId) {\n\t\t\tthis.cache.delete(docId);\n\t\t} else {\n\t\t\tthis.cache.clear();\n\t\t}\n\t}\n}\n","/**\n * EncryptedY - CSE (Client-Side Encryption) primitives for Yjs documents.\n *\n * Wire format for encrypted fields: [nonce(12) || AES-GCM ciphertext]\n *\n * Limitations (documented):\n * - Concurrent writes to the same Y.Map key produce last-write-wins semantics\n * (not character-level CRDT merge), because encrypted values are opaque to Yrs.\n */\n\nimport * as Y from \"yjs\";\n\n// ── Field-level encryption ─────────────────────────────────────────────────────\n\n/** Encrypt a field value with AES-256-GCM. Returns [nonce(12) || ciphertext]. */\nexport async function encryptField(value: Uint8Array, docKey: CryptoKey): Promise<Uint8Array> {\n\tconst nonce = crypto.getRandomValues(new Uint8Array(12));\n\tconst ciphertext = new Uint8Array(\n\t\tawait crypto.subtle.encrypt({ name: \"AES-GCM\", iv: nonce }, docKey, value),\n\t);\n\tconst result = new Uint8Array(12 + ciphertext.length);\n\tresult.set(nonce, 0);\n\tresult.set(ciphertext, 12);\n\treturn result;\n}\n\n/** Decrypt a field value from [nonce(12) || ciphertext] format. */\nexport async function decryptField(ciphertext: Uint8Array, docKey: CryptoKey): Promise<Uint8Array> {\n\tconst nonce = ciphertext.slice(0, 12);\n\tconst ct = ciphertext.slice(12);\n\treturn new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: nonce }, docKey, ct));\n}\n\n// ── EncryptedYMap ─────────────────────────────────────────────────────────────\n\n/**\n * A proxy wrapper around a Y.Map<Uint8Array> that transparently encrypts\n * values on .set() and decrypts on .get().\n *\n * NOTE: Concurrent writes to the same key produce last-write-wins (LWW)\n * because encrypted values are opaque blobs from Yrs's perspective.\n */\nexport class EncryptedYMap {\n\tconstructor(\n\t\tprivate readonly ymap: Y.Map<Uint8Array>,\n\t\tprivate readonly docKey: CryptoKey,\n\t) {}\n\n\tasync set(key: string, value: Uint8Array): Promise<void> {\n\t\tconst encrypted = await encryptField(value, this.docKey);\n\t\tthis.ymap.set(key, encrypted);\n\t}\n\n\tasync get(key: string): Promise<Uint8Array | null> {\n\t\tconst encrypted = this.ymap.get(key);\n\t\tif (!encrypted) return null;\n\t\ttry {\n\t\t\treturn await decryptField(encrypted, this.docKey);\n\t\t} catch {\n\t\t\treturn null; // Decryption failed (wrong key or corrupted)\n\t\t}\n\t}\n\n\thas(key: string): boolean {\n\t\treturn this.ymap.has(key);\n\t}\n\n\tdelete(key: string): void {\n\t\tthis.ymap.delete(key);\n\t}\n\n\tget size(): number {\n\t\treturn this.ymap.size;\n\t}\n\n\t/** Get all keys (encrypted values remain opaque until .get() is called). */\n\tkeys(): string[] {\n\t\treturn Array.from(this.ymap.keys());\n\t}\n\n\t/** Observe changes on the underlying Y.Map. */\n\tobserve(f: (event: Y.YMapEvent<Uint8Array>) => void): void {\n\t\tthis.ymap.observe(f);\n\t}\n\n\tunobserve(f: (event: Y.YMapEvent<Uint8Array>) => void): void {\n\t\tthis.ymap.unobserve(f);\n\t}\n}\n\n/** Create an EncryptedYMap wrapping a Y.Map<Uint8Array>. */\nexport function makeEncryptedYMap(ymap: Y.Map<Uint8Array>, docKey: CryptoKey): EncryptedYMap {\n\treturn new EncryptedYMap(ymap, docKey);\n}\n\n// ── EncryptedYText ────────────────────────────────────────────────────────────\n\n/**\n * Stores full text as a single encrypted blob in a Y.Map<Uint8Array> under a\n * fixed field name. This is last-write-wins for the entire text field.\n *\n * NOTE: This does NOT preserve character-level CRDT merge for concurrent edits.\n * It trades CRDT merge for confidentiality.\n */\nexport class EncryptedYText {\n\tprivate readonly ymap: Y.Map<Uint8Array>;\n\n\tconstructor(\n\t\tydoc: Y.Doc,\n\t\tfieldName: string,\n\t\tprivate readonly docKey: CryptoKey,\n\t) {\n\t\tthis.ymap = ydoc.getMap(`_encrypted_${fieldName}`);\n\t}\n\n\tasync set(text: string): Promise<void> {\n\t\tconst encoded = new TextEncoder().encode(text);\n\t\tconst encrypted = await encryptField(encoded, this.docKey);\n\t\tthis.ymap.set(\"v\", encrypted);\n\t}\n\n\tasync get(): Promise<string | null> {\n\t\tconst encrypted = this.ymap.get(\"v\");\n\t\tif (!encrypted) return null;\n\t\ttry {\n\t\t\tconst decoded = await decryptField(encrypted, this.docKey);\n\t\t\treturn new TextDecoder().decode(decoded);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tobserve(f: (event: Y.YMapEvent<Uint8Array>) => void): void {\n\t\tthis.ymap.observe(f);\n\t}\n\n\tunobserve(f: (event: Y.YMapEvent<Uint8Array>) => void): void {\n\t\tthis.ymap.unobserve(f);\n\t}\n}\n\n/** Create an EncryptedYText for a field in a Y.Doc. */\nexport function makeEncryptedYText(ydoc: Y.Doc, fieldName: string, docKey: CryptoKey): EncryptedYText {\n\treturn new EncryptedYText(ydoc, fieldName, docKey);\n}\n","/**\n * E2EOfflineStore\n *\n * Extends OfflineStore with transparent AES-GCM encryption of the document\n * snapshot, ensuring that even if the device is compromised, the local\n * IndexedDB data cannot be read without the doc key.\n *\n * Only the snapshot is encrypted (not the meta store entries, which contain\n * non-sensitive data like sequence numbers).\n *\n * Key availability limitation: if the user's WebAuthn key is not in\n * DocKeyManager's in-memory cache and there is no network, E2E docs show\n * empty — this is expected Phase 2 behavior.\n */\n\nimport { OfflineStore } from \"./OfflineStore.ts\";\nimport { encryptField, decryptField } from \"./EncryptedY.ts\";\n\nexport class E2EOfflineStore extends OfflineStore {\n\tprivate readonly docKey: CryptoKey;\n\n\t/**\n\t * @param docId The document UUID.\n\t * @param serverOrigin Hostname of the server (namespaces the IDB key).\n\t * @param docKey AES-GCM CryptoKey used to encrypt/decrypt the snapshot.\n\t */\n\tconstructor(docId: string, serverOrigin: string | undefined, docKey: CryptoKey) {\n\t\tsuper(docId, serverOrigin);\n\t\tthis.docKey = docKey;\n\t}\n\n\t/**\n\t * Encrypt the snapshot before storing it.\n\t */\n\toverride async saveDocSnapshot(snapshot: Uint8Array): Promise<void> {\n\t\tconst encrypted = await encryptField(snapshot, this.docKey);\n\t\tawait super.saveDocSnapshot(encrypted);\n\t}\n\n\t/**\n\t * Decrypt the snapshot after loading it.\n\t * Returns null if decryption fails (e.g. key mismatch or corrupt data).\n\t */\n\toverride async getDocSnapshot(): Promise<Uint8Array | null> {\n\t\tconst encrypted = await super.getDocSnapshot();\n\t\tif (!encrypted) return null;\n\t\ttry {\n\t\t\treturn await decryptField(encrypted, this.docKey);\n\t\t} catch {\n\t\t\t// Key mismatch or tampered data — return null so the provider falls\n\t\t\t// back to fetching from the server.\n\t\t\treturn null;\n\t\t}\n\t}\n}\n","/**\n * E2EAbracadabraProvider\n *\n * Extends AbracadabraProvider with full E2E encryption support.\n *\n * Differences from standard provider:\n * - startSync() sends a stateless e2e_sync_request instead of SYNC_STEP1\n * - On receiving e2e_ready, fetches all blobs via REST, decrypts, applies to Y.Doc\n * - Local updates are AES-GCM encrypted before sending over WebSocket\n * - Incoming e2e_update stateless messages are decrypted and applied\n *\n * Phase 2 offline support:\n * - After the doc key is obtained, an E2EOfflineStore is created for this doc.\n * - The stored encrypted snapshot is applied before fetching server updates.\n * - The last-seen sequence number (e2e_seq) is persisted so only delta updates\n * are fetched on subsequent connects.\n * - After sync, a fresh encrypted snapshot is saved.\n *\n * Key availability limitation: if the user's WebAuthn key is not in\n * DocKeyManager's in-memory cache and there is no network, E2E docs show\n * empty — the key fetch requires either a cached in-memory key or network.\n */\n\nimport * as Y from \"yjs\";\nimport { AbracadabraProvider } from \"./AbracadabraProvider.ts\";\nimport type { AbracadabraProviderConfiguration } from \"./AbracadabraProvider.ts\";\nimport type { DocKeyManager } from \"./DocKeyManager.ts\";\nimport type { CryptoIdentityKeystore } from \"./CryptoIdentityKeystore.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport { UpdateMessage } from \"./OutgoingMessages/UpdateMessage.ts\";\nimport { encryptField, decryptField } from \"./EncryptedY.ts\";\nimport { E2EOfflineStore } from \"./E2EOfflineStore.ts\";\n\nfunction fromBase64(b64: string): Uint8Array {\n\treturn Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n}\n\nexport interface E2EAbracadabraProviderConfiguration extends AbracadabraProviderConfiguration {\n\tdocKeyManager: DocKeyManager;\n\tkeystore: CryptoIdentityKeystore;\n\tclient: AbracadabraClient;\n}\n\nexport class E2EAbracadabraProvider extends AbracadabraProvider {\n\tprivate readonly docKeyManager: DocKeyManager;\n\tprivate readonly keystore: CryptoIdentityKeystore;\n\tprivate readonly e2eClient: AbracadabraClient;\n\tprivate docKey: CryptoKey | null = null;\n\tprivate lastSeq = -1;\n\n\t/** E2E-encrypted offline store; created after the doc key is available. */\n\tprivate e2eStore: E2EOfflineStore | null = null;\n\tprivate readonly e2eServerOrigin: string | undefined;\n\n\tconstructor(configuration: E2EAbracadabraProviderConfiguration) {\n\t\t// Disable the parent's offline store — E2E uses its own encrypted store.\n\t\tsuper({ ...configuration, disableOfflineStore: true });\n\t\tthis.docKeyManager = configuration.docKeyManager;\n\t\tthis.keystore = configuration.keystore;\n\t\tthis.e2eClient = configuration.client;\n\n\t\t// Derive server origin for E2EOfflineStore namespacing\n\t\tthis.e2eServerOrigin = E2EAbracadabraProvider.deriveServerOrigin(\n\t\t\tconfiguration,\n\t\t\tconfiguration.client,\n\t\t);\n\t}\n\n\t/** Fetch the doc key from the server (requires WebAuthn if not cached). */\n\tprivate async ensureDocKey(): Promise<CryptoKey | null> {\n\t\tif (this.docKey) return this.docKey;\n\t\tthis.docKey = await this.docKeyManager.getDocKey(\n\t\t\tthis.configuration.name,\n\t\t\tthis.e2eClient,\n\t\t\tthis.keystore,\n\t\t);\n\n\t\t// Create the encrypted offline store now that we have the key\n\t\tif (this.docKey && !this.e2eStore) {\n\t\t\tthis.e2eStore = new E2EOfflineStore(\n\t\t\t\tthis.configuration.name,\n\t\t\t\tthis.e2eServerOrigin,\n\t\t\t\tthis.docKey,\n\t\t\t);\n\t\t}\n\n\t\treturn this.docKey;\n\t}\n\n\t/** Handle stateless messages including e2e_ready and e2e_update. */\n\toverride receiveStateless(payload: string): void {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(payload);\n\t\t} catch {\n\t\t\tsuper.receiveStateless(payload);\n\t\t\treturn;\n\t\t}\n\n\t\tconst msg = parsed as { type?: string; seq?: number; data?: string; doc_id?: string };\n\n\t\tif (msg.type === \"e2e_ready\") {\n\t\t\t// Fetch all blobs and hydrate doc\n\t\t\tthis._fetchAndApplyAllBlobs().catch((e) => {\n\t\t\t\tconsole.error(\"[E2EAbracadabraProvider] failed to fetch e2e blobs:\", e);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (msg.type === \"e2e_update\" && msg.data !== undefined && msg.seq !== undefined) {\n\t\t\tif (msg.seq <= this.lastSeq) return; // Already applied\n\t\t\tthis._decryptAndApply(fromBase64(msg.data), msg.seq).catch((e) => {\n\t\t\t\tconsole.error(\"[E2EAbracadabraProvider] failed to apply e2e_update:\", e);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tsuper.receiveStateless(payload);\n\t}\n\n\tprivate async _fetchAndApplyAllBlobs(): Promise<void> {\n\t\tconst key = await this.ensureDocKey();\n\t\tif (!key) {\n\t\t\tconsole.warn(\"[E2EAbracadabraProvider] no doc key available, cannot decrypt blobs\");\n\t\t\tthis.synced = true;\n\t\t\treturn;\n\t\t}\n\n\t\t// Phase 2: load stored snapshot + lastSeq before fetching from server\n\t\tif (this.e2eStore) {\n\t\t\tconst storedSeqStr = await this.e2eStore.getMeta(\"e2e_seq\").catch(() => null);\n\t\t\tif (storedSeqStr !== null) {\n\t\t\t\tthis.lastSeq = parseInt(storedSeqStr, 10);\n\t\t\t}\n\n\t\t\tconst snapshot = await this.e2eStore.getDocSnapshot().catch(() => null);\n\t\t\tif (snapshot) {\n\t\t\t\tY.applyUpdate(this.document, snapshot, this.e2eStore);\n\t\t\t}\n\t\t}\n\n\t\t// Only fetch updates newer than lastSeq\n\t\tconst updates = await this.e2eClient.getE2EUpdatesSince(\n\t\t\tthis.configuration.name,\n\t\t\tthis.lastSeq,\n\t\t);\n\t\tfor (const { seq, data } of updates) {\n\t\t\tawait this._decryptAndApply(data, seq);\n\t\t}\n\n\t\tthis.synced = true;\n\n\t\t// Phase 2: persist updated snapshot and lastSeq\n\t\tif (this.e2eStore) {\n\t\t\tconst snapshot = Y.encodeStateAsUpdate(this.document);\n\t\t\tawait this.e2eStore.saveDocSnapshot(snapshot).catch(() => null);\n\t\t\tawait this.e2eStore.setMeta(\"e2e_seq\", String(this.lastSeq)).catch(() => null);\n\t\t}\n\t}\n\n\tprivate async _decryptAndApply(encryptedData: Uint8Array, seq: number): Promise<void> {\n\t\tconst key = await this.ensureDocKey();\n\t\tif (!key) return;\n\t\ttry {\n\t\t\tconst plaintext = await decryptField(encryptedData, key);\n\t\t\tY.applyUpdate(this.document, plaintext, this);\n\t\t\tthis.lastSeq = Math.max(this.lastSeq, seq);\n\t\t} catch (e) {\n\t\t\tconsole.error(\"[E2EAbracadabraProvider] decryption failed for seq\", seq, e);\n\t\t}\n\t}\n\n\t/** Encrypt local updates before sending over WebSocket. */\n\toverride documentUpdateHandler(update: Uint8Array, origin: unknown): void {\n\t\tif (origin === this) return;\n\t\t// Don't call super (which would send plaintext); encrypt first\n\t\tthis._encryptAndSend(update).catch((e) => {\n\t\t\tconsole.error(\"[E2EAbracadabraProvider] failed to encrypt update:\", e);\n\t\t});\n\t}\n\n\tprivate async _encryptAndSend(update: Uint8Array): Promise<void> {\n\t\tconst key = await this.ensureDocKey();\n\t\tif (!key) {\n\t\t\tconsole.warn(\"[E2EAbracadabraProvider] no doc key, dropping update\");\n\t\t\treturn;\n\t\t}\n\t\tconst encrypted = await encryptField(update, key);\n\t\tthis.send(UpdateMessage, {\n\t\t\tupdate: encrypted,\n\t\t\tdocumentName: this.configuration.name,\n\t\t});\n\t}\n\n\toverride destroy(): void {\n\t\tthis.e2eStore?.destroy();\n\t\tthis.e2eStore = null;\n\t\tsuper.destroy();\n\t}\n}\n","/**\n * TreeTimestamps\n *\n * Attaches an afterUpdate observer on a child Y.Doc so that whenever a\n * non-offline update is applied, the `updatedAt` timestamp on the\n * corresponding entry in the root doc's `doc-tree` map is written.\n *\n * This propagates \"last edited\" timestamps to all peers via the root CRDT,\n * without requiring any server-side changes.\n *\n * Limitation: at least one client must have the child doc open after an edit\n * for the timestamp to propagate (eventually consistent).\n */\n\nimport * as Y from \"yjs\";\nimport type { OfflineStore } from \"./OfflineStore.ts\";\n\n/**\n * Attach an observer that writes `updatedAt: Date.now()` to the root\n * doc-tree entry for `childDocId` whenever the child doc receives a\n * non-offline update.\n *\n * @param treeMap The root doc's \"doc-tree\" Y.Map.\n * @param childDocId The child document's UUID (key in treeMap).\n * @param childDoc The child Y.Doc to observe.\n * @param offlineStore The child provider's OfflineStore (used to detect\n * offline-replay origins and skip them). Pass null when\n * the offline store is disabled.\n * @returns Cleanup function — call on provider destroy.\n */\nexport function attachUpdatedAtObserver(\n\ttreeMap: Y.Map<any>,\n\tchildDocId: string,\n\tchildDoc: Y.Doc,\n\tofflineStore: OfflineStore | null,\n): () => void {\n\tfunction handler(update: Uint8Array, origin: unknown): void {\n\t\t// Skip updates replayed from the local offline store — they represent\n\t\t// content that was already \"seen\" and shouldn't advance updatedAt.\n\t\tif (offlineStore !== null && origin === offlineStore) return;\n\n\t\t// Update the root tree entry (no-op if the entry doesn't exist).\n\t\tconst entry = treeMap.get(childDocId);\n\t\tif (!entry) return;\n\n\t\ttreeMap.set(childDocId, { ...entry, updatedAt: Date.now() });\n\t}\n\n\tchildDoc.on(\"update\", handler);\n\treturn () => childDoc.off(\"update\", handler);\n}\n","/**\n * BackgroundSyncPersistence\n *\n * Minimal IndexedDB store (`abracadabra:bgsync:{serverOrigin}`) that persists\n * per-document sync state across page reloads. A single object store,\n * `sync_state`, is keyed by `docId`.\n *\n * Falls back to a no-op when IndexedDB is unavailable (SSR / Node.js).\n */\n\nexport interface DocSyncState {\n\tdocId: string;\n\t/** Current lifecycle status of this document's background sync. */\n\tstatus: \"pending\" | \"syncing\" | \"synced\" | \"error\" | \"skipped\";\n\t/** Unix ms of the last successful sync, or null if never synced. */\n\tlastSynced: number | null;\n\t/** Human-readable error message if status === \"error\". */\n\terror?: string;\n\t/** Whether the document uses E2E encryption. */\n\tisE2E: boolean;\n}\n\nconst DB_VERSION = 1;\n\nfunction idbAvailable(): boolean {\n\treturn typeof globalThis !== \"undefined\" && \"indexedDB\" in globalThis;\n}\n\nfunction openDb(serverOrigin: string): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = globalThis.indexedDB.open(\n\t\t\t`abracadabra:bgsync:${serverOrigin}`,\n\t\t\tDB_VERSION,\n\t\t);\n\t\treq.onupgradeneeded = (event) => {\n\t\t\tconst db = (event.target as IDBOpenDBRequest).result;\n\t\t\tif (!db.objectStoreNames.contains(\"sync_state\")) {\n\t\t\t\tdb.createObjectStore(\"sync_state\", { keyPath: \"docId\" });\n\t\t\t}\n\t\t};\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nfunction idbPromise<T>(request: IDBRequest<T>): Promise<T> {\n\treturn new Promise((resolve, reject) => {\n\t\trequest.onsuccess = () => resolve(request.result);\n\t\trequest.onerror = () => reject(request.error);\n\t});\n}\n\nexport class BackgroundSyncPersistence {\n\tprivate dbPromise: Promise<IDBDatabase | null> | null = null;\n\tprivate readonly serverOrigin: string;\n\n\tconstructor(serverOrigin: string) {\n\t\tthis.serverOrigin = serverOrigin;\n\t}\n\n\tprivate getDb(): Promise<IDBDatabase | null> {\n\t\tif (!idbAvailable()) return Promise.resolve(null);\n\t\tif (!this.dbPromise) {\n\t\t\tthis.dbPromise = openDb(this.serverOrigin).catch(() => null);\n\t\t}\n\t\treturn this.dbPromise;\n\t}\n\n\tasync getState(docId: string): Promise<DocSyncState | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(\"sync_state\", \"readonly\");\n\t\tconst result = await idbPromise<DocSyncState | undefined>(\n\t\t\ttx.objectStore(\"sync_state\").get(docId),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\tasync getAllStates(): Promise<DocSyncState[]> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"sync_state\", \"readonly\");\n\t\t\tconst req = tx.objectStore(\"sync_state\").getAll();\n\t\t\treq.onsuccess = () => resolve(req.result as DocSyncState[]);\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\tasync setState(state: DocSyncState): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"sync_state\", \"readwrite\");\n\t\tawait idbPromise(tx.objectStore(\"sync_state\").put(state));\n\t}\n\n\tasync deleteState(docId: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"sync_state\", \"readwrite\");\n\t\tawait idbPromise(tx.objectStore(\"sync_state\").delete(docId));\n\t}\n\n\tdestroy(): void {\n\t\t// No cleanup needed — shared IDB connection managed by browser\n\t}\n}\n","/**\n * BackgroundSyncManager\n *\n * Proactively syncs all documents in the root tree map to IndexedDB so they\n * are available offline even if the user has never opened them directly.\n *\n * Key behaviours:\n * - Priority queue: sorted by updatedAt desc → never-synced first → errored last\n * - Concurrency: semaphore (default 2 parallel WS connections)\n * - Provider selection: non-E2E via rootProvider.loadChild(); E2E via\n * E2EAbracadabraProvider directly when docKeyManager + keystore are present\n * - File pre-caching: after sync, walks the Y.Doc for file refs and warms\n * the FileBlobStore cache (opt-in via prefetchFiles, default true)\n * - Cover images: at start of syncAll(), pre-caches all cover upload IDs\n * from the root tree map immediately (fire-and-forget)\n * - Periodic sync: startPeriodicSync() returns a cleanup function\n *\n * Note: This is in-page only (no Service Worker). The existing\n * flushPendingUpdates() handles offline → reconnect for open docs.\n */\n\nimport * as Y from \"yjs\";\nimport type { AbracadabraProvider } from \"./AbracadabraProvider.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport type { FileBlobStore } from \"./FileBlobStore.ts\";\nimport {\n\tBackgroundSyncPersistence,\n\ttype DocSyncState,\n} from \"./BackgroundSyncPersistence.ts\";\nimport EventEmitter from \"./EventEmitter.ts\";\nimport { E2EAbracadabraProvider } from \"./E2EAbracadabraProvider.ts\";\n\nexport interface BackgroundSyncManagerOptions {\n\t/** Max parallel WS connections for background sync. Default: 2. */\n\tconcurrency?: number;\n\t/** Timeout (ms) waiting for a provider to sync. Default: 15 000. */\n\tsyncTimeout?: number;\n\t/** Pre-cache file blobs after syncing a doc. Default: true. */\n\tprefetchFiles?: boolean;\n}\n\n/**\n * Simple semaphore for capping concurrency.\n */\nclass Semaphore {\n\tprivate slots: number;\n\tprivate queue: Array<() => void> = [];\n\n\tconstructor(limit: number) {\n\t\tthis.slots = limit;\n\t}\n\n\tacquire(): Promise<void> {\n\t\tif (this.slots > 0) {\n\t\t\tthis.slots--;\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\treturn new Promise((resolve) => this.queue.push(resolve));\n\t}\n\n\trelease(): void {\n\t\tconst next = this.queue.shift();\n\t\tif (next) {\n\t\t\tnext();\n\t\t} else {\n\t\t\tthis.slots++;\n\t\t}\n\t}\n}\n\nexport class BackgroundSyncManager extends EventEmitter {\n\tprivate readonly rootProvider: AbracadabraProvider;\n\tprivate readonly client: AbracadabraClient;\n\tprivate readonly fileBlobStore: FileBlobStore | null;\n\tprivate readonly opts: Required<BackgroundSyncManagerOptions>;\n\n\tprivate readonly persistence: BackgroundSyncPersistence;\n\tprivate readonly semaphore: Semaphore;\n\tprivate readonly syncStates = new Map<string, DocSyncState>();\n\n\tprivate _destroyed = false;\n\n\tconstructor(\n\t\trootProvider: AbracadabraProvider,\n\t\tclient: AbracadabraClient,\n\t\tfileBlobStore?: FileBlobStore | null,\n\t\topts?: BackgroundSyncManagerOptions,\n\t) {\n\t\tsuper();\n\t\tthis.rootProvider = rootProvider;\n\t\tthis.client = client;\n\t\tthis.fileBlobStore = fileBlobStore ?? null;\n\t\tthis.opts = {\n\t\t\tconcurrency: opts?.concurrency ?? 2,\n\t\t\tsyncTimeout: opts?.syncTimeout ?? 15_000,\n\t\t\tprefetchFiles: opts?.prefetchFiles ?? true,\n\t\t};\n\n\t\t// Derive server origin from client URL for IDB namespacing\n\t\tlet serverOrigin = \"default\";\n\t\ttry {\n\t\t\tserverOrigin = new URL((client as any).baseUrl ?? \"\").hostname;\n\t\t} catch {}\n\n\t\tthis.persistence = new BackgroundSyncPersistence(serverOrigin);\n\t\tthis.semaphore = new Semaphore(this.opts.concurrency);\n\t}\n\n\t// ── Public API ────────────────────────────────────────────────────────────\n\n\t/** Sync all documents in the root tree. */\n\tasync syncAll(): Promise<void> {\n\t\tif (this._destroyed) return;\n\n\t\tconst treeMap = this.rootProvider.document.getMap(\"doc-tree\") as Y.Map<any>;\n\t\tconst entries = Array.from(treeMap.entries()) as Array<[string, any]>;\n\n\t\tif (entries.length === 0) return;\n\n\t\t// Pre-cache cover images immediately (fire-and-forget)\n\t\tthis._prefetchCovers(entries).catch(() => null);\n\n\t\t// Build the priority queue\n\t\tconst queue = this._buildQueue(entries);\n\n\t\t// Sync all docs respecting concurrency limit\n\t\tawait Promise.all(queue.map((docId) => this._syncWithSemaphore(docId)));\n\t}\n\n\t/** Sync a single document by ID. */\n\tasync syncDoc(docId: string): Promise<DocSyncState> {\n\t\tconst state = await this._doSyncDoc(docId);\n\t\tthis.syncStates.set(docId, state);\n\t\tawait this.persistence.setState(state).catch(() => null);\n\t\tthis.emit(\"stateChanged\", { docId, state });\n\t\treturn state;\n\t}\n\n\t/** Return a snapshot of all known sync states. */\n\tgetSyncStatus(): Map<string, DocSyncState> {\n\t\treturn new Map(this.syncStates);\n\t}\n\n\t/**\n\t * Start periodic background sync.\n\t * @param intervalMs Interval between sync runs. Default: 5 minutes.\n\t * @returns Cleanup function to stop the periodic sync.\n\t */\n\tstartPeriodicSync(intervalMs = 5 * 60 * 1000): () => void {\n\t\tconst handle = setInterval(() => {\n\t\t\tif (!this._destroyed) {\n\t\t\t\tthis.syncAll().catch(() => null);\n\t\t\t}\n\t\t}, intervalMs);\n\t\treturn () => clearInterval(handle);\n\t}\n\n\tdestroy(): void {\n\t\tthis._destroyed = true;\n\t\tthis.removeAllListeners();\n\t}\n\n\t// ── Internal ──────────────────────────────────────────────────────────────\n\n\t/**\n\t * Build a priority-sorted list of doc IDs:\n\t * 1. Never-synced docs first (lastSynced === null, status !== \"error\")\n\t * 2. Synced docs sorted by updatedAt desc (most-recently-edited first)\n\t * 3. Errored docs last\n\t */\n\tprivate _buildQueue(entries: Array<[string, any]>): string[] {\n\t\ttype Sortable = { docId: string; priority: number };\n\n\t\tconst items: Sortable[] = entries.map(([docId, v]) => {\n\t\t\tconst state = this.syncStates.get(docId);\n\t\t\tconst updatedAt: number = v?.updatedAt ?? v?.createdAt ?? 0;\n\n\t\t\tlet priority: number;\n\t\t\tif (!state || state.status === \"pending\") {\n\t\t\t\t// Never synced — high priority (large number so it sorts first when DESC)\n\t\t\t\tpriority = Number.MAX_SAFE_INTEGER - updatedAt;\n\t\t\t} else if (state.status === \"error\") {\n\t\t\t\t// Errored — lowest priority (large negative offset)\n\t\t\t\tpriority = -1;\n\t\t\t} else {\n\t\t\t\t// Synced — sort by updatedAt desc (most recent = highest priority)\n\t\t\t\tpriority = updatedAt;\n\t\t\t}\n\t\t\treturn { docId, priority };\n\t\t});\n\n\t\t// Sort descending by priority\n\t\titems.sort((a, b) => b.priority - a.priority);\n\t\treturn items.map((i) => i.docId);\n\t}\n\n\tprivate async _syncWithSemaphore(docId: string): Promise<void> {\n\t\tif (this._destroyed) return;\n\t\tawait this.semaphore.acquire();\n\t\ttry {\n\t\t\tconst state = await this._doSyncDoc(docId);\n\t\t\tthis.syncStates.set(docId, state);\n\t\t\tawait this.persistence.setState(state).catch(() => null);\n\t\t\tthis.emit(\"stateChanged\", { docId, state });\n\t\t} finally {\n\t\t\tthis.semaphore.release();\n\t\t}\n\t}\n\n\tprivate async _doSyncDoc(docId: string): Promise<DocSyncState> {\n\t\t// Mark as syncing\n\t\tconst syncing: DocSyncState = {\n\t\t\tdocId,\n\t\t\tstatus: \"syncing\",\n\t\t\tlastSynced: this.syncStates.get(docId)?.lastSynced ?? null,\n\t\t\tisE2E: false,\n\t\t};\n\t\tthis.syncStates.set(docId, syncing);\n\t\tthis.emit(\"stateChanged\", { docId, state: syncing });\n\n\t\ttry {\n\t\t\t// Check encryption type\n\t\t\tlet isE2E = false;\n\t\t\ttry {\n\t\t\t\tconst enc = await this.client.getDocEncryption(docId);\n\t\t\t\tisE2E = enc.mode === \"e2e\";\n\t\t\t} catch {\n\t\t\t\t// If we can't check, treat as non-E2E\n\t\t\t}\n\n\t\t\tif (isE2E) {\n\t\t\t\treturn await this._syncE2EDoc(docId);\n\t\t\t} else {\n\t\t\t\treturn await this._syncNonE2EDoc(docId);\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tconst error = err instanceof Error ? err.message : String(err);\n\t\t\treturn {\n\t\t\t\tdocId,\n\t\t\t\tstatus: \"error\",\n\t\t\t\tlastSynced: this.syncStates.get(docId)?.lastSynced ?? null,\n\t\t\t\terror,\n\t\t\t\tisE2E: false,\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate async _syncNonE2EDoc(docId: string): Promise<DocSyncState> {\n\t\t// loadChild() returns cached provider if already open\n\t\tconst childProvider = await this.rootProvider.loadChild(docId);\n\n\t\t// Wait for ready (offline snapshot loaded) then synced (server sync done)\n\t\tawait childProvider.ready;\n\t\tawait this._waitForSynced(childProvider);\n\n\t\t// Prefetch file blobs\n\t\tif (this.opts.prefetchFiles && this.fileBlobStore) {\n\t\t\tthis._prefetchDocFiles(docId, childProvider.document).catch(() => null);\n\t\t}\n\n\t\treturn { docId, status: \"synced\", lastSynced: Date.now(), isE2E: false };\n\t}\n\n\tprivate async _syncE2EDoc(docId: string): Promise<DocSyncState> {\n\t\t// Attempt E2E sync only when docKeyManager and keystore are available\n\t\tconst docKeyManager = (this.rootProvider as any).abracadabraConfig\n\t\t\t?.docKeyManager;\n\t\tconst keystore = (this.rootProvider as any).abracadabraConfig?.keystore;\n\n\t\tif (!docKeyManager || !keystore) {\n\t\t\t// No key management configured — skip silently\n\t\t\treturn { docId, status: \"skipped\", lastSynced: null, isE2E: true };\n\t\t}\n\n\t\tconst childDoc = new Y.Doc({ guid: docId });\n\t\tconst childProvider = new E2EAbracadabraProvider({\n\t\t\tname: docId,\n\t\t\tdocument: childDoc,\n\t\t\tclient: this.client,\n\t\t\tdocKeyManager,\n\t\t\tkeystore,\n\t\t});\n\n\t\ttry {\n\t\t\tawait childProvider.ready;\n\t\t\tawait this._waitForSynced(childProvider);\n\n\t\t\tif (this.opts.prefetchFiles && this.fileBlobStore) {\n\t\t\t\tthis._prefetchDocFiles(docId, childDoc).catch(() => null);\n\t\t\t}\n\n\t\t\treturn { docId, status: \"synced\", lastSynced: Date.now(), isE2E: true };\n\t\t} finally {\n\t\t\tchildProvider.destroy();\n\t\t}\n\t}\n\n\t/**\n\t * Wait for a provider to emit the \"synced\" event (with state=true),\n\t * timing out after opts.syncTimeout ms.\n\t */\n\tprivate _waitForSynced(provider: any): Promise<void> {\n\t\t// If already synced, resolve immediately\n\t\tif (provider.synced === true) return Promise.resolve();\n\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tprovider.off(\"synced\", onSynced);\n\t\t\t\treject(new Error(`Sync timeout after ${this.opts.syncTimeout}ms`));\n\t\t\t}, this.opts.syncTimeout);\n\n\t\t\tfunction onSynced(state: boolean | { state: boolean }) {\n\t\t\t\t// Hocuspocus passes `{ state }` or a boolean directly\n\t\t\t\tconst synced =\n\t\t\t\t\ttypeof state === \"boolean\" ? state : (state as any)?.state ?? state;\n\t\t\t\tif (synced) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tprovider.off(\"synced\", onSynced);\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprovider.on(\"synced\", onSynced);\n\t\t});\n\t}\n\n\t/**\n\t * Pre-cache all cover images referenced in the root tree map.\n\t */\n\tprivate async _prefetchCovers(entries: Array<[string, any]>): Promise<void> {\n\t\tif (!this.fileBlobStore) return;\n\t\tfor (const [docId, v] of entries) {\n\t\t\tconst coverUploadId = v?.meta?.coverUploadId;\n\t\t\tif (coverUploadId) {\n\t\t\t\tthis.fileBlobStore.getBlobUrl(docId, coverUploadId).catch(() => null);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Pre-cache file blobs referenced in a synced Y.Doc.\n\t * Walks:\n\t * - ydoc.getXmlFragment('default') for `fileBlock` nodes (TipTap)\n\t * - ydoc.getMap('doc-tree') for meta.coverUploadId entries\n\t */\n\tprivate async _prefetchDocFiles(\n\t\tdocId: string,\n\t\tydoc: Y.Doc,\n\t): Promise<void> {\n\t\tif (!this.fileBlobStore) return;\n\n\t\tconst refs = this._extractFileRefs(ydoc);\n\t\tfor (const { refDocId, uploadId } of refs) {\n\t\t\tthis.fileBlobStore\n\t\t\t\t.getBlobUrl(refDocId ?? docId, uploadId)\n\t\t\t\t.catch(() => null);\n\t\t}\n\t}\n\n\tprivate _extractFileRefs(\n\t\tydoc: Y.Doc,\n\t): Array<{ refDocId: string | null; uploadId: string }> {\n\t\tconst refs: Array<{ refDocId: string | null; uploadId: string }> = [];\n\n\t\t// Walk XML fragment for fileBlock nodes\n\t\ttry {\n\t\t\tconst fragment = ydoc.getXmlFragment(\"default\");\n\t\t\tthis._walkXml(fragment, refs);\n\t\t} catch {}\n\n\t\t// Walk doc-tree meta for cover upload IDs\n\t\ttry {\n\t\t\tconst treeMap = ydoc.getMap(\"doc-tree\") as Y.Map<any>;\n\t\t\tfor (const [id, v] of treeMap.entries()) {\n\t\t\t\tconst coverUploadId = v?.meta?.coverUploadId;\n\t\t\t\tif (coverUploadId) {\n\t\t\t\t\trefs.push({ refDocId: id, uploadId: coverUploadId });\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {}\n\n\t\treturn refs;\n\t}\n\n\tprivate _walkXml(\n\t\tnode: Y.XmlFragment | Y.XmlElement,\n\t\trefs: Array<{ refDocId: string | null; uploadId: string }>,\n\t): void {\n\t\tfor (const child of node.toArray()) {\n\t\t\tif (child instanceof Y.XmlElement) {\n\t\t\t\tif (child.nodeName === \"fileBlock\") {\n\t\t\t\t\tconst uploadId = child.getAttribute(\"uploadId\");\n\t\t\t\t\tconst refDocId = child.getAttribute(\"docId\") ?? null;\n\t\t\t\t\tif (uploadId) refs.push({ refDocId, uploadId });\n\t\t\t\t}\n\t\t\t\tthis._walkXml(child, refs);\n\t\t\t}\n\t\t}\n\t}\n}\n"],"x_google_ignoreList":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,19,20,21,22,23,24,25,26,32,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,MAAa,0BACZ,WACI;AACJ,QAAO,MAAM,KAAK,OAAO,SAAS,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW;AACzD,SAAO;GACN,UAAU;GACV,GAAG;GACH;GACA;;;;;;;;;;ACFH,MAAaA,UAAQ,KAAK;;;;;;;AAwB1B,MAAaC,SAAO,GAAG,MAAM,IAAI,IAAI,IAAI;;;;;;;AAQzC,MAAaC,SAAO,GAAG,MAAM,IAAI,IAAI,IAAI;AAEzC,MAAaC,UAAQ,OAAO;;;;ACpB5B,MAAaC,SAAO;AAUpB,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAC1B,MAAaC,UAAQ,KAAK;AAc1B,MAAaC,UAAQ;AAUrB,MAAaC,WAAShB,UAAQ;AAC9B,MAAaiB,WAAShB,UAAQ;AAC9B,MAAaiB,WAAShB,UAAQ;AAC9B,MAAaiB,WAAShB,UAAQ;AAC9B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