@absolutejs/sync-expo 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../node_modules/@noble/ciphers/utils.js", "../node_modules/@noble/ciphers/_polyval.js", "../node_modules/@noble/ciphers/aes.js", "../src/index.ts", "../src/store.ts", "../src/bridge.ts"],
4
+ "sourcesContent": [
5
+ "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nexport function aarray(item, title, inner = () => { }) {\n if (!Array.isArray(item))\n throw new TypeError(`\"${title}\" expected array, got type=${typeof item}`);\n for (let i = 0; i < item.length; i++)\n inner(item[i], `${title}[${i}]`);\n return item;\n}\n/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - Value to inspect.\n * @returns `true` when the value is a Uint8Array view, including Node's `Buffer`.\n * @example\n * Guards a value before treating it as raw key material.\n *\n * ```ts\n * isBytes(new Uint8Array());\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy /\n // cross-realm cases. The fallback still requires a real ArrayBuffer view\n // so plain JSON-deserialized `{ constructor: ... }`\n // spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is boolean.\n * @param value - Value to validate.\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validates a boolean option before branching on it.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Asserts something is a non-negative safe integer.\n * @param n - Value to validate.\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validates a non-negative length or counter.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - Value to validate.\n * @param length - Expected byte length.\n * @param title - Optional label used in error messages.\n * @returns The validated byte array.\n * On Node, `Buffer` is accepted too because it is a Uint8Array view.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument lengths. {@link RangeError}\n * @example\n * Validates a fixed-length nonce or key buffer.\n *\n * ```ts\n * abytes(new Uint8Array([1, 2]), 2);\n * ```\n */\nexport function abytes(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError(label === 'object'\n ? 'expected valid options object'\n : `\"${label}\" expected object, got type=${typeof value}`);\n};\n/**\n * Asserts a hash- or MAC-like instance has not been destroyed or finished.\n * @param instance - Stateful instance to validate.\n * @param checkFinished - Whether to reject finished instances.\n * When `false`, only `destroyed` is checked.\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Guards against calling `update()` or `digest()` on a finished hash.\n *\n * ```ts\n * aexists({ destroyed: false, finished: false });\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - Output buffer to validate.\n * @param instance - Hash-like instance providing `outputLen`.\n * This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`,\n * unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong output buffer lengths. {@link RangeError}\n * @example\n * Verifies that a caller-provided output buffer is large enough.\n *\n * ```ts\n * aoutput(new Uint8Array(16), { outputLen: 16 });\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\n}\n/**\n * Asserts output is a sufficiently-sized, 4-byte-aligned byte array.\n * {@link aoutput} plus an {@link isAligned32} check, for `digestInto()` paths\n * that write through zero-allocation `u32` word views.\n * @param out - Output buffer to validate.\n * @param instance - Hash-like instance providing `outputLen`.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong output buffer lengths. {@link RangeError}\n * @throws On wrong output buffer alignment. {@link Error}\n * @example\n * Verifies that a caller-provided output buffer is large enough and aligned.\n *\n * ```ts\n * aoutput32(new Uint8Array(16), { outputLen: 16 });\n * ```\n */\nexport function aoutput32(out, instance) {\n aoutput(out, instance);\n if (!isAligned32(out))\n throw new Error('invalid output, must be aligned');\n}\n/**\n * Casts a typed-array view to Uint8Array.\n * @param arr - Typed-array view to reinterpret.\n * @returns Uint8Array view over the same bytes.\n * @example\n * Views 32-bit words as raw bytes without copying.\n *\n * ```ts\n * u8(new Uint32Array([1]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed-array view to Uint32Array.\n * @param arr - Typed-array view to reinterpret.\n * @returns Uint32Array view over the same bytes. Callers are expected to provide a\n * 4-byte-aligned offset; trailing `1..3` bytes are silently dropped.\n * @example\n * Views a byte buffer as 32-bit words for block processing.\n *\n * ```ts\n * u32(new Uint8Array(4));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place.\n * Warning: JS provides no guarantees.\n * @param arrays - Arrays to wipe.\n * @example\n * Wipes a temporary key buffer after use.\n *\n * ```ts\n * const bytes = new Uint8Array([1]);\n * clean(bytes);\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - Typed-array view to wrap.\n * @returns DataView over the same bytes.\n * @example\n * Creates an endian-aware view for length encoding.\n *\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Whether the current platform is little-endian.\n * Most are; some IBM systems are not.\n */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Reverses byte order of one 32-bit word.\n * @param word - Unsigned 32-bit word to swap.\n * @returns The same word with bytes reversed.\n * @example\n * Swaps a big-endian word into little-endian byte order.\n *\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Normalizes one 32-bit word to the little-endian representation expected by cipher cores.\n * @param n - Unsigned 32-bit word to normalize.\n * @returns Little-endian normalized word on big-endian hosts, else the input word unchanged.\n * @example\n * Normalizes a host-endian word before passing it into an ARX/AES core.\n *\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - Uint32Array whose words should be swapped.\n * @returns The same array after in-place byte swapping.\n * @example\n * Swaps every 32-bit word in a word-view buffer.\n *\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Normalizes a Uint32Array view to the little-endian representation expected by cipher cores.\n * @param u - Word view to normalize in place.\n * @returns Little-endian normalized word view.\n * @example\n * Normalizes a word-view buffer before block processing.\n *\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion:\n// {@link https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex | caniuse entry}\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 * @param bytes - Bytes to encode.\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Formats ciphertext bytes for logs or test vectors.\n *\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\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// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('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)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n}\nconst _0n = /* @__PURE__ */ BigInt(0);\n// Used in ff1, via bytesToNumberBE\n/**\n * Converts a big-endian hex string into bigint.\n * @param hex - Hexadecimal string without `0x`.\n * @returns Parsed bigint value. The empty string is treated as `0n`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parses a big-endian field element or counter from hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n // Numeric parser, not byte-hex decoder: odd-length forms like 'f' are valid,\n // and malformed syntax follows BigInt's native error behavior.\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// Used in ff1\n// BE: Big Endian, LE: Little Endian\n/**\n * Converts big-endian bytes into bigint.\n * @param bytes - Big-endian bytes.\n * @returns Parsed bigint value. Empty input is treated as `0n`.\n * @throws On invalid byte input passed to the internal hex conversion. {@link TypeError}\n * @example\n * Reads a big-endian integer from serialized bytes.\n *\n * ```ts\n * bytesToNumberBE(new Uint8Array([1, 0]));\n * ```\n */\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\n/**\n * Validates that a value is a non-negative bigint or safe integer.\n * @param n - Value to validate.\n * @returns The same validated value.\n * @throws On wrong argument ranges or values. {@link RangeError}\n */\nfunction abignumber(n) {\n if (typeof n === 'bigint') {\n if (!(_0n <= n))\n throw new RangeError('positive bigint expected, got ' + n);\n }\n else\n anumber(n);\n return n;\n}\n// Used in ff1\n/**\n * Converts a number into big-endian bytes of fixed length.\n * @param n - Number to encode.\n * @param len - Output length in bytes. Must be greater than zero.\n * @returns Big-endian bytes padded to `len`.\n * Negative values, `len = 0`, and values that do not fit are rejected before\n * downstream hex parsing.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Encodes a counter as fixed-width big-endian bytes.\n *\n * ```ts\n * numberToBytesBE(1, 2);\n * ```\n */\nexport function numberToBytesBE(n, len) {\n anumber(len);\n if (len === 0)\n throw new Error('zero output length is invalid');\n n = abignumber(n);\n const expectedLen = len * 2;\n const hex = n.toString(16);\n // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n if (hex.length > expectedLen)\n throw new RangeError('number is too large');\n return hexToBytes(hex.padStart(expectedLen, '0'));\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @param str - String to encode.\n * @returns UTF-8 bytes in a detached fresh Uint8Array copy.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encodes application text before encryption or MACing.\n *\n * ```ts\n * utf8ToBytes('abc'); // new Uint8Array([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // {@link https://bugzil.la/1681809 | Firefox bug 1681809}\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @param bytes - UTF-8 bytes.\n * @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed\n * UTF-8 is replacement-decoded instead of rejected.\n * @example\n * Decodes UTF-8 plaintext back into a string.\n *\n * ```ts\n * bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc'\n * ```\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Checks if two U8A use same underlying buffer and overlaps.\n * This is invalid and can corrupt data.\n * @param a - First byte view.\n * @param b - Second byte view.\n * @returns `true` when the views overlap in memory.\n * @example\n * Detects whether two slices alias the same backing buffer.\n *\n * ```ts\n * overlapBytes(new Uint8Array(4), new Uint8Array(4));\n * ```\n */\nexport function overlapBytes(a, b) {\n // Zero-length views cannot overwrite anything, even if their offset sits inside another range.\n if (!a.byteLength || !b.byteLength)\n return false;\n return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy\n a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end\n b.byteOffset < a.byteOffset + a.byteLength // b starts before a end\n );\n}\n/**\n * If input and output overlap and input starts before output, we will overwrite end of input before\n * we start processing it, so this is not supported by forward-processing ciphers.\n * @param input - Input bytes.\n * @param output - Output bytes.\n * @throws If the output view would overwrite unread input bytes. {@link Error}\n * @example\n * Rejects an in-place layout that would overwrite unread input bytes.\n *\n * ```ts\n * const buffer = new Uint8Array(8);\n * complexOverlapBytes(buffer.subarray(0, 4), buffer.subarray(2, 6));\n * ```\n */\nexport function complexOverlapBytes(input, output) {\n // This is very cursed. It works somehow, but I'm completely unsure,\n // reasoning about overlapping aligned windows is very hard.\n if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)\n throw new Error('complex overlap of input and output is not supported');\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - Byte arrays to concatenate.\n * @returns Combined byte array.\n * @throws On wrong argument types inside the byte-array list. {@link TypeError}\n * @example\n * Builds a `nonce || ciphertext` style buffer.\n *\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\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/**\n * Merges user options into defaults.\n * @param defaults - Default option values.\n * @param opts - User-provided overrides.\n * @returns Combined options object.\n * `defaults` is a library-owned mutable object; user-provided `opts` only need to be\n * object-shaped, since \"plain object\" checks reject valid proxy/cross-realm containers.\n * The merge mutates `defaults` in place and returns the same object, so direct callers\n * should pass a fresh defaults object unless they intentionally want shared state updated.\n * @throws If options are missing or not an object. {@link Error}\n * @example\n * Applies user overrides to the default cipher options.\n *\n * ```ts\n * checkOpts({ rounds: 20 }, { rounds: 8 });\n * ```\n */\nexport function checkOpts(defaults, opts) {\n aobject(defaults, 'defaults');\n aobject(opts, 'opts');\n // Mutates defaults by design. __proto__ follows Object.assign semantics here and can only\n // affect this local option object; callers already control this low-level options surface.\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/**\n * Compares two byte arrays in kinda constant time once lengths already match.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns `true` when the arrays contain the same bytes. Different lengths still return early.\n * @example\n * Compares an expected authentication tag with the received one.\n *\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a, b) {\n a = abytes(a);\n b = abytes(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 * Wraps a keyed MAC constructor into a one-shot helper with `.create()`.\n * @param keyLen - Valid probe-key length used to read static metadata once.\n * The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes\n * can pass any representative size as long as those values stay fixed.\n * @param macCons - Keyed MAC constructor or factory.\n * @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message.\n * @returns Callable MAC helper with `.create()`.\n */\nexport function wrapMacConstructor(keyLen, macCons, fromMsg) {\n const mac = macCons;\n const getArgs = (fromMsg || (() => []));\n const macC = (msg, key) => mac(key, ...getArgs(msg))\n .update(msg)\n .digest();\n const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));\n macC.outputLen = tmp.outputLen;\n macC.blockLen = tmp.blockLen;\n macC.create = (key, ...args) => mac(key, ...args);\n return macC;\n}\n/**\n * Wraps a cipher: validates args, ensures encrypt() can only be called once.\n * Used internally by the exported cipher constructors.\n * Output-buffer support is inferred from the wrapped `encrypt` / `decrypt`\n * arity (`fn.length === 2`), so wrapped output-capable methods must use a normal\n * second parameter, not a default/rest parameter. AAD support is explicit in\n * `params.withAAD`; optional AAD starts after the nonce slot when one is present.\n * @__NO_SIDE_EFFECTS__\n * @param params - Static cipher metadata. See {@link CipherParams}.\n * @param constructor - Cipher constructor.\n * @returns Wrapped constructor with validation.\n */\nexport const wrapCipher = (params, constructor) => {\n function wrappedCipher(key, ...args) {\n // Validate key\n abytes(key, undefined, 'key');\n // Validate nonce if nonceLength is present\n if (params.nonceLength !== undefined) {\n const nonce = args[0];\n abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce');\n }\n // Keep tag length available for decrypt-size checks after constructor validation.\n const tagl = params.tagLength;\n const aadStart = params.nonceLength !== undefined ? 1 : 0;\n // No-AAD constructors otherwise silently ignore byte args meant as AAD.\n if (!params.withAAD) {\n for (let i = aadStart; i < args.length; i++)\n if (isBytes(args[i]))\n throw new Error('AAD not supported');\n }\n // Validate the first AAD slot early; rest-arg AAD constructors validate the tail themselves.\n if (params.withAAD && args[aadStart] !== undefined)\n abytes(args[aadStart], undefined, 'AAD');\n const cipher = constructor(key, ...args);\n const checkOutput = (fnLength, output) => {\n if (output !== undefined) {\n if (fnLength !== 2)\n throw new Error('cipher output not supported');\n abytes(output, undefined, 'output');\n }\n };\n // Create wrapped cipher with validation and single-use encryption\n let called = false;\n const wrCipher = {\n encrypt(data, output) {\n if (called)\n throw new Error('cannot encrypt() twice with same key + nonce');\n // Any encrypt attempt consumes the instance, even if validation rejects below.\n called = true;\n abytes(data, undefined, 'data');\n checkOutput(cipher.encrypt.length, output);\n return cipher.encrypt(data, output);\n },\n decrypt(data, output) {\n abytes(data, undefined, 'data');\n if (tagl && data.length < tagl)\n throw new Error('\"ciphertext\" expected length >= tagLength=' + tagl);\n checkOutput(cipher.decrypt.length, output);\n return cipher.decrypt(data, output);\n },\n };\n return wrCipher;\n }\n Object.assign(wrappedCipher, params);\n return wrappedCipher;\n};\n/**\n * By default, returns u8a of length.\n * When out is available, it checks it for validity and uses it.\n * @param expectedLength - Required output length.\n * @param out - Optional destination buffer.\n * @param onlyAligned - Whether `out` must be 4-byte aligned.\n * @returns Output buffer ready for writing.\n * @throws On wrong argument types. {@link TypeError}\n * @throws If the provided output buffer has the wrong size. {@link RangeError}\n * @throws If the provided output buffer has the wrong alignment. {@link Error}\n * @example\n * Reuses a caller-provided output buffer when lengths match.\n *\n * ```ts\n * getOutput(16, new Uint8Array(16));\n * ```\n */\nexport function getOutput(expectedLength, out, onlyAligned = true) {\n if (out === undefined)\n return new Uint8Array(expectedLength);\n // Keep Buffer/cross-realm Uint8Array support here instead of trusting a shape-compatible object.\n abytes(out, expectedLength, 'output');\n if (onlyAligned && !isAligned32(out))\n throw new Error('invalid output, must be aligned');\n return out;\n}\n/**\n * Encodes data and AAD lengths into a 16-byte buffer.\n * @param dataLength - Data length. Units are caller-defined: GCM passes bit\n * lengths, ChaCha20-Poly1305 passes byte lengths — the helper writes the raw values.\n * @param aadLength - AAD length, same unit convention as `dataLength`.\n * The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305\n * conventions even though the helper parameter order is `(dataLength, aadLength)`.\n * @param isLE - Whether to encode lengths as little-endian.\n * @returns 16-byte length block.\n * @throws On wrong argument types passed to the endian validator. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Builds the length block appended by GCM and Poly1305.\n *\n * ```ts\n * u64Lengths(16, 8, true);\n * ```\n */\nexport function u64Lengths(dataLength, aadLength, isLE) {\n // Reject coercible non-number lengths like '10' and true before BigInt(...) accepts them.\n anumber(dataLength);\n anumber(aadLength);\n abool(isLE);\n const num = new Uint8Array(16);\n const view = createView(num);\n view.setBigUint64(0, BigInt(aadLength), isLE);\n view.setBigUint64(8, BigInt(dataLength), isLE);\n return num;\n}\n/**\n * Checks whether a byte array is aligned to a 4-byte offset.\n * @param bytes - Byte array to inspect.\n * @returns `true` when the view is 4-byte aligned.\n * @example\n * Checks whether a buffer can be safely viewed as Uint32Array.\n *\n * ```ts\n * isAligned32(new Uint8Array(4));\n * ```\n */\nexport function isAligned32(bytes) {\n return bytes.byteOffset % 4 === 0;\n}\n/**\n * Copies bytes into a new Uint8Array.\n * @param bytes - Bytes to copy.\n * @returns Copied byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Copies input into an aligned Uint8Array before block processing.\n *\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\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 // Web Cryptography API Level 2 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Uses CSPRNG for nonce, nonce injected in ciphertext.\n * For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and\n * prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext\n * are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext`\n * buffer on encrypt and intentionally does not support caller-provided destination buffers.\n * Too-short decrypt inputs are split into short/empty nonce views and then delegated\n * to the wrapped cipher instead of being rejected here first.\n *\n * NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha\n * should be limited to `2**23` (8M) messages to get a collision chance of\n * `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to\n * `2**-33`, still negligible but creeping up.\n * @param fn - Cipher constructor that expects a nonce.\n * @param randomBytes_ - Random-byte source used for nonce generation.\n * @returns Cipher constructor that prepends the nonce to ciphertext.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError}\n * @example\n * Prepends a fresh random nonce to every ciphertext.\n *\n * ```ts\n * import { gcm } from '@noble/ciphers/aes.js';\n * import { managedNonce, randomBytes } from '@noble/ciphers/utils.js';\n * const wrapped = managedNonce(gcm);\n * const key = randomBytes(16);\n * const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3]));\n * wrapped(key).decrypt(ciphertext);\n * ```\n */\nexport function managedNonce(fn, randomBytes_ = randomBytes) {\n if (typeof fn !== 'function')\n throw new TypeError('\"fn\" expected cipher constructor, got type=' + typeof fn);\n if (typeof randomBytes_ !== 'function')\n throw new TypeError('\"randomBytes_\" expected function, got type=' + typeof randomBytes_);\n const { nonceLength } = fn;\n anumber(nonceLength, 'fn.nonceLength');\n const addNonce = (nonce, ciphertext, plaintext) => {\n const out = concatBytes(nonce, ciphertext);\n // Wrapped ciphers may alias caller plaintext on encrypt(); never zero\n // caller-owned buffers here.\n if (!overlapBytes(plaintext, ciphertext))\n ciphertext.fill(0);\n return out;\n };\n // NOTE: we cannot support DST here, it would be mistake:\n // - we don't know how much dst length cipher requires\n // - nonce may unalign dst and break everything\n // - we create new u8a anyway (concatBytes)\n // - previously we passed all args to cipher, but that was mistake!\n const res = ((key, ...args) => ({\n encrypt(plaintext) {\n abytes(plaintext, undefined, 'data');\n const nonce = randomBytes_(nonceLength);\n const encrypted = fn(key, nonce, ...args).encrypt(plaintext);\n // @ts-ignore\n if (encrypted instanceof Promise)\n return encrypted.then((ct) => addNonce(nonce, ct, plaintext));\n return addNonce(nonce, encrypted, plaintext);\n },\n decrypt(ciphertext) {\n abytes(ciphertext, undefined, 'data');\n const nonce = ciphertext.subarray(0, nonceLength);\n const decrypted = ciphertext.subarray(nonceLength);\n return fn(key, nonce, ...args).decrypt(decrypted);\n },\n }));\n // Auto-nonce wrappers still preserve the wrapped payload geometry.\n if ('blockSize' in fn)\n res.blockSize = fn.blockSize;\n if ('tagLength' in fn)\n res.tagLength = fn.tagLength;\n if ('withAAD' in fn)\n res.withAAD = fn.withAAD;\n return res;\n}\n",
6
+ "/**\n * GHash from AES-GCM and its little-endian \"mirror image\" Polyval from AES-SIV.\n *\n * Implemented in terms of GHash with conversion function for keys\n * GCM GHASH from\n * {@link https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf | NIST SP800-38d},\n * SIV from\n * {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.\n *\n * GHASH modulo: x^128 + x^7 + x^2 + x + 1\n * POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1\n *\n * @module\n */\nimport { abytes, aexists, aoutput32, clean, copyBytes, createView, isLE, swap32IfBE, swap8IfBE, u32, wrapMacConstructor, } from \"./utils.js\";\nconst BLOCK_SIZE = 16;\n// TODO: rewrite\n// temporary padding buffer\n// ZEROS32 aliases these bytes, so clean(ZEROS32) also resets this shared tail-padding scratch.\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\nconst ZEROS32 = /* @__PURE__ */ u32(ZEROS16);\n// GHASH reduces modulo x^128 + x^7 + x^2 + x + 1, so the low-degree terms\n// x^7 + x^2 + x + 1 become bits `11100001` = 0xe1 in R = 0xe1 || 0^120.\nconst POLY = 0xe1;\n// v = 2*v % POLY\n// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x\n// Montgomery ladder can multiply any field element with this doubling step;\n// addition stays simple xor.\nconst mul2 = (s0, s1, s2, s3) => {\n const hiBit = s3 & 1;\n return {\n s3: (s2 << 31) | (s3 >>> 1),\n s2: (s1 << 31) | (s2 >>> 1),\n s1: (s0 << 31) | (s1 >>> 1),\n // NIST SP 800-38D §6.3 applies `V >> 1` and XORs R on carry. In this\n // 4x32-bit split, R = 0xe1 || 0^120 lives in the top byte of s0.\n s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly\n };\n};\n// Per-word part of RFC 8452 `ByteReverse`; callers also reverse the 32-bit word order.\nconst swapLE = (n) => (((n >>> 0) & 0xff) << 24) |\n (((n >>> 8) & 0xff) << 16) |\n (((n >>> 16) & 0xff) << 8) |\n ((n >>> 24) & 0xff) |\n 0;\n// POLYVAL first applies RFC 8452's per-word byte reversal, then re-normalizes\n// host-endian u32 loads to the little-endian word value `_updateBlock()` expects.\nconst swap8IfLE = (n) => swap8IfBE(swapLE(n));\n/**\n * `mulX_GHASH(ByteReverse(H))` from RFC 8452 Appendix A.\n * @param k mutated in place\n */\nexport function _toGHASHKey(k) {\n // The input is the original POLYVAL key H; reverse() materializes\n // RFC 8452's `ByteReverse(H)` before the GHASH mulX step.\n k.reverse();\n const hiBit = k[15] & 1;\n // k >>= 1\n let carry = 0;\n for (let i = 0; i < k.length; i++) {\n const t = k[i];\n k[i] = (t >>> 1) | carry;\n carry = (t & 1) << 7;\n }\n k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;\n return k;\n}\n// Precompute-window heuristic only: larger inputs trade memory for fewer table lookups.\n// Any caller-provided length hint still collapses to one of the supported windows {2, 4, 8}.\nconst estimateWindow = (bytes) => {\n if (bytes > 64 * 1024)\n return 8;\n if (bytes > 1024)\n return 4;\n return 2;\n};\n/**\n * Incremental GHASH state for AES-GCM.\n * @param key - 16-byte GHASH key.\n * @param expectedLength - Expected message length for table sizing.\n * Chunking is segment-based, not hash-streaming: every `update()` call is zero-padded\n * to the next 16-byte boundary before it is absorbed. This matches the internal AES/GCM\n * use where AAD, payload, and length block are separate padded segments.\n * @example\n * Feeds one ciphertext block into an incremental GHASH state with a fresh hash key.\n *\n * ```ts\n * import { GHASH } from '@noble/ciphers/_polyval.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const mac = new GHASH(key);\n * mac.update(new Uint8Array(16));\n * mac.digest();\n * ```\n */\nexport class GHASH {\n blockLen = BLOCK_SIZE;\n outputLen = BLOCK_SIZE;\n s0 = 0;\n s1 = 0;\n s2 = 0;\n s3 = 0;\n finished = false;\n destroyed = false;\n t;\n W;\n windowSize;\n // We select bits per window adaptively based on expectedLength\n constructor(key, expectedLength) {\n abytes(key, 16, 'key');\n key = copyBytes(key);\n const kView = createView(key);\n let k0 = kView.getUint32(0, false);\n let k1 = kView.getUint32(4, false);\n let k2 = kView.getUint32(8, false);\n let k3 = kView.getUint32(12, false);\n // generate table of doubled keys (half of montgomery ladder)\n const doubles = [];\n for (let i = 0; i < 128; i++) {\n doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });\n ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));\n }\n const W = estimateWindow(expectedLength || 1024);\n if (![1, 2, 4, 8].includes(W))\n throw new Error('ghash: invalid window size, expected 2, 4 or 8');\n this.W = W;\n const bits = 128; // always 128 bits;\n const windows = bits / W;\n const windowSize = (this.windowSize = 2 ** W);\n const items = [];\n // Create precompute table for window of W bits\n for (let w = 0; w < windows; w++) {\n // truth table: 00, 01, 10, 11\n for (let byte = 0; byte < windowSize; byte++) {\n // prettier-ignore\n let s0 = 0, s1 = 0, s2 = 0, s3 = 0;\n for (let j = 0; j < W; j++) {\n const bit = (byte >>> (W - j - 1)) & 1;\n if (!bit)\n continue;\n const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];\n ((s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3));\n }\n items.push({ s0, s1, s2, s3 });\n }\n }\n this.t = items;\n }\n _updateBlock(s0, s1, s2, s3) {\n ((s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3));\n const { W, t, windowSize } = this;\n // prettier-ignore\n let o0 = 0, o1 = 0, o2 = 0, o3 = 0;\n const mask = (1 << W) - 1; // 2**W will kill performance.\n let w = 0;\n // NIST SP 800-38D §6.3 interprets blocks as little-endian polynomials,\n // so the lookup walk consumes each word byte-by-byte from\n // least-significant to most-significant bits.\n for (const num of [s0, s1, s2, s3]) {\n for (let bytePos = 0; bytePos < 4; bytePos++) {\n const byte = (num >>> (8 * bytePos)) & 0xff;\n for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {\n const bit = (byte >>> (W * bitPos)) & mask;\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];\n ((o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3));\n w += 1;\n }\n }\n }\n this.s0 = o0;\n this.s1 = o1;\n this.s2 = o2;\n this.s3 = o3;\n }\n update(data) {\n aexists(this);\n abytes(data);\n data = copyBytes(data);\n const b32 = u32(data);\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n const left = data.length % BLOCK_SIZE;\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(swap8IfBE(b32[i * 4 + 0]), swap8IfBE(b32[i * 4 + 1]), swap8IfBE(b32[i * 4 + 2]), swap8IfBE(b32[i * 4 + 3]));\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n // Tail blocks go through the shared ZEROS32 scratch, so they need the same host-endian\n // normalization as full blocks; otherwise segmented GHASH/POLYVAL updates diverge on BE.\n this._updateBlock(swap8IfBE(ZEROS32[0]), swap8IfBE(ZEROS32[1]), swap8IfBE(ZEROS32[2]), swap8IfBE(ZEROS32[3]));\n clean(ZEROS32); // clean tmp buffer\n }\n return this;\n }\n destroy() {\n // `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.\n this.destroyed = true;\n const { t } = this;\n // Wipe the key-derived precompute table; scalar accumulator words remain,\n // but the destroyed guard blocks further use.\n // clean precompute table\n for (const elm of t) {\n ((elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0));\n }\n }\n digestInto(out) {\n aexists(this);\n // `digestInto(out)` is the no-allocation fast path, so callers must pass a\n // 32-bit-aligned buffer before we reinterpret it with `u32(out)`.\n aoutput32(out, this);\n this.finished = true;\n // NIST SP 800-38D §6.4 returns the final 128-bit block Y_m.\n // `digestInto()` follows the relaxed `aoutput()` contract, so only\n // out[0..15] may be touched.\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n // Only the tag words need host-endian normalization; oversized output tails are caller-owned.\n if (!isLE)\n swap32IfBE(o32.subarray(0, BLOCK_SIZE / 4));\n }\n digest() {\n const res = new Uint8Array(BLOCK_SIZE);\n this.digestInto(res);\n // `res` is independent of internal state, so it stays valid after destroy() wipes the table.\n this.destroy();\n return res;\n }\n}\n/**\n * Incremental POLYVAL state for AES-SIV.\n * @param key - 16-byte POLYVAL key.\n * @param expectedLength - Expected message length for table sizing.\n * Inherits GHASH's segment-padded `update()` behavior: each call is padded\n * independently to a 16-byte boundary before absorption.\n * @example\n * Feeds one block into an incremental POLYVAL state with a fresh hash key.\n *\n * ```ts\n * import { Polyval } from '@noble/ciphers/_polyval.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const mac = new Polyval(key);\n * mac.update(new Uint8Array(16));\n * mac.digest();\n * ```\n */\nexport class Polyval extends GHASH {\n constructor(key, expectedLength) {\n abytes(key);\n // RFC 8452 Appendix A converts the POLYVAL key with\n // `mulX_GHASH(ByteReverse(H))`; copy first because `_toGHASHKey(...)`\n // mutates in place.\n const ghKey = _toGHASHKey(copyBytes(key));\n super(ghKey, expectedLength);\n clean(ghKey);\n }\n update(data) {\n aexists(this);\n abytes(data);\n data = copyBytes(data);\n const b32 = u32(data);\n const left = data.length % BLOCK_SIZE;\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n for (let i = 0; i < blocks; i++) {\n // RFC 8452 Appendix A feeds `ByteReverse(X_i)` into GHASH, so POLYVAL\n // reverses the 32-bit word order in addition to the per-word byte swap.\n this._updateBlock(swap8IfLE(b32[i * 4 + 3]), swap8IfLE(b32[i * 4 + 2]), swap8IfLE(b32[i * 4 + 1]), swap8IfLE(b32[i * 4 + 0]));\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(swap8IfLE(ZEROS32[3]), swap8IfLE(ZEROS32[2]), swap8IfLE(ZEROS32[1]), swap8IfLE(ZEROS32[0]));\n clean(ZEROS32);\n }\n return this;\n }\n digestInto(out) {\n aexists(this);\n // `digestInto(out)` is the no-allocation fast path, so callers must pass a\n // 32-bit-aligned buffer before we reinterpret the output prefix with `u32(view)`.\n aoutput32(out, this);\n this.finished = true;\n // RFC 8452 Appendix A maps POLYVAL output back through `ByteReverse(...)`.\n // `digestInto()` follows the relaxed `aoutput()` contract, so only out[0..15] may be touched.\n const view = out.subarray(0, this.outputLen);\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(view);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n swap32IfBE(o32);\n view.reverse();\n }\n}\n/**\n * GHash MAC for AES-GCM.\n * @param msg - Message bytes to authenticate.\n * @param key - 16-byte GHASH key.\n * @returns 16-byte authentication tag.\n * @example\n * Authenticates a short message with GHASH and a fresh hash key.\n *\n * ```ts\n * import { ghash } from '@noble/ciphers/_polyval.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * ghash(new Uint8Array(), key);\n * ```\n */\nexport const ghash = \n/* @__PURE__ */ wrapMacConstructor(16, (key, expectedLength) => new GHASH(key, expectedLength), (msg) => [msg.length]);\n/**\n * POLYVAL MAC for AES-SIV.\n * @param msg - Message bytes to authenticate.\n * @param key - 16-byte POLYVAL key.\n * @returns 16-byte authentication tag.\n * @example\n * Authenticates a short message with POLYVAL and a fresh hash key.\n *\n * ```ts\n * import { polyval } from '@noble/ciphers/_polyval.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * polyval(new Uint8Array(), key);\n * ```\n */\nexport const polyval = \n/* @__PURE__ */ wrapMacConstructor(16, (key, expectedLength) => new Polyval(key, expectedLength), (msg) => [msg.length]);\n",
7
+ "/**\n * {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard | AES}\n * a.k.a. Advanced Encryption Standard\n * is a variant of Rijndael block cipher, standardized by NIST in 2001.\n * We provide the fastest available pure JS implementation.\n *\n * `cipher = encrypt(block, key)`\n *\n * Data is split into 128-bit blocks.\n * Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:\n * 1. **S-box**, table substitution\n * 2. **Shift rows**, cyclic shift left of all rows of data array\n * 3. **Mix columns**, multiplying every column by fixed polynomial\n * 4. **Add round key**, round_key xor i-th column of array\n *\n * Check out\n * {@link https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf | FIPS-197},\n * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G},\n * and {@link https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf | original proposal}.\n * @module\n */\nimport { ghash, polyval } from \"./_polyval.js\";\n// prettier-ignore\nimport { abytes, aexists, anumber, aoutput32, byteSwap, clean, complexOverlapBytes, concatBytes, copyBytes, createView, equalBytes, getOutput, isAligned32, isLE, overlapBytes, swap32IfBE, swap8IfBE, u32, u64Lengths, u8, wrapCipher, wrapMacConstructor } from \"./utils.js\";\nconst BLOCK_SIZE = 16;\n// AES operates on 16-byte blocks, i.e. 4 32-bit words.\nconst BLOCK_SIZE32 = 4;\n// Shared zero block (`0^128`) used by GCM's `H = CIPH_K(0^128)` / J0 scratch\n// and by CMAC / SIV helpers; callers take `.slice()` before mutating it.\nconst EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE);\n// RFC 5297 §2.1 / §2.4: S2V uses `<one> = 0^127 || 1` for the `n = 0` special case.\nconst ONE_BLOCK = /* @__PURE__ */ Uint8Array.from([\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,\n]);\nconst POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8\n// Validates plain AES key sizes only; AES-SIV's doubled-key contract is checked elsewhere.\nfunction validateKeyLength(key) {\n if (![16, 24, 32].includes(key.length))\n throw new Error('\"aes key\" expected Uint8Array of length 16/24/32, got length=' + key.length);\n}\n// TODO: remove multiplication, binary ops only\n// Doubles one GF(2^8) field element; callers are expected to stay in byte range.\n// FIPS 197 upd1 §4.3 equation (4.5): XTIMES(b) left-shifts by one and, when\n// b7=1, reduces by m(x); using POLY=0x11b here yields the same byte result\n// as XORing with {1b} after the shift.\nfunction mul2(n) {\n return (n << 1) ^ (POLY & -(n >> 7));\n}\n// Shift-and-add multiplication in GF(2^8); callers are expected to pass byte values.\n// FIPS 197 upd1 §4.3 equation (4.7): general products are XORs of repeated\n// XTIMES() multiples, e.g. {57}•{13} = {57}⊕{ae}⊕{07}.\nfunction mul(a, b) {\n let res = 0;\n for (; b > 0; b >>= 1) {\n // Usual shift-and-add step in GF(2^8), not a scalar-multiplication ladder.\n res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).\n a = mul2(a); // a = 2*a\n }\n return res;\n}\n/**\n * Increments a counter block with wrap around.\n * AES call sites here currently use the big-endian branch, but the helper supports both layouts.\n * NIST SP 800-38A Appendix B.1 and SP 800-38D §6.2 increment the\n * least-significant/rightmost bits.\n * `isLE=false` matches that standard counter-block layout, while `isLE=true`\n * is a generic extension for non-AES callers.\n * The implementation keeps a 32-bit bitwise carry path, so `carry` is capped at `0xffffff00`;\n * larger values throw instead of silently overflowing before the next-byte propagation step.\n */\n// Keep the helper explicitly typed so `--isolatedDeclarations` can expose it\n// through the test-only `__TESTS` export without inference errors.\nconst incBytes = (data, isLE, carry = 1) => {\n // Carry is an increment count, not a signed delta; negatives would wrap through `| 0`.\n // Keep `carry + byte <= 0xffffffff` so the `| 0` / `>>> 8` path below\n // never truncates a real carry bit.\n if (!Number.isSafeInteger(carry) || carry < 0 || carry > 0xffffff00)\n throw new Error('incBytes: wrong carry ' + carry);\n abytes(data);\n for (let i = 0; i < data.length; i++) {\n const pos = !isLE ? data.length - 1 - i : i;\n carry = (carry + (data[pos] & 0xff)) | 0;\n data[pos] = carry & 0xff;\n carry >>>= 8;\n }\n};\n// AES S-box is generated using finite field inversion,\n// an affine transform, and xor of a constant 0x63.\nconst sbox = /* @__PURE__ */ (() => {\n const t = new Uint8Array(256);\n // Repeated multiplication by {03} walks all 255 nonzero field elements\n // once, so t[255 - i] is the multiplicative inverse of t[i] for the\n // affine step.\n for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))\n t[i] = x;\n const box = new Uint8Array(256);\n // FIPS 197 upd1 §5.1.1: SBOX({00}) = {63} because the inverse step leaves\n // {00} at {00}, then the affine transform xors in c = {63}.\n box[0] = 0x63;\n for (let i = 0; i < 255; i++) {\n let x = t[255 - i];\n x |= x << 8;\n box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;\n }\n clean(t);\n return box;\n})();\n// FIPS 197 upd1 §5.3.2: INVSBOX() is derived from SBOX() by swapping input\n// and output roles (Table 6).\n// `indexOf` is only used once at module init, so the quadratic setup cost stays off hot paths.\nconst invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));\n// FIPS 197 upd1 §5.2: ROTWORD([a0,a1,a2,a3]) = [a1,a2,a3,a0]; with this LE\n// word packing that is a right rotate by 8 bits.\nconst rotr32_8 = (n) => (n << 24) | (n >>> 8);\n// LE T-table helper: rotates one precomputed word by one byte so T1/T2/T3\n// reuse T0's substitution/mix result in the other byte lanes.\nconst rotl32_8 = (n) => (n << 8) | (n >>> 24);\n// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:\n// - LE instead of BE\n// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;\n// so index is u16, instead of u8. This speeds up things, unexpectedly\nfunction genTtable(sbox, fn) {\n if (sbox.length !== 256)\n throw new Error('wrong sbox length');\n const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));\n const T1 = T0.map(rotl32_8);\n const T2 = T1.map(rotl32_8);\n const T3 = T2.map(rotl32_8);\n // Pre-xor adjacent lanes so apply0123/applySbox can fetch two substituted\n // byte lanes per lookup in the LE round layout.\n const T01 = new Uint32Array(256 * 256);\n const T23 = new Uint32Array(256 * 256);\n const sbox2 = new Uint16Array(256 * 256);\n for (let i = 0; i < 256; i++) {\n for (let j = 0; j < 256; j++) {\n const idx = i * 256 + j;\n T01[idx] = T0[i] ^ T1[j];\n T23[idx] = T2[i] ^ T3[j];\n sbox2[idx] = (sbox[i] << 8) | sbox[j];\n }\n }\n return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };\n}\n// Forward round precompute: the packed word stores the MIXCOLUMNS row\n// [{02},{01},{01},{03}] in LE byte-lane order, and the returned `sbox2`\n// is also reused by key expansion and the final round.\nconst tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2));\n// Inverse round precompute: the packed word stores the INVMIXCOLUMNS row\n// [{0e},{09},{0d},{0b}] in LE byte-lane order, and the tables are reused\n// by decrypt() and expandKeyDecLE().\nconst tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14));\n// FIPS 197 upd1 §5.2 Table 5: left-most bytes of Rcon[j] = x^(j-1), generated by repeated XTIMES().\nconst xPowers = /* @__PURE__ */ (() => {\n const p = new Uint8Array(16);\n for (let i = 0, x = 1; i < 16; i++, x = mul2(x))\n p[i] = x;\n return p;\n})();\n/** Forward AES key expansion used across ECB/CBC/CTR/GCM/CMAC/KW-style paths. */\nfunction expandKeyLE(key) {\n abytes(key);\n const len = key.length;\n validateKeyLength(key);\n const { sbox2 } = tableEncoding;\n const toClean = [];\n // Copy on BE or misaligned inputs so the LE word normalization below never\n // mutates caller key bytes in place.\n if (!isLE || !isAligned32(key))\n toClean.push((key = copyBytes(key)));\n const k32 = swap32IfBE(u32(key));\n const Nk = k32.length;\n // `applySbox` normally reads one byte lane from each argument; repeating\n // `n` across all four lanes turns it into SUBWORD(n).\n const subByte = (n) => applySbox(sbox2, n, n, n, n);\n // AES key sizes are 16/24/32 bytes, so len + 28 yields the 44/52/60\n // schedule words from FIPS 197 §5.2 / Table 3.\n const xk = new Uint32Array(len + 28); // expanded key\n xk.set(k32);\n // 4.3.1 Key expansion\n for (let i = Nk; i < xk.length; i++) {\n let t = xk[i - 1];\n if (i % Nk === 0)\n t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];\n else if (Nk > 6 && i % Nk === 4)\n t = subByte(t);\n xk[i] = xk[i - Nk] ^ t;\n }\n clean(...toClean);\n return xk;\n}\nfunction expandKeyDecLE(key) {\n const encKey = expandKeyLE(key);\n const xk = encKey.slice();\n const Nk = encKey.length;\n const { sbox2 } = tableEncoding;\n const { T0, T1, T2, T3 } = tableDecoding;\n // Local decrypt() walks round keys forward from xk[0], so reverse the\n // encryption round-key blocks first before applying the equivalent-inverse\n // middle-round transform.\n for (let i = 0; i < Nk; i += 4) {\n for (let j = 0; j < 4; j++)\n xk[i + j] = encKey[Nk - i - 4 + j];\n }\n clean(encKey);\n // Apply InvMixColumn to the reversed round keys using the same LE sbox2\n // packing as the forward path.\n // apply InvMixColumn except first & last round\n for (let i = 4; i < Nk - 4; i++) {\n const x = xk[i];\n const w = applySbox(sbox2, x, x, x, x);\n xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];\n }\n return xk;\n}\n// Apply tables\nfunction apply0123(T01, T23, s0, s1, s2, s3) {\n // `T01` takes the low byte lane from `s0` plus the next lane from `s1`;\n // `T23` does the same for `s2`/`s3`.\n // Equivalent to `T0[s0&0xff] ^ T1[(s1>>>8)&0xff] ^ T2[(s2>>>16)&0xff] ^\n // T3[s3>>>24]`, but with two merged-table fetches.\n return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^\n T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]);\n}\nfunction applySbox(sbox2, s0, s1, s2, s3) {\n // `sbox2` packs two substituted byte lanes at a time in the same LE\n // layout used by the round code.\n // Equivalent to `SBOX(byte0(s0)) | SBOX(byte1(s1))<<8 |\n // SBOX(byte2(s2))<<16 | SBOX(byte3(s3))<<24`.\n return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] |\n (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16));\n}\nfunction encrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableEncoding;\n let k = 0;\n ((s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]));\n // `xk` has Nr+1 round-key blocks, so after the initial AddRoundKey and the\n // final S-box-only round there are Nr-1 full table/MixColumns rounds left.\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);\n ((s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3));\n }\n // last round (without mixcolumns, so using SBOX2 table)\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different\nfunction decrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableDecoding;\n let k = 0;\n ((s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]));\n // With `expandKeyDecLE()` the round keys are already reversed and middle\n // rounds are InvMixColumns-adjusted, so this loop follows the equivalent\n // inverse cipher order directly.\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);\n ((s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3));\n }\n // Final equivalent-inverse round omits InvMixColumns, so use inverse\n // S-box lanes in InvShiftRows order.\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\nfunction ctrCounter(xk, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE, 'nonce');\n abytes(src);\n const srcLen = src.length;\n dst = getOutput(srcLen, dst);\n complexOverlapBytes(src, dst);\n // Internal helper: mutate `nonce` in place as the live counter block so\n // each encrypted block uses the next CTR value.\n const ctr = nonce;\n const c32 = u32(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n const { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));\n dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0);\n dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1);\n dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2);\n dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3);\n // Full 128 bit big-endian counter with wrap around. Same fixed-shape\n // 16-byte carry walk as incBytes(ctr, false, 1), inlined to skip its\n // per-call argument validation on the per-block hot path.\n for (let j = BLOCK_SIZE - 1, carry = 1; j >= 0; j--) {\n carry = (carry + ctr[j]) | 0;\n ctr[j] = carry & 0xff;\n carry >>>= 8;\n }\n }\n // NIST SP 800-38A CTR mode uses the leading `u` bits of the next output\n // block for the final short block.\n // It's possible to handle > u32 fast, but is it worth it?\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n swap32IfBE(b32);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n // Unsafe mutable-counter API only advances whole blocks. Callers that want to\n // resume after consuming part of this block must re-run from the same counter\n // with left-padding and strip the already-consumed prefix themselves.\n return dst;\n}\n// AES CTR with overflowing 32 bit counter\n// It's possible to do 32le significantly simpler (and probably faster) by using u32.\n// But, we need both, and perf bottleneck is in ghash anyway.\n// Unsafe 32-bit CTR helper: mutates `nonce` in place, expects aligned `src`/`dst`,\n// and uses `isLE` to choose which 32-bit counter word is incremented.\nfunction ctr32(xk, isLE, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE, 'nonce');\n abytes(src);\n dst = getOutput(src.length, dst);\n const ctr = nonce; // write new value to nonce, so it can be re-used\n const c32 = u32(ctr);\n const view = createView(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // NIST SP 800-38D GCTR increments the rightmost 32 bits of J0, while\n // RFC 8452 AES-GCM-SIV increments the first 32 bits as a little-endian u32.\n const ctrPos = isLE ? 0 : 12;\n const srcLen = src.length;\n let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n const { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));\n dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0);\n dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1);\n dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2);\n dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3);\n ctrNum = (ctrNum + 1) >>> 0; // u32 wrap\n view.setUint32(ctrPos, ctrNum, isLE);\n }\n // leftovers (less than a block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n swap32IfBE(b32);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n // Same unsafe contract as ctrCounter(): only full blocks advance the stored\n // mutable counter state; partial-block continuation is caller-managed.\n return dst;\n}\n/**\n * **CTR** (Counter Mode): turns a block cipher into a stream cipher using a\n * full 16-byte counter block.\n * Efficient and parallelizable. Requires a unique nonce per encryption. Unauthenticated: needs MAC.\n * @param key - AES key bytes.\n * @param nonce - 16-byte counter block, incremented as a full AES block.\n * @returns Cipher instance with `encrypt()` and `decrypt()`.\n * @example\n * Encrypts a short payload with a fresh AES key and counter block.\n *\n * ```ts\n * import { ctr } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const nonce = randomBytes(16);\n * const cipher = ctr(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const ctr = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aesctr(key, nonce) {\n function processCtr(buf, dst) {\n abytes(buf);\n if (dst !== undefined) {\n abytes(dst);\n // Optional output buffers must stay 4-byte aligned because\n // ctrCounter() reinterprets them as Uint32Array words.\n if (!isAligned32(dst))\n throw new Error('unaligned destination');\n }\n const xk = expandKeyLE(key);\n // Public CTR keeps caller nonce bytes immutable even though ctrCounter()\n // advances the live 16-byte counter block in place.\n const n = copyBytes(nonce); // align + avoid changing\n const toClean = [xk, n];\n if (!isAligned32(buf))\n toClean.push((buf = copyBytes(buf)));\n const out = ctrCounter(xk, n, buf, dst);\n clean(...toClean);\n return out;\n }\n return {\n encrypt: (plaintext, dst) => processCtr(plaintext, dst),\n decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),\n };\n});\nfunction validateBlockDecrypt(data, dst) {\n abytes(data);\n // ECB/CBC decryption always consumes whole ciphertext blocks; PKCS#7/CMS\n // padding, when enabled, is removed only after decrypting the final block.\n if (data.length % BLOCK_SIZE !== 0) {\n throw new Error('ciphertext must be multiple of ' + BLOCK_SIZE);\n }\n // Validate caller-provided output before key expansion; allocation happens after it.\n if (dst !== undefined) {\n getOutput(data.length, dst);\n complexOverlapBytes(data, dst);\n }\n}\n// ECB/CBC core modes operate on whole blocks; `pkcs5` enables the library's\n// PKCS#7/CMS-compatible final-block padding convenience before encryption.\nfunction validateBlockEncrypt(plaintext, pkcs5, dst) {\n abytes(plaintext);\n let outLen = plaintext.length;\n const remaining = outLen % BLOCK_SIZE;\n if (!pkcs5 && remaining !== 0)\n throw new Error('plaintext must be multiple of ' + BLOCK_SIZE);\n if (pkcs5) {\n let left = BLOCK_SIZE - remaining;\n // RFC 5652 pads even already-aligned inputs, so a full extra block is\n // appended when the plaintext length is already a multiple of 16 bytes.\n if (!left)\n left = BLOCK_SIZE; // if no bytes left, create empty padding block\n outLen = outLen + left;\n }\n // Validate caller-provided output before key expansion; allocation happens after it.\n if (dst !== undefined) {\n getOutput(outLen, dst);\n complexOverlapBytes(plaintext, dst);\n }\n return outLen;\n}\nfunction prepareBlockEncrypt(plaintext, outLen, dst) {\n if (dst === undefined)\n dst = new Uint8Array(outLen);\n // Copy on BE or misaligned inputs so u32()/swap32IfBE() normalization never\n // mutates caller plaintext bytes in place before ECB/CBC processing.\n if (!isLE || !isAligned32(plaintext))\n plaintext = copyBytes(plaintext);\n const o = u32(dst);\n // Keep the full byte owner so callers can wipe a conditional copy without rebuilding a view.\n return { b: plaintext, o, out: dst };\n}\n// `pkcs5` is the historical option name; for AES's 16-byte block this is the\n// generic PKCS#7/CMS-style block-padding rule on decrypt.\nfunction validatePKCS(data, pkcs5) {\n if (!pkcs5)\n return data;\n const len = data.length;\n // RFC 5652 pads even empty / already-aligned inputs, so a valid padded\n // ECB/CBC ciphertext is never empty when PKCS#7/CMS unpadding is enabled.\n // AES-CBC/ECB ciphertext should be full blocks before unpadding\n if (len === 0)\n throw new Error('pkcs7: empty ciphertext not allowed');\n const lastByte = data[len - 1];\n let valid = 1;\n valid &= ((lastByte - 1) >>> 31) ^ 1; // pad >= 1\n valid &= ((16 - lastByte) >>> 31) ^ 1; // pad <= 16\n // Check exactly 16 tail bytes in constant-shape loop\n // For i < pad: byte must equal pad\n // For i >= pad: ignore byte\n for (let i = 0; i < 16; i++) {\n // const b = data[len - 1 - i];\n const shouldCheck = (i - lastByte) >>> 31; // 1 if i < pad else 0\n const eq = (data[len - 1 - i] ^ lastByte) === 0 ? 1 : 0; // 1 if equal\n valid &= eq | (shouldCheck ^ 1); // pass if equal OR not checked\n }\n // if (invalidLen) throw new Error('aes/pkcs7: ciphertext length must be multiple of 16');\n // Padding rejection is observable as a decrypt failure; authenticate CBC/ECB\n // ciphertexts before decrypting or use `disablePadding` in a higher-level protocol.\n if (!valid)\n throw new Error('aes: bad decrypt');\n return data.subarray(0, len - lastByte);\n}\n// ECB/CBC callers only pass the final short block here, so `left.length` is\n// 0..15 and the helper always emits exactly one padded 16-byte block.\nfunction padPCKS(left) {\n const tmp = new Uint8Array(16);\n const tmp32 = u32(tmp);\n tmp.set(left);\n const paddingByte = BLOCK_SIZE - left.length;\n // RFC 5652 §6.3 fills the whole suffix with the padding length byte:\n // e.g. `aa 0f..0f` for a 1-byte tail, or `10..10` for a full extra block.\n for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)\n tmp[i] = paddingByte;\n return tmp32;\n}\n/**\n * **ECB** (Electronic Codebook): Deterministic encryption; identical plaintext blocks yield\n * identical ciphertexts. Not secure due to pattern leakage.\n * See {@link https://words.filippo.io/the-ecb-penguin/ | the AES Penguin}.\n * @param key - AES key bytes.\n * @param opts - Padding options. See {@link BlockOpts}.\n * @returns Cipher instance with `encrypt()` and `decrypt()`.\n * @example\n * Shows the basic ECB encrypt call shape with a fresh key; avoid ECB in new designs.\n *\n * ```ts\n * import { ecb } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const cipher = ecb(key);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const ecb = /* @__PURE__ */ wrapCipher({ blockSize: 16 }, function aesecb(key, opts = {}) {\n const pkcs5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n const outLen = validateBlockEncrypt(plaintext, pkcs5, dst);\n const xk = expandKeyLE(key);\n const { b: input, o, out: _out } = prepareBlockEncrypt(plaintext, outLen, dst);\n const b = u32(input);\n swap32IfBE(b);\n let i = 0;\n for (; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n }\n if (pkcs5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n swap32IfBE(tmp32);\n const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n // The padding scratch contains the final plaintext tail; wipe it as soon as consumed.\n clean(tmp32);\n }\n swap32IfBE(o);\n clean(xk);\n if (input !== plaintext)\n clean(input);\n return _out;\n },\n decrypt(ciphertext, dst) {\n // Validate inputs before expanding the key, so a validation throw\n // never leaves an unwiped expanded key behind.\n validateBlockDecrypt(ciphertext, dst);\n const xk = expandKeyDecLE(key);\n if (dst === undefined)\n dst = new Uint8Array(ciphertext.length);\n const toClean = [xk];\n // Copy on BE or misaligned ciphertext so u32()/swap32IfBE()\n // normalization never mutates caller bytes in place before decrypt().\n if (!isLE || !isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const b = u32(ciphertext);\n const o = u32(dst);\n swap32IfBE(b);\n for (let i = 0; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n }\n swap32IfBE(o);\n clean(...toClean);\n return validatePKCS(dst, pkcs5);\n },\n };\n});\n/**\n * **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the\n * previous block of ciphertext before encryption.\n * Hard to use: requires proper padding and an unpredictable IV. Unauthenticated: needs MAC.\n * Bad padding is reported as decrypt failure, which can be a padding oracle if exposed.\n * @param key - AES key bytes.\n * @param iv - 16-byte unpredictable initialization vector.\n * @param opts - Padding options. See {@link BlockOpts}.\n * @returns Cipher instance with `encrypt()` and `decrypt()`.\n * @example\n * Encrypts a padded message with a fresh key and 16-byte IV.\n *\n * ```ts\n * import { cbc } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const iv = randomBytes(16);\n * const cipher = cbc(key, iv);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const cbc = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescbc(key, iv, opts = {}) {\n const pkcs5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n // Validate inputs before expanding the key, so a validation throw\n // never leaves an unwiped expanded key behind.\n const outLen = validateBlockEncrypt(plaintext, pkcs5, dst);\n const xk = expandKeyLE(key);\n const { b: input, o, out: _out } = prepareBlockEncrypt(plaintext, outLen, dst);\n const b = u32(input);\n swap32IfBE(b);\n let _iv = iv;\n const toClean = [xk];\n // Copy on BE or misaligned inputs so IV normalization and the mutable\n // local chaining state never write back into caller IV bytes.\n if (!isLE || !isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n swap32IfBE(n32);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n let i = 0;\n for (; i + 4 <= b.length;) {\n ((s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]));\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n }\n if (pkcs5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n swap32IfBE(tmp32);\n ((s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]));\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n // The padding scratch contains the final plaintext tail; wipe it as soon as consumed.\n clean(tmp32);\n }\n swap32IfBE(o);\n clean(...toClean);\n if (input !== plaintext)\n clean(input);\n return _out;\n },\n decrypt(ciphertext, dst) {\n // Validate inputs before expanding the key, so a validation throw\n // never leaves an unwiped expanded key behind.\n validateBlockDecrypt(ciphertext, dst);\n const xk = expandKeyDecLE(key);\n if (dst === undefined)\n dst = new Uint8Array(ciphertext.length);\n let _iv = iv;\n const toClean = [xk];\n // Copy on BE or misaligned inputs so IV normalization and the mutable\n // local chaining state never write back into caller IV bytes.\n if (!isLE || !isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n swap32IfBE(n32);\n // Copy on BE or misaligned ciphertext so u32()/swap32IfBE()\n // normalization never mutates caller bytes in place before decrypt().\n if (!isLE || !isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const b = u32(ciphertext);\n const o = u32(dst);\n swap32IfBE(b);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= b.length;) {\n // prettier-ignore\n const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;\n ((s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]));\n const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);\n ((o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3));\n }\n swap32IfBE(o);\n clean(...toClean);\n return validatePKCS(dst, pkcs5);\n },\n };\n});\n/**\n * CFB (CFB-128): Cipher Feedback Mode with 128-bit segments. The input for the\n * block cipher is the previous cipher output.\n * Unauthenticated: needs MAC.\n * @param key - AES key bytes.\n * @param iv - 16-byte unpredictable initialization vector.\n * @returns Cipher instance with `encrypt()` and `decrypt()`.\n * @example\n * Encrypts a short message with feedback mode and a fresh key/IV pair.\n *\n * ```ts\n * import { cfb } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const iv = randomBytes(16);\n * const cipher = cfb(key, iv);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const cfb = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescfb(key, iv) {\n function processCfb(src, isEncrypt, dst) {\n abytes(src);\n const srcLen = src.length;\n dst = getOutput(srcLen, dst);\n // CFB feeds back previous ciphertext, so overlapping src/dst could\n // overwrite bytes that are still needed as the next feedback block.\n if (overlapBytes(src, dst))\n throw new Error('overlapping src and dst not supported');\n const xk = expandKeyLE(key);\n let _iv = iv;\n const toClean = [xk];\n // Copy on BE or misaligned inputs so u32()/swap32IfBE() normalization\n // never mutates caller IV/src bytes in place before CFB processing.\n if (!isLE || !isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n if (!isLE || !isAligned32(src))\n toClean.push((src = copyBytes(src)));\n const src32 = u32(src);\n const dst32 = u32(dst);\n // NIST SP 800-38A §6.3 feeds back the previous ciphertext segment in\n // both directions: encrypt reuses freshly written dst words, decrypt\n // reuses the source ciphertext words.\n const next32 = isEncrypt ? dst32 : src32;\n const n32 = u32(_iv);\n swap32IfBE(src32);\n swap32IfBE(n32);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= src32.length;) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n ((s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]));\n }\n // leftovers (less than block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n // The byte tail loop reads `src` directly; restore any BE-swapped tail words first.\n if (!isLE)\n swap32IfBE(src32.subarray(start / 4));\n // Byte-oriented API: for a final short tail, reuse the next CFB-128\n // output block and XOR only the needed prefix. RFC 3826 §3.1.3 /\n // §3.1.4 describes the same no-padding rule at bit granularity for a\n // final r<=128 segment.\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n const tmp = new Uint32Array([s0, s1, s2, s3]);\n swap32IfBE(tmp);\n const buf = u8(tmp);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(buf);\n }\n if (!isLE)\n swap32IfBE(dst32.subarray(0, start / 4));\n clean(...toClean);\n return dst;\n }\n return {\n encrypt: (plaintext, dst) => processCfb(plaintext, true, dst),\n decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst),\n };\n});\n// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen\n// `data` is the payload covered by the polynomial MAC: ciphertext for GCM,\n// plaintext for GCM-SIV. Keep AAD/data/length as separate updates because\n// GHASH/POLYVAL pad each call to block boundaries, so the chunks must match the\n// spec-defined segments instead of arbitrary concatenation boundaries.\nfunction computeTag(fn, isLE, key, data, AAD) {\n const aadLength = AAD ? AAD.length : 0;\n const h = fn.create(key, data.length + aadLength);\n if (AAD)\n h.update(AAD);\n // u64Lengths() takes (dataBits, aadBits) but still serializes the final\n // block as len(AAD) || len(data), matching both GCM and GCM-SIV.\n const num = u64Lengths(8 * data.length, 8 * aadLength, isLE);\n h.update(data);\n h.update(num);\n const res = h.digest();\n clean(num);\n return res;\n}\n/**\n * **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used.\n * Not perfect:\n * a) conservative key wear-out is `2**32` (4B) msgs.\n * b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance.\n * c) MAC can be forged: see Poly1305 documentation.\n * @param key - AES key bytes.\n * @param nonce - Nonce bytes (12 recommended, minimum 8; other lengths use GHASH J0 derivation).\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance with a fixed 16-byte tag.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and 12-byte nonce.\n *\n * ```ts\n * import { gcm } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const nonce = randomBytes(12);\n * const aad = new TextEncoder().encode('session metadata');\n * const cipher = gcm(key, nonce, aad);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const gcm = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, withAAD: true, varSizeNonce: true }, function aesgcm(key, nonce, AAD) {\n // SP 800-38D lets implementations narrow supported IV lengths.\n // This wrapper intentionally requires at least 8 bytes; OpenSSL accepts shorter IVs too.\n // 12-byte nonces take the fast path; other allowed lengths use GHASH to derive J0.\n if (nonce.length < 8)\n throw new Error('aes/gcm: invalid nonce length');\n const tagLength = 16;\n function _computeTag(authKey, tagMask, data) {\n const tag = computeTag(ghash, false, authKey, data, AAD);\n for (let i = 0; i < tagMask.length; i++)\n tag[i] ^= tagMask[i];\n return tag;\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const authKey = EMPTY_BLOCK.slice();\n const counter = EMPTY_BLOCK.slice();\n ctr32(xk, false, counter, counter, authKey);\n // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces\n if (nonce.length === 12) {\n counter.set(nonce);\n }\n else {\n const nonceLen = EMPTY_BLOCK.slice();\n const view = createView(nonceLen);\n view.setBigUint64(8, BigInt(nonce.length * 8), false);\n // GHASH.update() pads each call to 16 bytes, so\n // update(nonce).update(nonceLen) realizes\n // IV || 0^s || 0^64 || [len(IV)]_64 for non-96-bit nonces.\n // ghash(nonce || u64be(0) || u64be(nonceLen*8))\n const g = ghash.create(authKey).update(nonce).update(nonceLen);\n g.digestInto(counter); // digestInto doesn't trigger '.destroy'\n g.destroy();\n }\n // GCTR_K(J0, 0^128) = E_K(J0); reusing ctr32() here extracts that tag\n // mask and leaves `counter` advanced to inc32(J0) for payload GCTR.\n const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);\n return { xk, authKey, counter, tagMask };\n }\n return {\n encrypt(plaintext) {\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const out = new Uint8Array(plaintext.length + tagLength);\n const toClean = [xk, authKey, counter, tagMask];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length));\n const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));\n toClean.push(tag);\n out.set(tag, plaintext.length);\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const toClean = [xk, authKey, tagMask, counter];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = _computeTag(authKey, tagMask, data);\n toClean.push(tag);\n // NIST SP 800-38D §7.2 permits equivalent step orderings; verify the\n // tag before CTR so unauthenticated plaintext is never materialized.\n if (!equalBytes(tag, passedTag)) {\n clean(...toClean);\n throw new Error('aes-gcm: invalid tag');\n }\n const out = ctr32(xk, false, counter, data);\n clean(...toClean);\n return out;\n },\n };\n});\nconst limit = (name, min, max) => (value) => {\n // Current AES-SIV/GCM-SIV callers pass protocol limits from RFC 8452 / RFC 5297,\n // not arbitrary library-preference bounds.\n // Callers feed Uint8Array.length values here, so safe-integer rejection\n // does not exclude any representable input even when an RFC bound is larger.\n if (!Number.isSafeInteger(value) || min > value || value > max) {\n const minmax = '[' + min + '..' + max + ']';\n throw new Error('' + name + ': expected value in range ' + minmax + ', got ' + value);\n }\n};\n/**\n * **SIV** (Synthetic IV): GCM with nonce-misuse resistance.\n * Repeating nonces reveal only the fact plaintexts are identical.\n * Also suffers from GCM issues: key wear-out limits & MAC forging.\n * See {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.\n * RFC 8452 defines 16-byte and 32-byte AES keys for this mode.\n * This implementation also accepts 24-byte AES-192 keys as a local\n * extension; see the inline comment next to `validateKeyLength(key)` below\n * for the exact scope note.\n * @param key - AES key bytes.\n * @param nonce - 12-byte nonce.\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and nonce, while tolerating reuse.\n *\n * ```ts\n * import { gcmsiv } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const nonce = randomBytes(12);\n * const aad = new TextEncoder().encode('session metadata');\n * const cipher = gcmsiv(key, nonce, aad);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const gcmsiv = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, withAAD: true, varSizeNonce: true }, function aessiv(key, nonce, AAD) {\n const tagLength = 16;\n // From RFC 8452: Section 6\n const AAD_LIMIT = limit('AAD', 0, 2 ** 36);\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);\n const NONCE_LIMIT = limit('nonce', 12, 12);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);\n abytes(key);\n // RFC 8452 only standardizes 16-byte and 32-byte key-generating keys.\n // The accepted 24-byte path is a local AES-192 extension outside the RFC-defined AEADs.\n validateKeyLength(key);\n NONCE_LIMIT(nonce.length);\n if (AAD !== undefined)\n AAD_LIMIT(AAD.length);\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const encKey = new Uint8Array(key.length);\n const authKey = new Uint8Array(16);\n const toClean = [xk, encKey];\n let _nonce = nonce;\n // Copy on BE or misaligned nonce so u32()/swap32IfBE() normalization\n // never mutates caller nonce bytes before RFC 8452 key derivation.\n if (!isLE || !isAligned32(_nonce))\n toClean.push((_nonce = copyBytes(_nonce)));\n const n32 = u32(_nonce);\n swap32IfBE(n32);\n // prettier-ignore\n let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];\n let counter = 0;\n for (const derivedKey of [authKey, encKey].map(u32)) {\n const d32 = u32(derivedKey);\n for (let i = 0; i < d32.length; i += 2) {\n // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...\n const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);\n d32[i + 0] = o0;\n d32[i + 1] = o1;\n s0 = ++counter; // increment counter inside state\n }\n swap32IfBE(d32);\n }\n const res = { authKey, encKey: expandKeyLE(encKey) };\n // Cleanup\n clean(...toClean);\n return res;\n }\n function _computeTag(encKey, authKey, data) {\n const tag = computeTag(polyval, true, authKey, data, AAD);\n // Compute the expected tag by XORing S_s and the nonce, clearing the\n // most significant bit of the last byte and encrypting with the\n // message-encryption key.\n for (let i = 0; i < 12; i++)\n tag[i] ^= nonce[i];\n tag[15] &= 0x7f; // Clear the highest bit\n // encrypt tag as block\n const t32 = u32(tag);\n swap32IfBE(t32);\n // prettier-ignore\n let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];\n ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));\n ((t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3));\n swap32IfBE(t32);\n return tag;\n }\n // actual decrypt/encrypt of message.\n function processSiv(encKey, tag, input) {\n let block = copyBytes(tag);\n // RFC 8452 §4 / §5 use the tag with the highest bit of the last byte\n // forced to one as the initial AES-CTR counter block.\n block[15] |= 0x80; // Force highest bit\n const res = ctr32(encKey, true, block, input);\n // Cleanup\n clean(block);\n return res;\n }\n return {\n encrypt(plaintext) {\n PLAIN_LIMIT(plaintext.length);\n const { encKey, authKey } = deriveKeys();\n const tag = _computeTag(encKey, authKey, plaintext);\n const toClean = [encKey, authKey, tag];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n const out = new Uint8Array(plaintext.length + tagLength);\n out.set(tag, plaintext.length);\n out.set(processSiv(encKey, tag, plaintext));\n // Cleanup\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n CIPHER_LIMIT(ciphertext.length);\n const tag = ciphertext.subarray(-tagLength);\n const { encKey, authKey } = deriveKeys();\n const toClean = [encKey, authKey];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));\n const expectedTag = _computeTag(encKey, authKey, plaintext);\n toClean.push(expectedTag);\n // RFC 8452 §5: plaintext is unauthenticated here and MUST NOT be\n // returned until the expected-tag check completes successfully.\n if (!equalBytes(tag, expectedTag)) {\n clean(plaintext, ...toClean);\n throw new Error('invalid polyval tag');\n }\n // Cleanup\n clean(...toClean);\n return plaintext;\n },\n };\n});\nfunction isBytes32(a) {\n // Plain `instanceof Uint32Array` is too strict for cross-realm expanded-key views.\n // This is only a best-effort unsafe-export guard, not a provenance proof for `expandKeyLE`.\n return (a instanceof Uint32Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint32Array'));\n}\n// Unsafe single-block helpers: mutate `block` in place and require its 16-byte\n// Uint8Array view to be 4-byte aligned because `u32(block)` reinterprets it.\nfunction encryptBlock(xk, block) {\n abytes(block, 16, 'block');\n if (!isBytes32(xk))\n throw new Error('_encryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n swap32IfBE(b32);\n let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n ((b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3));\n swap32IfBE(b32);\n return block;\n}\nfunction decryptBlock(xk, block) {\n abytes(block, 16, 'block');\n if (!isBytes32(xk))\n throw new Error('_decryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n swap32IfBE(b32);\n let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n ((b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3));\n swap32IfBE(b32);\n return block;\n}\n/**\n * AES-W (base for AESKW/AESKWP).\n * Specs:\n * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | SP800-38F},\n * {@link https://www.rfc-editor.org/rfc/rfc3394 | RFC 3394},\n * {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}.\n * Shared core mutates `out` in place; callers are responsible for prepending\n * the right IV/AIV and checking the recovered value after decrypt.\n */\nconst AESW = {\n /*\n High-level pseudocode:\n ```\n A: u64 = IV\n out = []\n for (let i=0, ctr = 0; i<6; i++) {\n for (const chunk of chunks(plaintext, 8)) {\n A ^= swapEndianess(ctr++)\n [A, res] = chunks(encrypt(A || chunk), 8);\n out ||= res\n }\n }\n out = A || out\n ```\n Decrypt is the same, but reversed.\n */\n encrypt(kek, out) {\n // Current implementation keeps RFC 3394/5649 `t` in a u32-shaped counter,\n // so the shared core caps plaintext below 4 GiB even though the specs allow more.\n if (out.length >= 2 ** 32)\n throw new Error('plaintext should be less than 4gb');\n const xk = expandKeyLE(kek);\n // 16-byte `S = A || P[1]` is the RFC 5649 KWP special case for n=1;\n // KW callers never reach it because KW requires at least two plaintext semiblocks.\n if (out.length === 16)\n encryptBlock(xk, out);\n else {\n const o32 = u32(out);\n swap32IfBE(o32);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = 1; j < 6; j++) {\n for (let pos = 2; pos < o32.length; pos += 2, ctr++) {\n const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n // A = MSB(64, B) ^ t where t = (n*j)+i. Under the 32-bit length cap\n // above, `t` fits in the low half of `[t]_64`, so xor only the low\n // 32 bits of A after converting `ctr` to network order.\n ((a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3));\n }\n }\n ((o32[0] = a0), (o32[1] = a1)); // out = A || out\n swap32IfBE(o32);\n }\n xk.fill(0);\n },\n decrypt(kek, out) {\n // Same implementation cap on the recovered plaintext length after\n // removing the 8-byte A/IV prefix.\n if (out.length - 8 >= 2 ** 32)\n throw new Error('ciphertext should be less than 4gb');\n const xk = expandKeyDecLE(kek);\n const chunks = out.length / 8 - 1; // first chunk is IV\n // `n = 2` semiblocks is the RFC 5649 KWP special case; KW ciphertexts\n // always have at least three semiblocks and therefore use the W^-1 loop.\n if (chunks === 1)\n decryptBlock(xk, out);\n else {\n const o32 = u32(out);\n swap32IfBE(o32);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = chunks * 6; j < 6; j++) {\n for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {\n a1 ^= byteSwap(ctr);\n const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n ((a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3));\n }\n }\n ((o32[0] = a0), (o32[1] = a1));\n swap32IfBE(o32);\n }\n xk.fill(0);\n },\n};\n// RFC 3394 §2.2.3.1 / NIST SP 800-38F Algorithm 3 / Algorithm 4: KW prepends\n// the default 64-bit ICV1 and unwrap must verify the same value.\nconst AESKW_IV = /* @__PURE__ */ new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6\n/**\n * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.\n * Reduces block size from 16 to 8 bytes.\n * Plaintext must be a non-empty multiple of 8 bytes with minimum 16 bytes.\n * 8-byte inputs use aeskwp.\n * Wrapped ciphertext must be a multiple of 8 bytes with minimum 24 bytes.\n * For padded version, use aeskwp.\n * See {@link https://www.rfc-editor.org/rfc/rfc3394/ | RFC 3394} and\n * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | NIST SP 800-38F}.\n * @param kek - AES key-encryption key.\n * @returns Key-wrap cipher instance.\n * As with other `wrapCipher(...)` wrappers, `encrypt()` is single-use per\n * instance.\n * @example\n * Wraps a 128-bit content-encryption key with a fresh key-encryption key.\n *\n * ```ts\n * import { aeskw } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const kek = randomBytes(16);\n * const cek = randomBytes(16);\n * const wrap = aeskw(kek);\n * wrap.encrypt(cek);\n * ```\n */\nexport const aeskw = /* @__PURE__ */ wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n if (!plaintext.length || plaintext.length % 8 !== 0)\n throw new Error('invalid plaintext length');\n // RFC 3394 / NIST SP 800-38F define KW only for >=2 plaintext\n // semiblocks; the 1-semiblock case belongs to RFC 5649 KWP.\n if (plaintext.length === 8)\n throw new Error('8-byte keys not allowed, use AESKWP');\n const out = concatBytes(AESKW_IV, plaintext);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n // ciphertext must be at least 24 bytes and a multiple of 8 bytes\n // 24 because should have at least two block (1 iv + 2).\n // Replace with 16 to enable '8-byte keys'\n if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8)\n throw new Error('invalid ciphertext length');\n // AESW.decrypt() mutates its buffer in place, so keep caller ciphertext\n // immutable across the unwrap, ICV1 check, and IV scrubbing below.\n const out = copyBytes(ciphertext);\n AESW.decrypt(kek, out);\n if (!equalBytes(out.subarray(0, 8), AESKW_IV))\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8);\n },\n}));\n/*\nWe don't support 8-byte keys. The rabbit hole:\n\n- Wycheproof says: \"NIST SP 800-38F does not define the wrapping of 8 byte keys.\n RFC 3394 Section 2 on the other hand specifies that 8 byte keys are wrapped\n by directly encrypting one block with AES.\"\n - {@link https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md | Wycheproof key-wrap note}\n - \"RFC 3394 specifies in Section 2, that the input for the key wrap\n algorithm must be at least two blocks and otherwise the constant\n field and key are simply encrypted with ECB as a single block\"\n- What RFC 3394 actually says (in Section 2):\n - \"Before being wrapped, the key data is parsed into n blocks of 64 bits.\n The only restriction the key wrap algorithm places on n is that n be\n at least two\"\n - \"For key data with length less than or equal to 64 bits, the constant\n field used in this specification and the key data form a single\n 128-bit codebook input making this key wrap unnecessary.\"\n- Which means \"assert(n >= 2)\" and \"use something else for 8 byte keys\"\n- NIST SP800-38F actually prohibits 8-byte in \"5.3.1 Mandatory Limits\".\n It states that plaintext for KW should be \"2 to 2^54 -1 semiblocks\".\n- So, where does \"directly encrypt single block with AES\" come from?\n - Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses\n loop of 6 for any code path\n - There is a weird W3C spec:\n {@link https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128 | XML Encryption AES key-wrap section}\n - This spec is outdated, as admitted by Wycheproof authors\n - There is RFC 5649 for padded key wrap, which is padding construction on\n top of AESKW. In '4.1.2' it says: \"If the padded plaintext contains exactly\n eight octets, then prepend the AIV as defined in Section 3 above to P[1] and\n encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key\n K (the KEK). In this case, the output is two 64-bit blocks C[0] and C[1]:\"\n - Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes:\n `Error: error:1C8000E6:Provider routines::invalid input length]\n { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]`\n\nIn the end, seems like a bug in Wycheproof.\nThe 8-byte check can be easily disabled inside of AES_W.\n*/\n// RFC 5649 §3 / NIST SP 800-38F Algorithm 5 / Algorithm 6: KWP uses ICV2 as\n// the high 32 bits of the AIV; the low 32 bits carry the MLI in network order.\nconst AESKWP_IV = 0xa65959a6; // single u32le value\n/**\n * AES-KW, but with padding and allows random keys.\n * Uses the RFC 5649 alternative initial value; the second u32 stores the\n * 32-bit MLI in network order.\n * Wrapped ciphertext must be at least 16 bytes; malformed lengths are\n * rejected during AIV/padding checks.\n * See {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}.\n * @param kek - AES key-encryption key.\n * @returns Padded key-wrap cipher instance.\n * @example\n * Wraps a short key blob using the padded variant and a fresh key-encryption key.\n *\n * ```ts\n * import { aeskwp } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const kek = randomBytes(16);\n * const wrap = aeskwp(kek);\n * wrap.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const aeskwp = /* @__PURE__ */ wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n if (!plaintext.length)\n throw new Error('invalid plaintext length');\n const padded = Math.ceil(plaintext.length / 8) * 8;\n const out = new Uint8Array(8 + padded);\n out.set(plaintext, 8);\n const out32 = u32(out);\n out32[0] = swap8IfBE(AESKWP_IV);\n // RFC 5649 §3: the low 32 bits of the AIV carry the octet-length MLI in\n // network order, even though this buffer is addressed through LE u32s.\n out32[1] = swap8IfBE(byteSwap(plaintext.length));\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n // 16 because should have at least one block\n if (ciphertext.length < 16)\n throw new Error('invalid ciphertext length');\n // AESW.decrypt() mutates its buffer in place, so keep caller ciphertext\n // immutable across the unwrap, AIV checks, and IV scrubbing below.\n const out = copyBytes(ciphertext);\n const o32 = u32(out);\n AESW.decrypt(kek, out);\n const len = byteSwap(swap8IfBE(o32[1])) >>> 0;\n const padded = Math.ceil(len / 8) * 8;\n if (swap8IfBE(o32[0]) !== AESKWP_IV || out.length - 8 !== padded)\n throw new Error('integrity check failed');\n // RFC 5649 §3 / NIST SP 800-38F Algorithm 6: recovered padding length\n // must be in [0,7], and every recovered pad octet must be zero.\n for (let i = len; i < padded; i++)\n if (out[8 + i] !== 0)\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8, 8 + len);\n },\n}));\nclass _AesCtrDRBG {\n blockLen;\n key;\n nonce;\n state;\n reseedCnt;\n destroyed = false;\n constructor(keyLen, seed, personalization) {\n this.blockLen = ctr.blockSize;\n const keyLenBytes = keyLen / 8;\n const nonceLen = 16;\n // Store the full seedlen state as key || V so CTR_DRBG_Update-style steps\n // can rewrite the entire internal state in place.\n this.state = new Uint8Array(keyLenBytes + nonceLen);\n this.key = this.state.subarray(0, keyLenBytes);\n this.nonce = this.state.subarray(keyLenBytes, keyLenBytes + nonceLen);\n this.reseedCnt = 1;\n // Keep the stored counter one step ahead of SP 800-90A's formal V so\n // ctr(key, nonce) uses the next counter block directly.\n incBytes(this.nonce, false, 1);\n this.addEntropy(seed, personalization);\n }\n update(data) {\n // cannot re-use state here, because we will wipe current key\n ctr(this.key, this.nonce).encrypt(new Uint8Array(this.state.length), this.state);\n if (data) {\n abytes(data);\n // CTR_DRBG without a derivation function pads shorter additional_input\n // with zeros to seedlen, so XOR only the provided prefix here.\n for (let i = 0; i < data.length; i++)\n this.state[i] ^= data[i];\n }\n // Keep storing V+1 so the next ctr(key, nonce) call starts from the\n // spec's post-update counter state.\n incBytes(this.nonce, false, 1);\n }\n // Optional `info` is additional input XORed into the reseed block and is\n // limited to the internal state width.\n addEntropy(seed, info) {\n if (this.destroyed)\n throw new Error('cannot use destroyed DRBG');\n abytes(seed, this.state.length, 'seed');\n // Copy caller entropy before XORing in personalization/additional input,\n // then wipe the mixed seed material after CTR_DRBG_Update consumes it.\n const _seed = seed.slice();\n if (info) {\n abytes(info);\n if (info.length > _seed.length)\n throw new Error('info length is too big');\n for (let i = 0; i < info.length; i++)\n _seed[i] ^= info[i];\n }\n this.update(_seed);\n _seed.fill(0);\n this.reseedCnt = 1;\n }\n // Optional `info` is additional input for the pre/post-update steps; bytes\n // SP 800-90A Rev. 1 CTR_DRBG without a derivation function limits\n // additional_input to seedlen, which is exactly this internal state width.\n randomBytes(len, info) {\n if (this.destroyed)\n throw new Error('cannot use destroyed DRBG');\n anumber(len);\n // SP 800-90A Table 3 caps AES CTR_DRBG requests at 2^16 bits = 65536 bytes.\n if (len > 2 ** 16)\n throw new Error('requested output is too big');\n // The spec allows generate while reseed_counter == reseed_interval and increments afterwards.\n if (this.reseedCnt > 2 ** 48)\n throw new Error('entropy exhausted');\n if (info) {\n abytes(info);\n if (info.length > this.state.length)\n throw new Error('info length is too big');\n this.update(info);\n }\n const res = new Uint8Array(len);\n ctr(this.key, this.nonce).encrypt(res, res);\n incBytes(this.nonce, false, Math.ceil(len / this.blockLen));\n this.update(info);\n this.reseedCnt++;\n return res;\n }\n // Zeroes the current state and marks the instance destroyed. Fails closed:\n // any later randomBytes()/addEntropy() throws instead of continuing from the\n // zeroed state (which would make subsequent output the predictable zero-key stream).\n clean() {\n // `key` and `nonce` alias this backing buffer, so one fill wipes the full\n // secret state in place.\n this.state.fill(0);\n this.reseedCnt = 0;\n this.destroyed = true;\n }\n}\n// Internal helper for the exported 128-bit and 256-bit aliases; other key\n// lengths are not validated here.\nconst createAesDrbg = (keyLen) => {\n return (seed, personalization = undefined) => new _AesCtrDRBG(keyLen, seed, personalization);\n};\n/**\n * AES-CTR DRBG 128-bit - CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * @param seed - Initial 32-byte entropy input.\n * @param personalization - Optional personalization string.\n * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.\n * @example\n * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.\n *\n * ```ts\n * import { rngAesCtrDrbg128 } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const prg = rngAesCtrDrbg128(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngAesCtrDrbg128 = /* @__PURE__ */ createAesDrbg(128);\n/**\n * AES-CTR DRBG 256-bit - CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * @param seed - Initial 48-byte entropy input.\n * @param personalization - Optional personalization string.\n * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.\n * @example\n * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.\n *\n * ```ts\n * import { rngAesCtrDrbg256 } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(48);\n * const prg = rngAesCtrDrbg256(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngAesCtrDrbg256 = /* @__PURE__ */ createAesDrbg(256);\n//#region CMAC\n/**\n * Left-shift by one bit and conditionally XOR with 0x87:\n * ```\n * if MSB(L) is equal to 0\n * then K1 := L << 1;\n * else K1 := (L << 1) XOR const_Rb;\n * ```\n *\n * Specs:\n * {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3},\n * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.3 | RFC 5297 Section 2.3}\n *\n * @returns modified `block` (for chaining)\n */\nfunction dbl(block) {\n let carry = 0;\n // Left shift by 1 bit\n for (let i = BLOCK_SIZE - 1; i >= 0; i--) {\n const newCarry = (block[i] & 0x80) >>> 7;\n block[i] = (block[i] << 1) | carry;\n carry = newCarry;\n }\n // XOR with 0x87 if there was a carry from the most significant bit.\n // RFC 4493 §2.3 / RFC 5297 §2.1: 0x87 is const_Rb for doubling in the\n // CMAC/S2V finite field with primitive polynomial x^128 + x^7 + x^2 + x + 1.\n // Branchless: `carry` derives from secret CMAC subkey material.\n block[BLOCK_SIZE - 1] ^= 0x87 & -carry;\n return block;\n}\n/**\n * `a XOR b`, running in-place on `a`.\n * @param a left operand and output\n * @param b right operand\n * @returns `a` (for chaining)\n */\nfunction xorBlock(a, b) {\n if (a.length !== b.length)\n throw new Error('xorBlock: blocks must have same length');\n for (let i = 0; i < a.length; i++) {\n a[i] = a[i] ^ b[i];\n }\n return a;\n}\n/**\n * xorend as defined in\n * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.1 | RFC 5297 Section 2.1}.\n *\n * ```\n * leftmost(A, len(A)-len(B)) || (rightmost(A, len(B)) xor B)\n * ```\n *\n * Mutates `a` in place so the left prefix stays untouched and only the\n * rightmost `len(B)` bytes are xored with `b`.\n */\nfunction xorend(a, b) {\n if (b.length > a.length) {\n throw new Error('xorend: expected len(B) <= len(A)');\n }\n // keep leftmost part of `a` unchanged\n // and xor only the rightmost part:\n const offset = a.length - b.length;\n for (let i = 0; i < b.length; i++) {\n a[offset + i] = a[offset + i] ^ b[i];\n }\n return a;\n}\n/**\n * Internal CMAC class.\n */\nclass _CMAC {\n blockLen = BLOCK_SIZE;\n outputLen = BLOCK_SIZE;\n // CMAC can only decide between `K1` and `K2` once the true final block is known,\n // so updates process older blocks eagerly but keep one pending block buffered.\n buffer;\n pos;\n finished;\n destroyed;\n k1;\n k2;\n x;\n x32;\n xk;\n constructor(key) {\n abytes(key);\n validateKeyLength(key);\n this.xk = expandKeyLE(key);\n this.buffer = new Uint8Array(BLOCK_SIZE);\n this.pos = 0;\n this.finished = false;\n this.destroyed = false;\n this.x = new Uint8Array(BLOCK_SIZE);\n // Cached word view over `x`: process() runs once per 16 input bytes, so\n // it must not re-create views or re-validate per block like encryptBlock().\n this.x32 = u32(this.x);\n // L = AES_encrypt(K, const_Zero)\n const L = new Uint8Array(BLOCK_SIZE);\n encryptBlock(this.xk, L);\n // Generate subkeys K1 and K2 from the main key according to\n // {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3}\n // K1\n this.k1 = dbl(L);\n this.k2 = dbl(new Uint8Array(this.k1));\n }\n // Consumes 16 bytes of `data` starting at `pos`; `pos` avoids a per-block\n // subarray view allocation in update().\n process(data, pos) {\n // RFC 4493 §2.4 step 6 loop body: Y := X XOR M_i; X := AES-128(K, Y).\n const { x, x32, xk } = this;\n for (let i = 0; i < BLOCK_SIZE; i++)\n x[i] ^= data[pos + i];\n swap32IfBE(x32);\n const { s0, s1, s2, s3 } = encrypt(xk, x32[0], x32[1], x32[2], x32[3]);\n ((x32[0] = s0), (x32[1] = s1), (x32[2] = s2), (x32[3] = s3));\n swap32IfBE(x32);\n }\n update(data) {\n aexists(this);\n abytes(data);\n let pos = 0;\n if (this.pos) {\n const take = Math.min(BLOCK_SIZE - this.pos, data.length);\n this.buffer.set(data.subarray(0, take), this.pos);\n this.pos += take;\n pos = take;\n if (this.pos === BLOCK_SIZE && pos < data.length) {\n this.process(this.buffer, 0);\n this.pos = 0;\n }\n }\n // Keep one complete block buffered: an exact 16-byte tail may still be\n // M_n, and digestInto() must decide there whether RFC 4493 uses K1 or K2.\n while (pos + BLOCK_SIZE < data.length) {\n this.process(data, pos);\n pos += BLOCK_SIZE;\n }\n if (pos < data.length) {\n this.buffer.set(data.subarray(pos), 0);\n this.pos = data.length - pos;\n }\n return this;\n }\n // See {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.4 | RFC 4493 Section 2.4}.\n digestInto(out) {\n aexists(this);\n // `digestInto(out)` is the no-allocation fast path, so AES block re-use below\n // requires a 32-bit-aligned caller buffer instead of hidden temp copies.\n aoutput32(out, this);\n this.finished = true;\n // `digestInto()` accepts out.length >= outputLen, so only the first block stores the tag.\n const view = out.subarray(0, this.outputLen);\n let last = new Uint8Array(BLOCK_SIZE);\n if (this.pos === BLOCK_SIZE) {\n // M_last := M_n XOR K1;\n last.set(this.buffer);\n xorBlock(last, this.k1);\n }\n else {\n // M_last := padding(M_n) XOR K2;\n //\n // [...] padding(x) is the concatenation of x and a single '1',\n // followed by the minimum number of '0's, so that the total length is\n // equal to 128 bits.\n last.set(this.buffer.subarray(0, this.pos));\n last[this.pos] = 0x80; // single '1' bit\n xorBlock(last, this.k2);\n }\n view.set(this.x); // X := AES_CBC(K, M_1..M_{n-1})\n xorBlock(view, last); // Y := X XOR M_last\n encryptBlock(this.xk, view); // T := AES-128(K, Y)\n clean(last);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy out before destroy() wipes the internal digest buffer in place.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n destroy() {\n const { buffer, destroyed, x, xk, k1, k2 } = this;\n if (destroyed)\n return;\n this.destroyed = true;\n // Wipe the buffered tail, chaining value, expanded AES key, and both CMAC subkeys.\n clean(buffer, x, xk, k1, k2);\n }\n}\n/**\n * AES-CMAC (Cipher-based Message Authentication Code).\n * Specs: {@link https://www.rfc-editor.org/rfc/rfc4493.html | RFC 4493}.\n * @param msg - Message bytes to authenticate.\n * @param key - AES key bytes.\n * @returns 16-byte authentication tag. `cmac.create(...)` follows the same incremental MAC shape as\n * the other keyed helpers in this repo, including `blockLen`,\n * `outputLen`, `digestInto()` and `destroy()`.\n * @example\n * Authenticates a message with AES-CMAC and a fresh key.\n *\n * ```ts\n * import { cmac } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * cmac(new Uint8Array(), key);\n * ```\n */\n// The 16-byte probe key is only used to read static metadata; runtime CMAC\n// still accepts AES-128/192/256 keys.\nexport const cmac = /* @__PURE__ */ wrapMacConstructor(16, (key) => new _CMAC(key));\n/**\n * S2V (Synthetic Initialization Vector) function as described in\n * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.4 | RFC 5297 Section 2.4}.\n *\n * ```\n * S2V(K, S1, ..., Sn) {\n * if n = 0 then\n * return V = AES-CMAC(K, <one>)\n * fi\n * D = AES-CMAC(K, <zero>)\n * for i = 1 to n-1 do\n * D = dbl(D) xor AES-CMAC(K, Si)\n * done\n * if len(Sn) >= 128 then\n * T = Sn xorend D\n * else\n * T = dbl(D) xor pad(Sn)\n * fi\n * return V = AES-CMAC(K, T)\n * }\n * ```\n *\n * S2V takes a key and a vector of strings S1, S2, ..., Sn and returns a 128-bit string.\n * The S2V function is used to generate a synthetic IV for AES-SIV.\n *\n * @param key - AES key (128, 192, or 256 bits)\n * @param strings - Array of byte arrays to process\n * @returns 128-bit synthetic IV\n */\nfunction s2v(key, strings) {\n validateKeyLength(key);\n const len = strings.length;\n if (len > 127) {\n // RFC 5297 §7 only proves S2V secure for at most 127 components; SIV\n // spends one of those on the plaintext, leaving at most 126 AAD inputs.\n throw new Error('s2v: expected <= 127 inputs');\n }\n if (len === 0)\n return cmac(ONE_BLOCK, key);\n // D = AES-CMAC(K, <zero>)\n let d = cmac(EMPTY_BLOCK, key);\n // for i = 1 to n-1 do\n // D = dbl(D) xor AES-CMAC(K, Si)\n for (let i = 0; i < len - 1; i++) {\n dbl(d);\n const cmacResult = cmac(strings[i], key);\n xorBlock(d, cmacResult);\n clean(cmacResult);\n }\n const s_n = strings[len - 1];\n // Earlier components are validated through cmac(...); validate the final one explicitly because\n // the Uint8Array.from()/set() paths below would otherwise coerce array-like inputs silently.\n abytes(s_n);\n let t;\n // if len(Sn) >= 128 then\n if (s_n.byteLength >= BLOCK_SIZE) {\n // T = Sn xorend D\n t = xorend(Uint8Array.from(s_n), d);\n }\n else {\n // pad(Sn):\n const paddedSn = new Uint8Array(BLOCK_SIZE);\n paddedSn.set(s_n);\n paddedSn[s_n.length] = 0x80; // padding: 0x80 followed by zeros\n // T = dbl(D) xor pad(Sn)\n t = xorBlock(dbl(d), paddedSn);\n clean(paddedSn);\n }\n // V = AES-CMAC(K, T)\n const result = cmac(t, key);\n clean(d, t);\n return result;\n}\n/**\n * Use `gcmsiv` or `aessiv`.\n * @returns Never; always throws with the migration hint.\n * @throws If called; `siv()` is a removed v1 alias. {@link Error}\n * @example\n * `siv()` was removed in v2; use `gcmsiv()` for nonce-based SIV instead.\n *\n * ```ts\n * import { gcmsiv } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const nonce = randomBytes(12);\n * const cipher = gcmsiv(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const siv = () => {\n throw new Error('\"siv\" from v1 is now \"gcmsiv\"');\n};\n/**\n * **SIV**: Synthetic Initialization Vector (SIV) Authenticated Encryption\n * Nonce is derived from the plaintext and AAD using the S2V function.\n * Supports at most 126 AAD components. RFC 5297 nonce-based use is expressed by\n * passing the nonce as the final AAD component before the plaintext.\n * See {@link https://datatracker.ietf.org/doc/html/rfc5297.html | RFC 5297}.\n * @param key - 32-byte, 48-byte, or 64-byte key.\n * @param AAD - Additional authenticated data chunks (up to 126).\n * @returns AEAD cipher instance.\n * @example\n * Authenticates and encrypts plaintext with a fresh key without requiring unique nonces.\n *\n * ```ts\n * import { aessiv } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const cipher = aessiv(key);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const aessiv = /* @__PURE__ */ wrapCipher({ blockSize: 16, tagLength: 16, withAAD: true }, function aessiv(key, ...AAD) {\n // From RFC 5297: Section 6.1, 6.2, 6.3:\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 132);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 132 + 16);\n if (AAD.length > 126) {\n // RFC 5297 §2.6 / §2.7 / §7: SIV passes the plaintext as the last S2V\n // component, so callers only get 126 associated-data components.\n throw new Error('\"AAD\" expected <= 126 items');\n }\n AAD.forEach((aad) => abytes(aad));\n abytes(key);\n if (![32, 48, 64].includes(key.length))\n throw new Error('\"aes key\" expected Uint8Array of length 32/48/64, got length=' + key.length);\n // The key is split into equal halves, K1 = leftmost(K, len(K)/2) and\n // K2 = rightmost(K, len(K)/2). K1 is used for S2V and K2 is used for CTR.\n // This borrows caller key/AAD buffers by reference; mutating them after\n // construction changes future encrypt/decrypt results.\n const k1 = key.subarray(0, key.length / 2);\n const k2 = key.subarray(key.length / 2);\n return {\n // {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.6 | RFC 5297 Section 2.6}\n encrypt(plaintext) {\n PLAIN_LIMIT(plaintext.length);\n const v = s2v(k1, [...AAD, plaintext]);\n // clear out the 31st and 63rd (rightmost) bit:\n const q = Uint8Array.from(v);\n q[8] &= 0x7f;\n q[12] &= 0x7f;\n // encrypt:\n const c = ctr(k2, q).encrypt(plaintext);\n return concatBytes(v, c);\n },\n // {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.7 | RFC 5297 Section 2.7}\n decrypt(ciphertext) {\n CIPHER_LIMIT(ciphertext.length);\n const v = ciphertext.subarray(0, BLOCK_SIZE);\n const c = ciphertext.subarray(BLOCK_SIZE);\n // clear out the 31st and 63rd (rightmost) bit:\n const q = Uint8Array.from(v);\n q[8] &= 0x7f;\n q[12] &= 0x7f;\n // decrypt:\n const p = ctr(k2, q).decrypt(c);\n // verify tag:\n const t = s2v(k1, [...AAD, p]);\n if (equalBytes(t, v)) {\n return p;\n }\n else {\n clean(p);\n throw new Error('invalid siv tag');\n }\n },\n };\n});\n//#endregion\n/**\n * Unsafe low-level internal methods. May change at any time.\n * Callers are expected to use reviewed expanded-key outputs, pass mutable and\n * aligned 16-byte blocks where required, and treat several helpers as in-place\n * mutations of their input buffers or counters.\n */\nexport const unsafe = /* @__PURE__ */ Object.freeze({\n expandKeyLE,\n expandKeyDecLE,\n encrypt,\n decrypt,\n encryptBlock,\n decryptBlock,\n ctrCounter,\n ctr32,\n dbl,\n xorBlock,\n xorend,\n s2v,\n});\nexport const __TESTS = /* @__PURE__ */ Object.freeze({\n incBytes: incBytes,\n});\n",
8
+ "import type { SyncClient } from \"@absolutejs/sync/client\";\nimport type {\n SyncLocalProtectionProvider,\n SyncLocalRecordProtector,\n} from \"@absolutejs/sync/client\";\nimport { gcm } from \"@noble/ciphers/aes.js\";\nimport { randomBytes } from \"@noble/ciphers/utils.js\";\nimport * as BackgroundTask from \"expo-background-task\";\nimport * as Network from \"expo-network\";\nimport * as SecureStore from \"expo-secure-store\";\nimport * as TaskManager from \"expo-task-manager\";\nimport { AppState } from \"react-native\";\n\nexport * from \"./store\";\nexport * from \"./bridge\";\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\nconst base64 = (value: Uint8Array) => {\n let binary = \"\";\n for (const byte of value) binary += String.fromCharCode(byte);\n\n return btoa(binary);\n};\nconst unbase64 = (value: string) =>\n Uint8Array.from(atob(value), (character) => character.charCodeAt(0));\n\nexport type ExpoSyncSecureStore = {\n AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY: number;\n deleteItemAsync(\n key: string,\n options?: Record<string, unknown>,\n ): Promise<void>;\n getItemAsync(\n key: string,\n options?: Record<string, unknown>,\n ): Promise<string | null>;\n isAvailableAsync(): Promise<boolean>;\n setItemAsync(\n key: string,\n value: string,\n options?: Record<string, unknown>,\n ): Promise<void>;\n};\n\nexport type ExpoSyncProtectionOptions = {\n secureStore?: ExpoSyncSecureStore;\n storagePrefix?: string;\n};\n\nconst normalizeStoragePrefix = (value = \"absolutejs.sync\") => {\n if (!/^[A-Za-z0-9._-]{1,80}$/u.test(value))\n throw new TypeError(\n \"Expo Sync storagePrefix must use 1-80 letters, numbers, dots, underscores, or hyphens.\",\n );\n\n return value;\n};\n\nconst lockTails = new Map<string, Promise<void>>();\nconst withProcessLock = async <T>(key: string, run: () => Promise<T>) => {\n const previous = lockTails.get(key) ?? Promise.resolve();\n let release: () => void = () => undefined;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const tail = previous.then(() => current);\n lockTails.set(key, tail);\n await previous;\n try {\n return await run();\n } finally {\n release();\n if (lockTails.get(key) === tail) lockTails.delete(key);\n }\n};\n\n/** AES-256-GCM records whose data key is retained only by Expo SecureStore. */\nexport const createExpoSyncProtection = (\n options: ExpoSyncProtectionOptions = {},\n): SyncLocalProtectionProvider => {\n const storage = options.secureStore ?? SecureStore;\n const prefix = normalizeStoragePrefix(options.storagePrefix);\n const keyName = `${prefix}.data-key.v1`;\n const secureStoreOptions = {\n keychainAccessible: storage.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY,\n };\n\n return {\n prepare: async (): Promise<SyncLocalRecordProtector> => {\n if (!(await storage.isAvailableAsync()))\n throw new Error(\n \"Expo Sync data protection requires persistent SecureStore storage.\",\n );\n const key = await withProcessLock(keyName, async () => {\n const existing = await storage.getItemAsync(\n keyName,\n secureStoreOptions,\n );\n if (existing) return unbase64(existing);\n const created = randomBytes(32);\n await storage.setItemAsync(\n keyName,\n base64(created),\n secureStoreOptions,\n );\n const persisted = await storage.getItemAsync(\n keyName,\n secureStoreOptions,\n );\n if (!persisted)\n throw new Error(\"Expo Sync data-protection key was not persisted.\");\n\n return unbase64(persisted);\n });\n if (key.byteLength !== 32)\n throw new Error(\"Expo Sync data-protection key is invalid.\");\n const additionalData = (context: {\n kind: string;\n name: string;\n namespace: string;\n }) =>\n textEncoder.encode(\n `absolute-sync-v1\\u0000${context.kind}\\u0000${context.namespace}\\u0000${context.name}`,\n );\n\n return {\n id: \"aes-256-gcm-v1\",\n open: (value, context) => {\n const bytes = unbase64(value);\n if (bytes.byteLength < 13)\n throw new Error(\"Expo Sync protected record is malformed.\");\n const nonce = bytes.slice(0, 12);\n\n return textDecoder.decode(\n gcm(key, nonce, additionalData(context)).decrypt(bytes.slice(12)),\n );\n },\n seal: (value, context) => {\n const nonce = randomBytes(12);\n const encrypted = gcm(key, nonce, additionalData(context)).encrypt(\n textEncoder.encode(value),\n );\n const output = new Uint8Array(nonce.length + encrypted.length);\n output.set(nonce);\n output.set(encrypted, nonce.length);\n\n return base64(output);\n },\n };\n },\n };\n};\n\ntype Subscription = { remove(): void };\nexport type ExpoSyncLifecycleDependencies = {\n appState: {\n currentState?: string | null;\n addEventListener(\n type: \"change\",\n listener: (state: string) => void,\n ): Subscription;\n };\n network: {\n addNetworkStateListener(\n listener: (state: {\n isConnected?: boolean;\n isInternetReachable?: boolean;\n }) => void,\n ): Subscription;\n };\n};\n\nexport type ExpoSyncLifecycleOptions = {\n client: Pick<SyncClient, \"reconnect\"> & Partial<Pick<SyncClient, \"flush\">>;\n /** Finite outbox budget after a wake-up. Defaults to 10 seconds. */\n flushTimeoutMs?: number;\n onError?: (error: unknown) => void;\n dependencies?: ExpoSyncLifecycleDependencies;\n};\n\n/** Reconnect and perform a bounded flush after foreground or connectivity. */\nexport const installExpoSyncLifecycle = ({\n client,\n flushTimeoutMs = 10_000,\n onError,\n dependencies = { appState: AppState, network: Network },\n}: ExpoSyncLifecycleOptions) => {\n if (!Number.isFinite(flushTimeoutMs) || flushTimeoutMs < 0)\n throw new TypeError(\n \"Expo Sync flushTimeoutMs must be a non-negative number.\",\n );\n const wake = () => {\n client.reconnect();\n void client\n .flush?.({ timeoutMs: flushTimeoutMs })\n .catch((error) => onError?.(error));\n };\n let previous = dependencies.appState.currentState ?? undefined;\n const appState = dependencies.appState.addEventListener(\"change\", (state) => {\n if (state === \"active\" && previous !== \"active\") wake();\n previous = state;\n });\n const network = dependencies.network.addNetworkStateListener((state) => {\n if (state.isConnected && state.isInternetReachable !== false) wake();\n });\n let active = true;\n\n return () => {\n if (!active) return;\n active = false;\n appState.remove();\n network.remove();\n };\n};\n\nexport type ExpoSyncBackgroundDependencies = {\n backgroundTask: {\n Failed: number;\n Success: number;\n getStatusAsync(): Promise<number | null>;\n registerTaskAsync(\n taskName: string,\n options?: { minimumInterval?: number },\n ): Promise<void>;\n unregisterTaskAsync(taskName: string): Promise<void>;\n };\n taskManager: {\n defineTask(taskName: string, run: () => Promise<number>): void;\n isAvailableAsync(): Promise<boolean>;\n isTaskDefined(taskName: string): boolean;\n isTaskRegisteredAsync(taskName: string): Promise<boolean>;\n };\n};\n\nconst backgroundDependencies = (): ExpoSyncBackgroundDependencies => ({\n backgroundTask: {\n Failed: BackgroundTask.BackgroundTaskResult.Failed,\n Success: BackgroundTask.BackgroundTaskResult.Success,\n getStatusAsync: () => BackgroundTask.getStatusAsync(),\n registerTaskAsync: (taskName, options) =>\n BackgroundTask.registerTaskAsync(taskName, options),\n unregisterTaskAsync: (taskName) =>\n BackgroundTask.unregisterTaskAsync(taskName),\n },\n taskManager: TaskManager,\n});\n\nconst requireTaskName = (taskName: string) => {\n if (!/^[A-Za-z0-9._-]{1,120}$/u.test(taskName))\n throw new TypeError(\"Expo Sync background task name is invalid.\");\n};\n\n/** Define the task at module scope before registering it during app startup. */\nexport const defineExpoSyncBackgroundTask = (\n taskName: string,\n run: () => Promise<unknown>,\n dependencies = backgroundDependencies(),\n) => {\n requireTaskName(taskName);\n if (dependencies.taskManager.isTaskDefined(taskName)) return;\n dependencies.taskManager.defineTask(taskName, async () => {\n try {\n await run();\n\n return dependencies.backgroundTask.Success;\n } catch {\n return dependencies.backgroundTask.Failed;\n }\n });\n};\n\nexport type ExpoSyncBackgroundRegistration = {\n available: boolean;\n registered: boolean;\n status: number | null;\n};\n\nexport const registerExpoSyncBackgroundTask = async (\n taskName: string,\n options: { minimumInterval?: number } = {},\n dependencies = backgroundDependencies(),\n): Promise<ExpoSyncBackgroundRegistration> => {\n requireTaskName(taskName);\n if (\n options.minimumInterval !== undefined &&\n (!Number.isFinite(options.minimumInterval) || options.minimumInterval < 15)\n )\n throw new TypeError(\n \"Expo Sync background minimumInterval must be at least 15 minutes.\",\n );\n const available = await dependencies.taskManager.isAvailableAsync();\n const status = await dependencies.backgroundTask.getStatusAsync();\n if (!available)\n return {\n available: false,\n registered: false,\n status,\n };\n if (!dependencies.taskManager.isTaskDefined(taskName))\n throw new Error(\n \"Expo Sync background task must be defined at module scope before registration.\",\n );\n if (!(await dependencies.taskManager.isTaskRegisteredAsync(taskName)))\n await dependencies.backgroundTask.registerTaskAsync(taskName, options);\n\n return {\n available: true,\n registered: true,\n status,\n };\n};\n\nexport const unregisterExpoSyncBackgroundTask = async (\n taskName: string,\n dependencies = backgroundDependencies(),\n) => {\n requireTaskName(taskName);\n if (await dependencies.taskManager.isTaskRegisteredAsync(taskName))\n await dependencies.backgroundTask.unregisterTaskAsync(taskName);\n};\n",
9
+ "import type {\n LocalCollectionRecord,\n LocalMutationRecord,\n SyncLocalStore,\n SyncLocalStoreMode,\n SyncLocalStoreSchemaInput,\n SyncLocalStoreSchemaStatus,\n SyncLocalProtectionProvider,\n SyncLocalRecordProtector,\n SyncLocalTransaction,\n} from \"@absolutejs/sync/client\";\nimport {\n createSyncLocalSchemaStatus,\n migrateSyncLocalCollectionRecord,\n migrateSyncLocalMutationRecord,\n resolveSyncLocalDataPolicy,\n resolveSyncLocalSchemaComponents,\n runSyncLocalPolicyTransaction,\n} from \"@absolutejs/sync/client\";\nimport * as SQLite from \"expo-sqlite\";\n\nexport type ExpoSyncSqliteExecutor = {\n execAsync(source: string): Promise<void>;\n getAllAsync<T>(\n source: string,\n params?: readonly (boolean | number | null | string | Uint8Array)[],\n ): Promise<T[]>;\n getFirstAsync<T>(\n source: string,\n params?: readonly (boolean | number | null | string | Uint8Array)[],\n ): Promise<T | null>;\n runAsync(\n source: string,\n params?: readonly (boolean | number | null | string | Uint8Array)[],\n ): Promise<unknown>;\n};\n\nexport type ExpoSyncSqliteDatabase = ExpoSyncSqliteExecutor & {\n withExclusiveTransactionAsync(\n run: (transaction: ExpoSyncSqliteExecutor) => Promise<void>,\n ): Promise<void>;\n};\n\nexport type ExpoSyncSqliteFactory = () =>\n | ExpoSyncSqliteDatabase\n | Promise<ExpoSyncSqliteDatabase>;\n\nexport type ExpoSyncLocalStoreOptions = {\n /** Defaults to `absolutejs-sync-local-v1.db`. */\n databaseName?: string;\n /** Injection seam for conformance tests and custom database provisioning. */\n database?: ExpoSyncSqliteFactory;\n /** Same generated logical migration plan used by web and Capacitor. */\n storageSchema?: SyncLocalStoreSchemaInput;\n protection?: SyncLocalProtectionProvider;\n now?: () => number;\n};\n\nconst SCHEMA = [\n `CREATE TABLE IF NOT EXISTS absolute_sync_schema (\n singleton_id INTEGER PRIMARY KEY NOT NULL CHECK (singleton_id = 1),\n logical_version INTEGER NOT NULL\n)`,\n `CREATE TABLE IF NOT EXISTS absolute_sync_schema_components (\n component_id TEXT PRIMARY KEY NOT NULL,\n logical_version INTEGER NOT NULL\n)`,\n `CREATE TABLE IF NOT EXISTS absolute_sync_metadata (\n namespace TEXT PRIMARY KEY NOT NULL,\n installation_id TEXT NOT NULL\n)`,\n `CREATE TABLE IF NOT EXISTS absolute_sync_collections (\n namespace TEXT NOT NULL,\n collection_key TEXT NOT NULL,\n record_json TEXT NOT NULL,\n PRIMARY KEY (namespace, collection_key)\n)`,\n `CREATE TABLE IF NOT EXISTS absolute_sync_mutations (\n namespace TEXT NOT NULL,\n operation_id TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n record_json TEXT NOT NULL,\n PRIMARY KEY (namespace, operation_id)\n)`,\n `CREATE INDEX IF NOT EXISTS absolute_sync_mutations_order\n ON absolute_sync_mutations (namespace, created_at, operation_id)`,\n] as const;\n\ntype SqliteValue = boolean | number | null | string | Uint8Array;\ntype SqliteRow = Record<string, unknown>;\n\nconst executor = (\n value: Pick<\n SQLite.SQLiteDatabase,\n \"execAsync\" | \"getAllAsync\" | \"getFirstAsync\" | \"runAsync\"\n >,\n): ExpoSyncSqliteExecutor => ({\n execAsync: (source) => value.execAsync(source),\n getAllAsync: (source, params = []) =>\n value.getAllAsync(source, [...params] as SQLite.SQLiteBindParams),\n getFirstAsync: (source, params = []) =>\n value.getFirstAsync(source, [...params] as SQLite.SQLiteBindParams),\n runAsync: (source, params = []) =>\n value.runAsync(source, [...params] as SQLite.SQLiteBindParams),\n});\n\nconst defaultDatabase = async (\n databaseName: string,\n): Promise<ExpoSyncSqliteDatabase> => {\n const database = await SQLite.openDatabaseAsync(databaseName);\n const direct = executor(database);\n\n return {\n ...direct,\n withExclusiveTransactionAsync: (run) =>\n database.withExclusiveTransactionAsync((transaction) =>\n run(executor(transaction)),\n ),\n };\n};\n\ntype ProtectedRecordEnvelope = {\n __absoluteSyncProtected: {\n name: string;\n protector: string;\n value: string;\n };\n};\n\nconst parseRecord = <T>(\n value: unknown,\n label: string,\n context?: { kind: \"collection\" | \"mutation\"; namespace: string },\n protector?: SyncLocalRecordProtector,\n): T | undefined => {\n if (value === undefined || value === null) return undefined;\n if (typeof value !== \"string\")\n throw new Error(`Expo Sync SQLite returned invalid ${label} JSON.`);\n try {\n const parsed: unknown = JSON.parse(value);\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n \"__absoluteSyncProtected\" in parsed\n ) {\n const envelope = (parsed as ProtectedRecordEnvelope)\n .__absoluteSyncProtected;\n if (!context || !protector || protector.id !== envelope.protector)\n throw new Error(\n `Expo Sync ${label} requires unavailable protection provider \"${envelope.protector}\".`,\n );\n return JSON.parse(\n protector.open(envelope.value, {\n ...context,\n name: envelope.name,\n }),\n ) as T;\n }\n\n return parsed as T;\n } catch (cause) {\n throw new Error(`Expo Sync SQLite could not parse ${label} JSON.`, {\n cause,\n });\n }\n};\n\nconst serializeRecord = (\n value: LocalCollectionRecord | LocalMutationRecord,\n context: {\n kind: \"collection\" | \"mutation\";\n name: string;\n namespace: string;\n },\n protector?: SyncLocalRecordProtector,\n) =>\n protector\n ? JSON.stringify({\n __absoluteSyncProtected: {\n name: context.name,\n protector: protector.id,\n value: protector.seal(JSON.stringify(value), context),\n },\n } satisfies ProtectedRecordEnvelope)\n : JSON.stringify(value);\n\nconst requireNamespace = (namespace: string) => {\n if (namespace.length === 0)\n throw new TypeError(\"Sync local-store namespace must not be empty.\");\n};\n\nconst rowString = (\n row: SqliteRow | null | undefined,\n field: string,\n): string | undefined => {\n const value = row?.[field];\n\n return typeof value === \"string\" ? value : undefined;\n};\n\nconst prepareSchema = async (\n database: ExpoSyncSqliteDatabase,\n storageSchema: SyncLocalStoreSchemaInput,\n protector: SyncLocalRecordProtector | undefined,\n): Promise<SyncLocalStoreSchemaStatus> => {\n let status: SyncLocalStoreSchemaStatus | undefined;\n await database.withExclusiveTransactionAsync(async (transaction) => {\n const legacy = await transaction.getFirstAsync<SqliteRow>(\n \"SELECT logical_version FROM absolute_sync_schema WHERE singleton_id = 1 LIMIT 1\",\n );\n const componentRows = await transaction.getAllAsync<SqliteRow>(\n \"SELECT component_id, logical_version FROM absolute_sync_schema_components ORDER BY component_id\",\n );\n const storedVersions: Record<string, number> = {};\n for (const row of componentRows) {\n if (\n typeof row.component_id !== \"string\" ||\n typeof row.logical_version !== \"number\"\n )\n throw new Error(\n \"Expo Sync SQLite returned an invalid schema component ledger.\",\n );\n storedVersions[row.component_id] = row.logical_version;\n }\n if (\n storedVersions[\"@absolutejs/app\"] === undefined &&\n typeof legacy?.logical_version === \"number\"\n )\n storedVersions[\"@absolutejs/app\"] = legacy.logical_version;\n const resolved = resolveSyncLocalSchemaComponents(\n storedVersions,\n storageSchema,\n );\n const steps = resolved.components.flatMap((component) => component.steps);\n if (steps.length > 0) {\n const collections = await transaction.getAllAsync<SqliteRow>(\n \"SELECT namespace, collection_key, record_json FROM absolute_sync_collections ORDER BY namespace, collection_key\",\n );\n for (const row of collections) {\n const namespace = row.namespace;\n const key = row.collection_key;\n if (typeof namespace !== \"string\" || typeof key !== \"string\")\n throw new Error(\n \"Expo Sync SQLite returned an invalid collection identity.\",\n );\n const record = parseRecord<LocalCollectionRecord>(\n row.record_json,\n \"collection\",\n { kind: \"collection\", namespace },\n protector,\n );\n if (!record)\n throw new Error(\n \"Expo Sync SQLite returned a missing collection record.\",\n );\n const migrated = migrateSyncLocalCollectionRecord(\n record,\n { key, namespace },\n steps,\n );\n if (migrated === null)\n await transaction.runAsync(\n \"DELETE FROM absolute_sync_collections WHERE namespace = ? AND collection_key = ?\",\n [namespace, key],\n );\n else\n await transaction.runAsync(\n \"UPDATE absolute_sync_collections SET record_json = ? WHERE namespace = ? AND collection_key = ?\",\n [\n serializeRecord(\n migrated,\n {\n kind: \"collection\",\n name: migrated.collection ?? key,\n namespace,\n },\n protector,\n ),\n namespace,\n key,\n ],\n );\n }\n const mutations = await transaction.getAllAsync<SqliteRow>(\n \"SELECT namespace, operation_id, record_json FROM absolute_sync_mutations ORDER BY namespace, operation_id\",\n );\n for (const row of mutations) {\n const namespace = row.namespace;\n const operationId = row.operation_id;\n if (typeof namespace !== \"string\" || typeof operationId !== \"string\")\n throw new Error(\n \"Expo Sync SQLite returned an invalid mutation identity.\",\n );\n const record = parseRecord<LocalMutationRecord>(\n row.record_json,\n \"mutation\",\n { kind: \"mutation\", namespace },\n protector,\n );\n if (!record)\n throw new Error(\n \"Expo Sync SQLite returned a missing mutation record.\",\n );\n const migrated = migrateSyncLocalMutationRecord(\n record,\n { key: operationId, namespace },\n steps,\n );\n if (migrated === null)\n await transaction.runAsync(\n \"DELETE FROM absolute_sync_mutations WHERE namespace = ? AND operation_id = ?\",\n [namespace, operationId],\n );\n else\n await transaction.runAsync(\n \"UPDATE absolute_sync_mutations SET created_at = ?, record_json = ? WHERE namespace = ? AND operation_id = ?\",\n [\n migrated.createdAt,\n serializeRecord(\n migrated,\n {\n kind: \"mutation\",\n name: migrated.name,\n namespace,\n },\n protector,\n ),\n namespace,\n operationId,\n ],\n );\n }\n }\n for (const component of resolved.components)\n await transaction.runAsync(\n \"INSERT INTO absolute_sync_schema_components (component_id, logical_version) VALUES (?, ?) ON CONFLICT(component_id) DO UPDATE SET logical_version = excluded.logical_version\",\n [component.id, component.targetVersion],\n );\n const app = resolved.components.find(\n (component) => component.id === \"@absolutejs/app\",\n );\n if (app)\n await transaction.runAsync(\n \"INSERT INTO absolute_sync_schema (singleton_id, logical_version) VALUES (1, ?) ON CONFLICT(singleton_id) DO UPDATE SET logical_version = excluded.logical_version\",\n [app.targetVersion],\n );\n status = createSyncLocalSchemaStatus(\n resolved.components,\n resolved.orphanedComponents,\n \"components\" in storageSchema,\n );\n });\n if (!status) throw new Error(\"Expo Sync schema transaction did not run.\");\n\n return status;\n};\n\n/**\n * Expo SQLite implementation of Sync's principal-partitioned atomic cache and\n * mutation outbox. Every operation is serialized around an exclusive native\n * transaction so concurrent native routes, WebViews, and background work\n * cannot observe partial state.\n */\nexport const createExpoSyncLocalStore = ({\n databaseName = \"absolutejs-sync-local-v1.db\",\n database: createDatabase = () => defaultDatabase(databaseName),\n storageSchema = { version: 1 },\n protection,\n now = Date.now,\n}: ExpoSyncLocalStoreOptions = {}): SyncLocalStore => {\n if (!/^[A-Za-z0-9._-]{1,120}$/u.test(databaseName))\n throw new TypeError(\"Expo Sync databaseName is invalid.\");\n const localData = resolveSyncLocalDataPolicy(storageSchema);\n let protectorPromise: Promise<SyncLocalRecordProtector> | undefined;\n const prepareProtector = () => (protectorPromise ??= protection?.prepare());\n let schemaStatus: SyncLocalStoreSchemaStatus | undefined;\n let databasePromise: Promise<ExpoSyncSqliteDatabase> | undefined;\n const database = () => {\n databasePromise ??= Promise.all([\n Promise.resolve(createDatabase()),\n prepareProtector(),\n ]).then(async ([value, protector]) => {\n await value.execAsync(\"PRAGMA journal_mode = WAL\");\n for (const statement of SCHEMA) await value.execAsync(statement);\n schemaStatus = await prepareSchema(value, storageSchema, protector);\n\n return value;\n });\n\n return databasePromise;\n };\n let tail = Promise.resolve();\n const locked = async <T>(run: () => Promise<T>): Promise<T> => {\n let release: () => void = () => undefined;\n const previous = tail;\n tail = new Promise<void>((resolve) => {\n release = resolve;\n });\n await previous;\n try {\n return await run();\n } finally {\n release();\n }\n };\n\n const transaction = async <T>(\n namespace: string,\n mode: SyncLocalStoreMode,\n run: (transaction: SyncLocalTransaction) => Promise<T>,\n ): Promise<T> => {\n requireNamespace(namespace);\n\n return locked(async () => {\n const value = await database();\n const protector = await prepareProtector();\n let result: T | undefined;\n let completed = false;\n await value.withExclusiveTransactionAsync(async (sqlite) => {\n const writable = () => {\n if (mode !== \"readwrite\")\n throw new Error(\n \"Cannot write in a readonly Sync local transaction\",\n );\n };\n const raw: SyncLocalTransaction = {\n deleteCollection: async (key) => {\n writable();\n await sqlite.runAsync(\n \"DELETE FROM absolute_sync_collections WHERE namespace = ? AND collection_key = ?\",\n [namespace, key],\n );\n },\n deleteMutation: async (operationId) => {\n writable();\n await sqlite.runAsync(\n \"DELETE FROM absolute_sync_mutations WHERE namespace = ? AND operation_id = ?\",\n [namespace, operationId],\n );\n },\n getCollection: async <R>(key: string) => {\n const row = await sqlite.getFirstAsync<SqliteRow>(\n \"SELECT record_json FROM absolute_sync_collections WHERE namespace = ? AND collection_key = ? LIMIT 1\",\n [namespace, key],\n );\n\n return parseRecord<LocalCollectionRecord<R>>(\n row?.record_json,\n \"collection\",\n { kind: \"collection\", namespace },\n protector,\n );\n },\n getInstallationId: async () => {\n const row = await sqlite.getFirstAsync<SqliteRow>(\n \"SELECT installation_id FROM absolute_sync_metadata WHERE namespace = ? LIMIT 1\",\n [namespace],\n );\n\n return rowString(row, \"installation_id\");\n },\n getMutation: async (operationId) => {\n const row = await sqlite.getFirstAsync<SqliteRow>(\n \"SELECT record_json FROM absolute_sync_mutations WHERE namespace = ? AND operation_id = ? LIMIT 1\",\n [namespace, operationId],\n );\n\n return parseRecord<LocalMutationRecord>(\n row?.record_json,\n \"mutation\",\n { kind: \"mutation\", namespace },\n protector,\n );\n },\n listCollections: async () => {\n const rows = await sqlite.getAllAsync<SqliteRow>(\n \"SELECT collection_key, record_json FROM absolute_sync_collections WHERE namespace = ? ORDER BY collection_key ASC\",\n [namespace],\n );\n\n return rows\n .map((row) => {\n const key = row.collection_key;\n const record = parseRecord<LocalCollectionRecord>(\n row.record_json,\n \"collection\",\n { kind: \"collection\", namespace },\n protector,\n );\n\n return typeof key === \"string\" && record\n ? { key, record }\n : undefined;\n })\n .filter(\n (\n entry,\n ): entry is {\n key: string;\n record: LocalCollectionRecord;\n } => entry !== undefined,\n );\n },\n listMutations: async () => {\n const rows = await sqlite.getAllAsync<SqliteRow>(\n \"SELECT record_json FROM absolute_sync_mutations WHERE namespace = ? ORDER BY created_at ASC, operation_id ASC\",\n [namespace],\n );\n\n return rows\n .map((row) =>\n parseRecord<LocalMutationRecord>(\n row.record_json,\n \"mutation\",\n { kind: \"mutation\", namespace },\n protector,\n ),\n )\n .filter(\n (record): record is LocalMutationRecord => record !== undefined,\n );\n },\n putCollection: async (key, record) => {\n writable();\n await sqlite.runAsync(\n \"INSERT INTO absolute_sync_collections (namespace, collection_key, record_json) VALUES (?, ?, ?) ON CONFLICT(namespace, collection_key) DO UPDATE SET record_json = excluded.record_json\",\n [\n namespace,\n key,\n serializeRecord(\n record,\n {\n kind: \"collection\",\n name: record.collection ?? key,\n namespace,\n },\n protector,\n ),\n ],\n );\n },\n putMutation: async (record) => {\n writable();\n await sqlite.runAsync(\n \"INSERT INTO absolute_sync_mutations (namespace, operation_id, created_at, record_json) VALUES (?, ?, ?, ?) ON CONFLICT(namespace, operation_id) DO UPDATE SET created_at = excluded.created_at, record_json = excluded.record_json\",\n [\n namespace,\n record.operationId,\n record.createdAt,\n serializeRecord(\n record,\n {\n kind: \"mutation\",\n name: record.name,\n namespace,\n },\n protector,\n ),\n ],\n );\n },\n setInstallationId: async (installationId) => {\n writable();\n if (installationId.length === 0)\n throw new TypeError(\"Sync installation id must not be empty.\");\n await sqlite.runAsync(\n \"INSERT INTO absolute_sync_metadata (namespace, installation_id) VALUES (?, ?) ON CONFLICT(namespace) DO UPDATE SET installation_id = excluded.installation_id\",\n [namespace, installationId],\n );\n },\n };\n result = await runSyncLocalPolicyTransaction({\n mode,\n now: now(),\n policy: localData,\n protected: protector !== undefined,\n raw,\n run,\n });\n completed = true;\n });\n if (!completed)\n throw new Error(\"Expo Sync transaction did not complete.\");\n\n return result as T;\n });\n };\n\n return {\n deleteNamespace: async (namespace) => {\n requireNamespace(namespace);\n await locked(async () => {\n const value = await database();\n await value.withExclusiveTransactionAsync(async (sqlite) => {\n for (const table of [\n \"absolute_sync_metadata\",\n \"absolute_sync_collections\",\n \"absolute_sync_mutations\",\n ])\n await sqlite.runAsync(`DELETE FROM ${table} WHERE namespace = ?`, [\n namespace,\n ]);\n });\n });\n },\n getSchemaStatus: async () => {\n await database();\n if (!schemaStatus) throw new Error(\"Expo Sync schema was not prepared.\");\n\n return { ...schemaStatus };\n },\n transaction,\n };\n};\n",
10
+ "import type {\n LocalCollectionRecord,\n LocalMutationRecord,\n SyncLocalStore,\n SyncLocalStoreMode,\n SyncLocalTransaction,\n} from \"@absolutejs/sync/client\";\n\nexport type ExpoSyncBridgeHostOptions = {\n store: SyncLocalStore;\n namespace: string;\n /** Maximum time one WebView may hold an atomic transaction. Defaults to 8s. */\n transactionTimeoutMs?: number;\n createId?: () => string;\n};\n\nexport type ExpoSyncSocketBridgeEvent = {\n socketId: string;\n type: \"close\" | \"error\" | \"message-chunk\" | \"open\";\n code?: number;\n data?: string;\n index?: number;\n messageId?: string;\n reason?: string;\n total?: number;\n};\n\nexport type ExpoSyncSocketBridgeHostOptions = {\n allowedOrigin: string;\n socketTicket: (audience?: string) => Promise<string>;\n emit(event: ExpoSyncSocketBridgeEvent): void;\n webSocketImpl?: typeof WebSocket;\n maxSockets?: number;\n /** Maximum encoded Sync frame size. Defaults to 4 MiB. */\n maxFrameBytes?: number;\n};\n\ntype TransactionSession = {\n complete: Promise<void>;\n finish(commit: boolean): void;\n timer: ReturnType<typeof setTimeout>;\n transaction: SyncLocalTransaction;\n};\n\nconst requireRecord = (value: unknown, label: string) => {\n if (typeof value !== \"object\" || value === null || Array.isArray(value))\n throw new TypeError(`Expo Sync bridge ${label} is invalid.`);\n\n return value as Record<string, unknown>;\n};\n\nconst requireString = (value: unknown, label: string) => {\n if (typeof value !== \"string\" || value.length === 0 || value.length > 512)\n throw new TypeError(`Expo Sync bridge ${label} is invalid.`);\n\n return value;\n};\n\nconst requireCollectionRecord = (value: unknown): LocalCollectionRecord => {\n const record = requireRecord(value, \"collection record\");\n if (\n !Array.isArray(record.rows) ||\n typeof record.version !== \"number\" ||\n !Number.isSafeInteger(record.version) ||\n record.version < 0\n )\n throw new TypeError(\"Expo Sync bridge collection record is invalid.\");\n\n return structuredClone(record) as LocalCollectionRecord;\n};\n\nconst requireMutationRecord = (value: unknown): LocalMutationRecord => {\n const record = requireRecord(value, \"mutation record\");\n if (\n typeof record.operationId !== \"string\" ||\n record.operationId.length === 0 ||\n record.operationId.length > 512 ||\n typeof record.name !== \"string\" ||\n record.name.length === 0 ||\n record.name.length > 512 ||\n typeof record.createdAt !== \"number\" ||\n !Number.isFinite(record.createdAt) ||\n typeof record.attempts !== \"number\" ||\n !Number.isSafeInteger(record.attempts) ||\n record.attempts < 0 ||\n !Array.isArray(record.optimistic) ||\n !Array.isArray(record.inverse)\n )\n throw new TypeError(\"Expo Sync bridge mutation record is invalid.\");\n\n return structuredClone(record) as LocalMutationRecord;\n};\n\nconst rollbackMarker = Symbol(\"expo-sync-bridge-rollback\");\n\n/**\n * Native owner for WebView local-store transactions. It exposes only Sync's\n * typed persistence contract and never accepts a namespace from page code.\n */\nexport const createExpoSyncBridgeHost = ({\n store,\n namespace,\n transactionTimeoutMs = 8_000,\n createId = () => crypto.randomUUID(),\n}: ExpoSyncBridgeHostOptions) => {\n if (!namespace || namespace.length > 512)\n throw new TypeError(\"Expo Sync bridge namespace is invalid.\");\n if (\n !Number.isSafeInteger(transactionTimeoutMs) ||\n transactionTimeoutMs < 100 ||\n transactionTimeoutMs > 30_000\n )\n throw new TypeError(\n \"Expo Sync bridge transactionTimeoutMs must be between 100 and 30000.\",\n );\n const sessions = new Map<string, TransactionSession>();\n\n const begin = async (mode: SyncLocalStoreMode) => {\n if (sessions.size >= 8)\n throw new Error(\"Expo Sync bridge has too many open transactions.\");\n const id = createId();\n if (!/^[A-Za-z0-9._:-]{1,160}$/u.test(id) || sessions.has(id))\n throw new Error(\"Expo Sync bridge generated an invalid transaction id.\");\n let readyResolve: (transaction: SyncLocalTransaction) => void = () =>\n undefined;\n let readyReject: (error: unknown) => void = () => undefined;\n const ready = new Promise<SyncLocalTransaction>((resolve, reject) => {\n readyResolve = resolve;\n readyReject = reject;\n });\n let finish: (commit: boolean) => void = () => undefined;\n const decision = new Promise<boolean>((resolve) => {\n finish = resolve;\n });\n const complete = store\n .transaction(namespace, mode, async (transaction) => {\n readyResolve(transaction);\n if (!(await decision)) throw rollbackMarker;\n })\n .catch((error) => {\n readyReject(error);\n if (error !== rollbackMarker) throw error;\n });\n const transaction = await ready;\n const timer = setTimeout(() => {\n sessions.delete(id);\n finish(false);\n }, transactionTimeoutMs);\n sessions.set(id, { complete, finish, timer, transaction });\n\n return id;\n };\n\n const session = (params: Record<string, unknown>) => {\n const id = requireString(params.transactionId, \"transaction id\");\n const value = sessions.get(id);\n if (!value)\n throw new Error(\"Expo Sync bridge transaction is closed or unknown.\");\n\n return { id, value };\n };\n\n const end = async (params: Record<string, unknown>) => {\n const { id, value } = session(params);\n if (typeof params.commit !== \"boolean\")\n throw new TypeError(\"Expo Sync bridge commit decision is invalid.\");\n sessions.delete(id);\n clearTimeout(value.timer);\n value.finish(params.commit);\n await value.complete;\n\n return null;\n };\n\n const operation = async (\n method: string,\n params: Record<string, unknown>,\n ): Promise<unknown> => {\n const { value } = session(params);\n const transaction = value.transaction;\n if (method === \"sync.tx.getInstallationId\")\n return (await transaction.getInstallationId()) ?? null;\n if (method === \"sync.tx.setInstallationId\") {\n await transaction.setInstallationId(\n requireString(params.installationId, \"installation id\"),\n );\n\n return null;\n }\n if (method === \"sync.tx.getCollection\")\n return (\n (await transaction.getCollection(\n requireString(params.key, \"collection key\"),\n )) ?? null\n );\n if (method === \"sync.tx.listCollections\")\n return transaction.listCollections();\n if (method === \"sync.tx.putCollection\") {\n await transaction.putCollection(\n requireString(params.key, \"collection key\"),\n requireCollectionRecord(params.record),\n );\n\n return null;\n }\n if (method === \"sync.tx.deleteCollection\") {\n await transaction.deleteCollection(\n requireString(params.key, \"collection key\"),\n );\n\n return null;\n }\n if (method === \"sync.tx.listMutations\") return transaction.listMutations();\n if (method === \"sync.tx.getMutation\")\n return (\n (await transaction.getMutation(\n requireString(params.operationId, \"operation id\"),\n )) ?? null\n );\n if (method === \"sync.tx.putMutation\") {\n await transaction.putMutation(requireMutationRecord(params.record));\n\n return null;\n }\n if (method === \"sync.tx.deleteMutation\") {\n await transaction.deleteMutation(\n requireString(params.operationId, \"operation id\"),\n );\n\n return null;\n }\n if (method === \"sync.tx.resolveMutationPolicy\")\n return (\n transaction.resolveMutationPolicy?.(\n requireString(params.name, \"mutation name\"),\n ) ?? null\n );\n throw new Error(\"Expo Sync bridge transaction method is not allowed.\");\n };\n\n return {\n close: async () => {\n const active = [...sessions.values()];\n sessions.clear();\n for (const value of active) {\n clearTimeout(value.timer);\n value.finish(false);\n }\n await Promise.allSettled(active.map((value) => value.complete));\n },\n request: async (method: string, rawParams: unknown): Promise<unknown> => {\n const params = requireRecord(rawParams, \"params\");\n if (method === \"sync.store.begin\") {\n if (params.mode !== \"readonly\" && params.mode !== \"readwrite\")\n throw new TypeError(\"Expo Sync bridge transaction mode is invalid.\");\n\n return { transactionId: await begin(params.mode) };\n }\n if (method === \"sync.store.end\") return end(params);\n if (method === \"sync.store.schema\")\n return (await store.getSchemaStatus?.()) ?? null;\n if (method === \"sync.store.deleteNamespace\") {\n await store.deleteNamespace?.(namespace);\n\n return null;\n }\n if (method.startsWith(\"sync.tx.\")) return operation(method, params);\n throw new Error(\"Expo Sync bridge method is not allowed.\");\n },\n };\n};\n\nconst websocketOrigin = (url: URL) => {\n const protocol = url.protocol === \"wss:\" ? \"https:\" : \"http:\";\n\n return `${protocol}//${url.host}`;\n};\n\nconst ticketSocketUrl = (url: URL) => {\n if (url.searchParams.has(\"__absolute_auth\"))\n throw new TypeError(\n \"Expo Sync socket URL contains reserved authentication.\",\n );\n url.searchParams.set(\"__absolute_auth\", \"ticket\");\n\n return url.href;\n};\n\nconst SOCKET_CHUNK_BYTES = 24 * 1024;\nconst SOCKET_UPLOAD_TIMEOUT_MS = 10_000;\nconst encodeBase64 = (value: Uint8Array) => {\n let binary = \"\";\n for (const byte of value) binary += String.fromCharCode(byte);\n\n return btoa(binary);\n};\nconst decodeBase64 = (value: string) => {\n if (\n value.length === 0 ||\n value.length > Math.ceil(SOCKET_CHUNK_BYTES / 3) * 4 + 4 ||\n !/^[A-Za-z0-9+/]+={0,2}$/u.test(value)\n )\n throw new TypeError(\"Expo Sync socket chunk is invalid.\");\n\n return Uint8Array.from(atob(value), (character) => character.charCodeAt(0));\n};\n\n/**\n * Owns authenticated sockets in native JavaScript. Only ordinary string Sync\n * frames cross the WebView bridge; the single-use ticket is consumed here.\n */\nexport const createExpoSyncSocketBridgeHost = ({\n allowedOrigin,\n socketTicket,\n emit,\n webSocketImpl = globalThis.WebSocket,\n maxSockets = 4,\n maxFrameBytes = 4 * 1024 * 1024,\n}: ExpoSyncSocketBridgeHostOptions) => {\n const origin = new URL(allowedOrigin);\n if (\n origin.protocol !== \"https:\" ||\n origin.username ||\n origin.password ||\n origin.pathname !== \"/\" ||\n origin.search ||\n origin.hash\n )\n throw new TypeError(\n \"Expo Sync socket allowedOrigin must be an HTTPS origin.\",\n );\n if (!webSocketImpl)\n throw new Error(\"Expo Sync socket bridge requires WebSocket support.\");\n if (!Number.isSafeInteger(maxSockets) || maxSockets < 1 || maxSockets > 16)\n throw new TypeError(\"Expo Sync maxSockets must be between 1 and 16.\");\n if (\n !Number.isSafeInteger(maxFrameBytes) ||\n maxFrameBytes < SOCKET_CHUNK_BYTES ||\n maxFrameBytes > 16 * 1024 * 1024\n )\n throw new TypeError(\n \"Expo Sync maxFrameBytes must be between 24 KiB and 16 MiB.\",\n );\n const sockets = new Map<string, WebSocket>();\n const uploads = new Map<\n string,\n {\n chunks: Array<Uint8Array | undefined>;\n timer: ReturnType<typeof setTimeout>;\n }\n >();\n let messageSequence = 0;\n const socketId = (value: unknown) => {\n const id = requireString(value, \"socket id\");\n if (!/^[A-Za-z0-9._:-]{1,160}$/u.test(id))\n throw new TypeError(\"Expo Sync bridge socket id is invalid.\");\n\n return id;\n };\n const close = (id: string, code?: number, reason?: string) => {\n const socket = sockets.get(id);\n if (!socket) return;\n sockets.delete(id);\n for (const [key, upload] of uploads)\n if (key.startsWith(`${id}:\\u0000`)) {\n clearTimeout(upload.timer);\n uploads.delete(key);\n }\n socket.close(code, reason);\n };\n const emitMessage = (id: string, data: string) => {\n const bytes = new TextEncoder().encode(data);\n if (bytes.byteLength > maxFrameBytes) {\n emit({ socketId: id, type: \"error\" });\n close(id, 1009, \"Sync frame is too large\");\n\n return;\n }\n const total = Math.max(1, Math.ceil(bytes.byteLength / SOCKET_CHUNK_BYTES));\n const messageId = `native_${(messageSequence += 1).toString(36)}`;\n for (let index = 0; index < total; index += 1)\n emit({\n data: encodeBase64(\n bytes.slice(\n index * SOCKET_CHUNK_BYTES,\n Math.min(bytes.byteLength, (index + 1) * SOCKET_CHUNK_BYTES),\n ),\n ),\n index,\n messageId,\n socketId: id,\n total,\n type: \"message-chunk\",\n });\n };\n\n return {\n close: () => {\n for (const id of [...sockets.keys()]) close(id, 1000, \"Host closed\");\n },\n request: async (method: string, rawParams: unknown): Promise<unknown> => {\n const params = requireRecord(rawParams, \"socket params\");\n const id = socketId(params.socketId);\n if (method === \"sync.socket.open\") {\n if (sockets.has(id))\n throw new Error(\"Expo Sync bridge socket id is already open.\");\n if (sockets.size >= maxSockets)\n throw new Error(\"Expo Sync bridge socket limit exceeded.\");\n const url = new URL(requireString(params.url, \"socket URL\"));\n if (\n url.protocol !== \"wss:\" ||\n url.username ||\n url.password ||\n websocketOrigin(url) !== origin.origin\n )\n throw new Error(\n \"Expo Sync socket must use WSS on the configured production origin.\",\n );\n const socket = new webSocketImpl(ticketSocketUrl(url));\n sockets.set(id, socket);\n socket.onopen = () => {\n void socketTicket(origin.origin)\n .then((ticket) => {\n if (sockets.get(id) !== socket) return;\n socket.send(JSON.stringify({ ticket, type: \"authenticate\" }));\n emit({ socketId: id, type: \"open\" });\n })\n .catch(() => {\n if (sockets.get(id) !== socket) return;\n emit({ socketId: id, type: \"error\" });\n close(id, 1008, \"Authentication failed\");\n });\n };\n socket.onmessage = (event) => {\n if (sockets.get(id) !== socket) return;\n if (typeof event.data !== \"string\") {\n emit({ socketId: id, type: \"error\" });\n close(id, 1003, \"Binary frames are not supported\");\n\n return;\n }\n emitMessage(id, event.data);\n };\n socket.onerror = () => {\n if (sockets.get(id) === socket) emit({ socketId: id, type: \"error\" });\n };\n socket.onclose = (event) => {\n if (sockets.get(id) === socket) sockets.delete(id);\n emit({\n code: event.code,\n reason: event.reason,\n socketId: id,\n type: \"close\",\n });\n };\n\n return null;\n }\n if (method === \"sync.socket.sendChunk\") {\n const socket = sockets.get(id);\n if (!socket || socket.readyState !== webSocketImpl.OPEN)\n throw new Error(\"Expo Sync bridge socket is not open.\");\n const messageId = requireString(params.messageId, \"message id\");\n const index = params.index;\n const total = params.total;\n if (\n typeof index !== \"number\" ||\n !Number.isSafeInteger(index) ||\n typeof total !== \"number\" ||\n !Number.isSafeInteger(total) ||\n index < 0 ||\n total < 1 ||\n index >= total ||\n total > Math.ceil(maxFrameBytes / SOCKET_CHUNK_BYTES)\n )\n throw new TypeError(\"Expo Sync socket chunk position is invalid.\");\n if (typeof params.data !== \"string\")\n throw new TypeError(\"Expo Sync socket chunk data is invalid.\");\n const key = `${id}:\\u0000${messageId}`;\n let upload = uploads.get(key);\n if (!upload) {\n const timer = setTimeout(\n () => uploads.delete(key),\n SOCKET_UPLOAD_TIMEOUT_MS,\n );\n upload = { chunks: Array.from({ length: total }), timer };\n uploads.set(key, upload);\n }\n if (upload.chunks.length !== total || upload.chunks[index])\n throw new Error(\"Expo Sync socket chunk sequence is invalid.\");\n upload.chunks[index] = decodeBase64(params.data);\n if (upload.chunks.every((chunk) => chunk !== undefined)) {\n clearTimeout(upload.timer);\n uploads.delete(key);\n const size = upload.chunks.reduce(\n (sum, chunk) => sum + (chunk?.byteLength ?? 0),\n 0,\n );\n if (size > maxFrameBytes)\n throw new Error(\"Expo Sync socket frame exceeds its byte limit.\");\n const bytes = new Uint8Array(size);\n let offset = 0;\n for (const chunk of upload.chunks) {\n bytes.set(chunk!, offset);\n offset += chunk!.byteLength;\n }\n socket.send(new TextDecoder().decode(bytes));\n }\n\n return null;\n }\n if (method === \"sync.socket.close\") {\n const code =\n params.code === undefined\n ? undefined\n : typeof params.code === \"number\" &&\n Number.isSafeInteger(params.code) &&\n params.code >= 1000 &&\n params.code <= 4999\n ? params.code\n : null;\n if (code === null)\n throw new TypeError(\"Expo Sync bridge close code is invalid.\");\n const reason =\n params.reason === undefined\n ? undefined\n : requireString(params.reason, \"close reason\");\n close(id, code, reason);\n\n return null;\n }\n throw new Error(\"Expo Sync socket bridge method is not allowed.\");\n },\n };\n};\n"
11
+ ],
12
+ "mappings": ";AAKA;AAkBO,SAAS,OAAO,CAAC,GAAG;AAAA,EAKvB,OAAQ,aAAa,cAChB,YAAY,OAAO,CAAC,KACjB,EAAE,YAAY,SAAS,gBACvB,uBAAu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-0,0 +1,28 @@
1
+ import type { SyncLocalStore, SyncLocalStoreSchemaInput, SyncLocalProtectionProvider } from "@absolutejs/sync/client";
2
+ export type ExpoSyncSqliteExecutor = {
3
+ execAsync(source: string): Promise<void>;
4
+ getAllAsync<T>(source: string, params?: readonly (boolean | number | null | string | Uint8Array)[]): Promise<T[]>;
5
+ getFirstAsync<T>(source: string, params?: readonly (boolean | number | null | string | Uint8Array)[]): Promise<T | null>;
6
+ runAsync(source: string, params?: readonly (boolean | number | null | string | Uint8Array)[]): Promise<unknown>;
7
+ };
8
+ export type ExpoSyncSqliteDatabase = ExpoSyncSqliteExecutor & {
9
+ withExclusiveTransactionAsync(run: (transaction: ExpoSyncSqliteExecutor) => Promise<void>): Promise<void>;
10
+ };
11
+ export type ExpoSyncSqliteFactory = () => ExpoSyncSqliteDatabase | Promise<ExpoSyncSqliteDatabase>;
12
+ export type ExpoSyncLocalStoreOptions = {
13
+ /** Defaults to `absolutejs-sync-local-v1.db`. */
14
+ databaseName?: string;
15
+ /** Injection seam for conformance tests and custom database provisioning. */
16
+ database?: ExpoSyncSqliteFactory;
17
+ /** Same generated logical migration plan used by web and Capacitor. */
18
+ storageSchema?: SyncLocalStoreSchemaInput;
19
+ protection?: SyncLocalProtectionProvider;
20
+ now?: () => number;
21
+ };
22
+ /**
23
+ * Expo SQLite implementation of Sync's principal-partitioned atomic cache and
24
+ * mutation outbox. Every operation is serialized around an exclusive native
25
+ * transaction so concurrent native routes, WebViews, and background work
26
+ * cannot observe partial state.
27
+ */
28
+ export declare const createExpoSyncLocalStore: ({ databaseName, database: createDatabase, storageSchema, protection, now, }?: ExpoSyncLocalStoreOptions) => SyncLocalStore;