@vbyte/btc-dev 2.0.0 → 2.1.0

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.
Files changed (52) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/LICENSE +21 -121
  3. package/README.md +36 -227
  4. package/dist/error.d.ts +11 -0
  5. package/dist/error.js +20 -0
  6. package/dist/index.d.ts +1 -0
  7. package/dist/index.js +1 -0
  8. package/dist/lib/address/api.js +3 -2
  9. package/dist/lib/address/encode.js +6 -4
  10. package/dist/lib/address/p2pkh.js +4 -4
  11. package/dist/lib/address/p2sh.js +3 -3
  12. package/dist/lib/address/p2tr.js +3 -3
  13. package/dist/lib/address/p2wpkh.js +4 -4
  14. package/dist/lib/address/p2wsh.js +3 -3
  15. package/dist/lib/address/util.js +3 -1
  16. package/dist/lib/meta/locktime.js +3 -2
  17. package/dist/lib/meta/ref.js +4 -3
  18. package/dist/lib/meta/scribe.js +26 -6
  19. package/dist/lib/meta/sequence.js +8 -7
  20. package/dist/lib/script/decode.js +10 -9
  21. package/dist/lib/script/encode.js +4 -3
  22. package/dist/lib/script/words.js +4 -3
  23. package/dist/lib/sighash/segwit.js +9 -6
  24. package/dist/lib/sighash/taproot.js +7 -4
  25. package/dist/lib/sighash/util.js +4 -3
  26. package/dist/lib/signer/sign.js +7 -6
  27. package/dist/lib/signer/verify.js +8 -9
  28. package/dist/lib/taproot/cblock.js +3 -2
  29. package/dist/lib/taproot/encode.d.ts +1 -1
  30. package/dist/lib/taproot/encode.js +4 -3
  31. package/dist/lib/taproot/parse.js +9 -7
  32. package/dist/lib/taproot/tree.js +3 -2
  33. package/dist/lib/tx/create.js +1 -1
  34. package/dist/lib/tx/decode.js +13 -11
  35. package/dist/lib/tx/encode.js +1 -1
  36. package/dist/lib/tx/parse.js +3 -3
  37. package/dist/lib/tx/size.js +2 -4
  38. package/dist/lib/tx/util.js +2 -3
  39. package/dist/lib/tx/validate.js +36 -8
  40. package/dist/lib/witness/util.js +1 -1
  41. package/dist/main.cjs +1127 -1160
  42. package/dist/main.cjs.map +1 -1
  43. package/dist/module.mjs +1125 -1161
  44. package/dist/module.mjs.map +1 -1
  45. package/dist/package.json +13 -11
  46. package/dist/script.js +10 -12
  47. package/dist/script.js.map +1 -1
  48. package/docs/API.md +1145 -0
  49. package/docs/CONVENTIONS.md +316 -0
  50. package/docs/FAQ.md +396 -0
  51. package/docs/GUIDE.md +1102 -0
  52. package/package.json +13 -11
@@ -1 +1 @@
1
- {"version":3,"file":"script.js","sources":["../src/const.ts","../node_modules/@vbyte/buff/dist/util/validate.js","../node_modules/@vbyte/buff/dist/util/assert.js","../node_modules/@vbyte/buff/dist/lib/big.js","../node_modules/@vbyte/buff/dist/lib/num.js","../node_modules/@vbyte/buff/dist/lib/hex.js","../node_modules/@vbyte/buff/dist/lib/bytes.js","../node_modules/@vbyte/buff/dist/lib/str.js","../node_modules/@vbyte/buff/dist/class/buff.js","../node_modules/@vbyte/buff/dist/lib/bin.js","../node_modules/@vbyte/buff/dist/lib/rand.js","../node_modules/@vbyte/buff/dist/class/stream.js","../src/lib/script/lock.ts","../node_modules/@vbyte/micro-lib/dist/lib/util.js","../node_modules/@vbyte/micro-lib/dist/lib/test.js","../node_modules/@vbyte/micro-lib/dist/lib/assert.js","../node_modules/@vbyte/micro-lib/node_modules/@noble/hashes/esm/crypto.js","../node_modules/@vbyte/micro-lib/node_modules/@noble/hashes/esm/utils.js","../node_modules/@vbyte/micro-lib/node_modules/@noble/hashes/esm/_md.js","../node_modules/@vbyte/micro-lib/node_modules/@noble/hashes/esm/sha2.js","../node_modules/@vbyte/micro-lib/node_modules/@noble/hashes/esm/hmac.js","../node_modules/@vbyte/micro-lib/node_modules/@noble/curves/esm/utils.js","../node_modules/@vbyte/micro-lib/node_modules/@noble/curves/esm/abstract/modular.js","../node_modules/@vbyte/micro-lib/node_modules/@noble/curves/esm/abstract/curve.js","../node_modules/@vbyte/micro-lib/node_modules/@noble/curves/esm/abstract/weierstrass.js","../node_modules/@vbyte/micro-lib/node_modules/@noble/curves/esm/secp256k1.js","../node_modules/@vbyte/micro-lib/node_modules/@noble/curves/esm/_shortw_utils.js","../node_modules/@vbyte/micro-lib/dist/lib/ecc.js","../node_modules/@vbyte/micro-lib/node_modules/@noble/hashes/esm/legacy.js","../node_modules/@vbyte/micro-lib/dist/lib/hash.js","../node_modules/@scure/base/lib/esm/index.js","../node_modules/@vbyte/micro-lib/dist/lib/encode.js","../src/lib/address/encode.ts","../src/lib/address/script.ts","../src/lib/address/util.ts","../src/lib/address/p2pkh.ts","../src/lib/address/p2sh.ts","../src/lib/address/p2tr.ts","../src/lib/address/p2wpkh.ts","../src/lib/address/p2wsh.ts","../src/lib/address/api.ts","../src/lib/meta/locktime.ts","../src/lib/meta/ref.ts","../src/lib/script/words.ts","../src/lib/script/decode.ts","../src/lib/script/encode.ts","../src/lib/meta/scribe.ts","../src/lib/meta/sequence.ts","../src/lib/script/util.ts","../src/lib/tx/decode.ts","../node_modules/zod/v4/core/core.js","../node_modules/zod/v4/core/util.js","../node_modules/zod/v4/core/errors.js","../node_modules/zod/v4/core/parse.js","../node_modules/zod/v4/core/regexes.js","../node_modules/zod/v4/core/checks.js","../node_modules/zod/v4/core/doc.js","../node_modules/zod/v4/core/versions.js","../node_modules/zod/v4/core/schemas.js","../node_modules/zod/v4/core/registries.js","../node_modules/zod/v4/core/api.js","../node_modules/zod/v4/core/to-json-schema.js","../node_modules/zod/v4/core/json-schema-processors.js","../node_modules/zod/v4/classic/iso.js","../node_modules/zod/v4/classic/errors.js","../node_modules/zod/v4/classic/parse.js","../node_modules/zod/v4/classic/schemas.js","../src/schema/base.ts","../src/schema/taproot.ts","../src/schema/tx.ts","../src/lib/tx/validate.ts","../src/lib/tx/encode.ts","../src/lib/tx/parse.ts","../src/lib/tx/util.ts","../src/lib/tx/create.ts","../src/lib/tx/size.ts","../src/lib/sighash/util.ts","../src/lib/sighash/segwit.ts","../src/lib/taproot/encode.ts","../src/lib/sighash/taproot.ts","../src/lib/signer/sign.ts","../src/lib/witness/parse.ts","../src/lib/taproot/parse.ts","../src/lib/taproot/tree.ts","../src/lib/taproot/cblock.ts","../src/lib/signer/verify.ts","../src/lib/witness/util.ts"],"sourcesContent":["export const COINBASE = {\n\tTXID: \"00\".repeat(32),\n\tVOUT: 0xffffffff,\n};\n\nexport const DEFAULT = {\n\tLOCKTIME: 0,\n\tSEQUENCE: 0xffffffff,\n\tVERSION: 2,\n};\n\nexport const TAPLEAF_VERSIONS = [\n\t0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0xcc, 0xce, 0xd0, 0xd2, 0xd4, 0xd6, 0xd8,\n\t0xda, 0xdc, 0xde, 0xe0, 0xe2, 0xe4, 0xe6, 0xe8, 0xea, 0xec, 0xee, 0xf0, 0xf2,\n\t0xf4, 0xf6, 0xf8, 0xfa, 0xfc, 0xfe, 0x66, 0x7e, 0x80, 0x84, 0x96, 0x98, 0xba,\n\t0xbc, 0xbe,\n];\n\nexport const TAPLEAF_DEFAULT_VERSION = 0xc0;\n\nexport const LOCK_SCRIPT_TYPE = {\n\tP2PKH: \"p2pkh\",\n\tP2SH: \"p2sh\",\n\tP2WPKH: \"p2wpkh\",\n\tP2WSH: \"p2wsh\",\n\tP2TR: \"p2tr\",\n\tOPRETURN: \"opreturn\",\n} as const;\n\nexport const SPEND_SCRIPT_TYPE = {\n\tP2PKH: \"p2pkh\",\n\tP2SH: \"p2sh\",\n\tP2WPKH: \"p2wpkh\",\n\tP2WSH: \"p2wsh\",\n\tP2TR: \"p2tr\",\n\tP2TS: \"p2ts\",\n} as const;\n\nexport const LOCK_SCRIPT_REGEX: Record<string, RegExp> = {\n\t[LOCK_SCRIPT_TYPE.P2PKH]: /^76a914[0-9a-f]{40}88ac$/i,\n\t[LOCK_SCRIPT_TYPE.P2SH]: /^a914[0-9a-f]{40}87$/i,\n\t[LOCK_SCRIPT_TYPE.P2WPKH]: /^0014[0-9a-f]{40}$/i,\n\t[LOCK_SCRIPT_TYPE.P2WSH]: /^0020[0-9a-f]{64}$/i,\n\t[LOCK_SCRIPT_TYPE.P2TR]: /^5120[0-9a-f]{64}$/i,\n\t[LOCK_SCRIPT_TYPE.OPRETURN]: /^6a[0-9a-f]{2,}$/i,\n} as const;\n\nexport const SCRIPT_INT_KEY = \"\";\n\nexport const TX_SIZE = {\n\tGLOBAL_BASE: 8,\n\tGLOBAL_WIT: 10,\n\tTXIN_BASE: 32 + 4 + 4,\n\tTXOUT_BASE: 8,\n};\n\nexport const SIGHASH_DEFAULT = 0x01;\nexport const SIGHASH_SEGWIT = [0x01, 0x02, 0x03, 0x81, 0x82, 0x83];\nexport const SIGHASH_TAPROOT = [0x00, ...SIGHASH_SEGWIT];\n\n/** Bitcoin consensus script size limit (10,000 bytes) */\nexport const MAX_SCRIPT_SIZE = 10_000;\n\n/** Maximum varint payload size (~520KB, prevents memory exhaustion attacks) */\nexport const MAX_VARINT_SIZE = 520_000;\n\n/** Offset to convert 1-16 to OP_1 through OP_16 */\nexport const OP_1_OFFSET = 0x50;\n","export var Check;\n(function (Check) {\n function is_hex(input) {\n return (input.match(/[^a-fA-F0-9]/) === null &&\n input.length % 2 === 0);\n }\n Check.is_hex = is_hex;\n function is_bytes(input) {\n if (typeof input === 'string' && is_hex(input)) {\n return true;\n }\n else if (input instanceof Uint8Array) {\n return true;\n }\n else if (Array.isArray(input) &&\n input.every(e => typeof e === 'number')) {\n return true;\n }\n else {\n return false;\n }\n }\n Check.is_bytes = is_bytes;\n})(Check || (Check = {}));\n","import { Check } from '../util/validate.js';\nexport var Assert;\n(function (Assert) {\n function within_size(data, size) {\n if (data.length > size) {\n throw new TypeError(`Data is larger than array size: ${data.length} > ${size}`);\n }\n }\n Assert.within_size = within_size;\n function is_hex(hex) {\n if (hex.match(/[^a-fA-F0-9]/) !== null) {\n throw new TypeError(`Invalid characters in hex string: ${hex}`);\n }\n if (hex.length % 2 !== 0) {\n throw new Error(`Length of hex string is invalid: ${hex.length}`);\n }\n }\n Assert.is_hex = is_hex;\n function is_bytes(bytes) {\n if (!Check.is_bytes(bytes)) {\n throw new Error(`Bytes contains invalid elements: ${String(bytes)}`);\n }\n }\n Assert.is_bytes = is_bytes;\n function is_json(str) {\n try {\n JSON.parse(str);\n }\n catch {\n throw new TypeError('JSON string is invalid!');\n }\n }\n Assert.is_json = is_json;\n function is_safe_int(num) {\n if (num > Number.MAX_SAFE_INTEGER) {\n throw new TypeError('Number exceeds safe bounds!');\n }\n }\n Assert.is_safe_int = is_safe_int;\n})(Assert || (Assert = {}));\n","const _0n = BigInt(0);\nconst _255n = BigInt(255);\nconst _256n = BigInt(256);\nexport function get_big_size(big) {\n if (big <= 0xffn)\n return 1;\n if (big <= 0xffffn)\n return 2;\n if (big <= 0xffffffffn)\n return 4;\n if (big <= 0xffffffffffffffffn)\n return 8;\n if (big <= 0xffffffffffffffffffffffffffffffffn)\n return 16;\n if (big <= 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn) {\n return 32;\n }\n throw new TypeError('Must specify a fixed buffer size for bigints greater than 32 bytes.');\n}\nexport function big_to_bytes(big, size, endian = 'be') {\n if (size === undefined)\n size = get_big_size(big);\n const use_le = (endian === 'le');\n const buffer = new ArrayBuffer(size);\n const dataView = new DataView(buffer);\n let offset = (use_le) ? 0 : size - 1;\n while (big > _0n) {\n const byte = big & _255n;\n const num = Number(byte);\n if (use_le) {\n dataView.setUint8(offset++, num);\n }\n else {\n dataView.setUint8(offset--, num);\n }\n big = (big - byte) / _256n;\n }\n return new Uint8Array(buffer);\n}\nexport function bytes_to_big(bytes) {\n let num = BigInt(0);\n for (let i = bytes.length - 1; i >= 0; i--) {\n num = (num * _256n) + BigInt(bytes[i]);\n }\n return BigInt(num);\n}\nexport function bigint_replacer(_, v) {\n return typeof v === 'bigint'\n ? `${v}n`\n : v;\n}\nexport function bigint_reviver(_, v) {\n return typeof v === 'string' && /^[0-9]+n$/.test(v)\n ? BigInt(v.slice(0, -1))\n : v;\n}\n","import { Assert } from '../util/assert.js';\nexport function get_num_size(num) {\n if (num < 0) {\n throw new TypeError('Number must be non-negative');\n }\n if (num <= 0xFF)\n return 1;\n if (num <= 0xFFFF)\n return 2;\n if (num <= 0xFFFFFFFF)\n return 4;\n throw new TypeError('Numbers larger than 4 bytes must specify a fixed size!');\n}\nexport function num_to_bytes(num, size, endian = 'be') {\n if (size === undefined)\n size = get_num_size(num);\n const use_le = (endian === 'le');\n const buffer = new ArrayBuffer(size);\n const dataView = new DataView(buffer);\n let offset = (use_le) ? 0 : size - 1;\n while (num > 0) {\n const byte = num & 255;\n if (use_le) {\n dataView.setUint8(offset++, byte);\n }\n else {\n dataView.setUint8(offset--, byte);\n }\n num = (num - byte) / 256;\n }\n return new Uint8Array(buffer);\n}\nexport function bytes_to_num(bytes) {\n let num = 0;\n for (let i = bytes.length - 1; i >= 0; i--) {\n num = (num * 256) + bytes[i];\n Assert.is_safe_int(num);\n }\n return num;\n}\n","import { Assert } from '../util/assert.js';\nexport function hex_to_bytes(hexstr, size, endian = 'be') {\n size = get_hex_size(hexstr, size);\n const use_be = (endian === 'be');\n const buffer = new ArrayBuffer(size);\n const dataView = new DataView(buffer);\n let offset = (use_be) ? 0 : size - 1;\n for (let i = 0; i < hexstr.length; i += 2) {\n const char = hexstr.substring(i, i + 2);\n const num = parseInt(char, 16);\n if (use_be) {\n dataView.setUint8(offset++, num);\n }\n else {\n dataView.setUint8(offset--, num);\n }\n }\n return new Uint8Array(buffer);\n}\nexport function bytes_to_hex(bytes) {\n let chars = '';\n for (let i = 0; i < bytes.length; i++) {\n chars += bytes[i].toString(16).padStart(2, '0');\n }\n return chars;\n}\nfunction get_hex_size(hexstr, size) {\n Assert.is_hex(hexstr);\n const len = hexstr.length / 2;\n if (size === undefined)\n size = len;\n if (len > size) {\n throw new TypeError(`Hex string is larger than array size: ${len} > ${size}`);\n }\n return size;\n}\n","import { Assert } from '../util/assert.js';\nimport { big_to_bytes } from './big.js';\nimport { num_to_bytes } from './num.js';\nimport { hex_to_bytes } from './hex.js';\nexport function buffer(bytes, size, endian) {\n if (bytes instanceof ArrayBuffer) {\n return new Uint8Array(bytes);\n }\n else if (bytes instanceof Uint8Array) {\n return create_bytes(bytes, size, endian);\n }\n else if (typeof bytes === 'string') {\n Assert.is_hex(bytes);\n return hex_to_bytes(bytes, size, endian);\n }\n else if (typeof bytes === 'bigint') {\n return big_to_bytes(bytes, size, endian);\n }\n else if (typeof bytes === 'number') {\n return num_to_bytes(bytes, size, endian);\n }\n throw new TypeError(`Input type not supported: ${typeof bytes}`);\n}\nexport function create_bytes(data, size, endian = 'le') {\n if (size === undefined)\n size = data.length;\n Assert.within_size(data, size);\n const buffer = new Uint8Array(size).fill(0);\n const offset = (endian === 'be') ? 0 : size - data.length;\n buffer.set(data, offset);\n return buffer;\n}\nexport function join_bytes(arr) {\n let i, offset = 0;\n const size = arr.reduce((len, arr) => len + arr.length, 0);\n const buff = new Uint8Array(size);\n for (i = 0; i < arr.length; i++) {\n const a = arr[i];\n buff.set(a, offset);\n offset += a.length;\n }\n return buff;\n}\nexport function split_bytes(data_blob, chunk_size, total_size) {\n const len = data_blob.length, count = total_size / chunk_size;\n if (total_size % chunk_size !== 0) {\n throw new TypeError(`Invalid parameters: ${total_size} % ${chunk_size} !== 0`);\n }\n if (len !== total_size) {\n throw new TypeError(`Invalid data stream: ${len} !== ${total_size}`);\n }\n if (len % chunk_size !== 0) {\n throw new TypeError(`Invalid data stream: ${len} % ${chunk_size} !== 0`);\n }\n const chunks = new Array(count);\n for (let i = 0; i < count; i++) {\n const idx = i * chunk_size;\n chunks[i] = data_blob.subarray(idx, idx + chunk_size);\n }\n return chunks;\n}\n","const ec = new TextEncoder();\nconst dc = new TextDecoder();\nexport function str_to_bytes(str) {\n return ec.encode(str);\n}\nexport function bytes_to_str(bytes) {\n return dc.decode(bytes);\n}\n","import * as Lib from '../lib/index.js';\nimport { Assert, Check } from '../util/index.js';\nexport class Buff extends Uint8Array {\n static { this.num = (number, size, endian) => {\n return new Buff(number, size, endian);\n }; }\n static { this.big = (bigint, size, endian) => {\n return new Buff(bigint, size, endian);\n }; }\n static { this.bin = (data, size, endian) => {\n const uint = Lib.bin_to_bytes(data);\n return new Buff(uint, size, endian);\n }; }\n static { this.u8a = (data, size, endian) => {\n return new Buff(data, size, endian);\n }; }\n static { this.str = (data, size, endian) => {\n const uint = Lib.str_to_bytes(data);\n return new Buff(uint, size, endian);\n }; }\n static { this.hex = (data, size, endian) => {\n Assert.is_hex(data);\n return new Buff(data, size, endian);\n }; }\n static { this.bytes = (bytes, size, endian) => {\n Assert.is_bytes(bytes);\n return new Buff(bytes, size, endian);\n }; }\n static { this.json = (data, replacer) => {\n replacer = replacer ?? Lib.bigint_replacer;\n const str = JSON.stringify(data, replacer);\n const uint = Lib.str_to_bytes(str);\n return new Buff(uint);\n }; }\n static { this.chunk = (payload, chunk_size, total_size) => {\n const bytes = Lib.buffer(payload);\n const chunks = Lib.split_bytes(bytes, chunk_size, total_size);\n return chunks.map(e => new Buff(e));\n }; }\n static { this.is_equal = (a, b) => {\n return new Buff(a).hex === new Buff(b).hex;\n }; }\n static { this.is_bytes = Check.is_bytes; }\n static { this.is_hex = Check.is_hex; }\n static random(size = 32) {\n const uint = Lib.get_random_bytes(size);\n return new Buff(uint, size);\n }\n static now() {\n const stamp = Math.floor(Date.now() / 1000);\n return new Buff(stamp, 4);\n }\n constructor(data, size, endian) {\n super(Lib.buffer(data, size, endian));\n }\n get arr() {\n return this.to_arr();\n }\n get big() {\n return this.to_big();\n }\n get bin() {\n return this.to_bin();\n }\n get hex() {\n return this.to_hex();\n }\n get num() {\n return this.to_num();\n }\n get str() {\n return this.to_str();\n }\n get u8a() {\n return this.to_u8a();\n }\n to_big(endian = 'be') {\n const bytes = (endian === 'be')\n ? this.u8a.reverse()\n : this.u8a;\n return Lib.bytes_to_big(bytes);\n }\n to_hex(endian = 'be') {\n const bytes = (endian === 'be')\n ? this.u8a\n : this.u8a.reverse();\n return Lib.bytes_to_hex(bytes);\n }\n to_json(reviver) {\n if (reviver === undefined) {\n reviver = Lib.bigint_reviver;\n }\n const str = Lib.bytes_to_str(this);\n return JSON.parse(str, reviver);\n }\n to_num(endian = 'be') {\n const bytes = (endian === 'be')\n ? this.u8a.reverse()\n : this.u8a;\n return Lib.bytes_to_num(bytes);\n }\n to_arr() { return [...this]; }\n to_bin() { return Lib.bytes_to_bin(this); }\n to_str() { return Lib.bytes_to_str(this); }\n to_u8a() { return new Uint8Array(this); }\n append(data) {\n return Buff.join([this, new Buff(data)]);\n }\n equals(data) {\n return new Buff(data).hex === this.hex;\n }\n prepend(data) {\n return Buff.join([new Buff(data), this]);\n }\n prefix_varint(endian) {\n if (this.length === 0)\n throw new Error('buffer is empty');\n const varint = Buff.create_varint(this.length, endian);\n return this.prepend(varint);\n }\n reverse() {\n super.reverse();\n return this;\n }\n set(array, offset) {\n super.set(array, offset);\n }\n slice(start, end) {\n const arr = new Uint8Array(this).slice(start, end);\n return new Buff(arr);\n }\n subarray(begin, end) {\n const arr = new Uint8Array(this).subarray(begin, end);\n return new Buff(arr);\n }\n toJSON() {\n return this.hex;\n }\n toString() {\n return this.hex;\n }\n static from(data) {\n return new Buff(Uint8Array.from(data));\n }\n static of(...args) {\n return new Buff(Uint8Array.of(...args));\n }\n static join(arr) {\n const bytes = arr.map(e => new Buff(e));\n const joined = Lib.join_bytes(bytes);\n return new Buff(joined);\n }\n static sort(arr, size) {\n const hex = arr.map(e => new Buff(e, size).hex);\n hex.sort();\n return hex.map(e => Buff.hex(e, size));\n }\n static create_varint(num, endian) {\n if (num < 0xFD) {\n return Buff.num(num, 1);\n }\n else if (num < 0x10000) {\n return Buff.of(0xFD, ...Buff.num(num, 2, endian));\n }\n else if (num < 0x100000000) {\n return Buff.of(0xFE, ...Buff.num(num, 4, endian));\n }\n else if (BigInt(num) < 0x10000000000000000n) {\n return Buff.of(0xFF, ...Buff.num(num, 8, endian));\n }\n else {\n throw new Error(`Value is too large: ${num}`);\n }\n }\n}\n","export function bin_to_bytes(binary) {\n if (!/^[01]*$/.test(binary)) {\n throw new TypeError('Binary string must contain only 0 and 1 characters');\n }\n const bins = binary.split('').map(Number);\n if (bins.length % 8 !== 0) {\n throw new Error(`Binary array is invalid length: ${binary.length}`);\n }\n const bytes = new Uint8Array(bins.length / 8);\n for (let i = 0, ct = 0; i < bins.length; i += 8, ct++) {\n let byte = 0;\n for (let j = 0; j < 8; j++) {\n byte |= (bins[i + j] << (7 - j));\n }\n bytes[ct] = byte;\n }\n return bytes;\n}\nexport function bytes_to_bin(bytes) {\n const bin = new Array(bytes.length * 8);\n let count = 0;\n for (const num of bytes) {\n if (num > 255) {\n throw new Error(`Invalid byte value: ${num}. Byte values must be between 0 and 255.`);\n }\n for (let i = 7; i >= 0; i--, count++) {\n bin[count] = (num >> i) & 1;\n }\n }\n return bin.join('');\n}\n","export function get_random_bytes(length = 32) {\n if (!Number.isInteger(length) || length < 0) {\n throw new TypeError('Length must be a non-negative integer');\n }\n if (crypto &&\n typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(length));\n }\n const pcrypto = crypto;\n if (pcrypto &&\n pcrypto.randomBytes !== undefined &&\n typeof pcrypto.randomBytes === 'function') {\n return pcrypto.randomBytes(length);\n }\n throw new Error('getRandomValues from crypto library is undefined');\n}\n","import { Buff } from '../class/buff.js';\nexport class Stream {\n constructor(data) {\n this.data = new Buff(data);\n this.size = this.data.length;\n }\n peek(size) {\n if (size > this.size) {\n throw new Error(`Size greater than stream: ${size} > ${this.size}`);\n }\n return new Buff(this.data.slice(0, size));\n }\n read(size) {\n const chunk = this.peek(size);\n this.data = this.data.slice(size);\n this.size = this.data.length;\n return chunk;\n }\n read_varint(endian) {\n const num = this.read(1).num;\n switch (true) {\n case (num >= 0 && num < 0xFD):\n return num;\n case (num === 0xFD):\n return this.read(2).to_num(endian);\n case (num === 0xFE):\n return this.read(4).to_num(endian);\n case (num === 0xFF):\n return this.read(8).to_num(endian);\n default:\n throw new Error(`Varint is out of range: ${num}`);\n }\n }\n}\n","import { Buff, type Bytes } from \"@vbyte/buff\";\nimport { LOCK_SCRIPT_REGEX } from \"@/const.js\";\n\nimport type {\n\tLockScriptInfo,\n\tLockScriptType,\n\tWitnessVersion,\n} from \"@/types/index.js\";\n\nexport function is_return_script(script: Bytes): boolean {\n\tconst bytes = Buff.bytes(script);\n\treturn bytes.at(0) === 0x6a;\n}\n\nexport function get_lock_script_info(script: Bytes): LockScriptInfo {\n\treturn {\n\t\ttype: get_lock_script_type(script),\n\t\tversion: get_lock_script_version(script),\n\t};\n}\n\nexport function get_lock_script_type(script: Bytes): LockScriptType | null {\n\t// Get the hex string of the script.\n\tconst hex = Buff.bytes(script).hex;\n\t// Iterate over the lock script regexes.\n\tfor (const [type, regex] of Object.entries(LOCK_SCRIPT_REGEX)) {\n\t\t// If the script matches the regex, return the type.\n\t\tif (regex.test(hex)) return type as LockScriptType;\n\t}\n\t// If the script does not match any regex, return null.\n\treturn null;\n}\n\nexport function get_lock_script_version(script: Bytes): WitnessVersion | null {\n\t// Get the version of the script.\n\tconst version = Buff.bytes(script);\n\t// Return the version of the script.\n\tswitch (version.at(0)) {\n\t\tcase 0x00:\n\t\t\treturn 0;\n\t\tcase 0x51:\n\t\t\treturn 1;\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\nexport function is_p2pkh_script(script: Bytes): boolean {\n\tconst hex = Buff.bytes(script).hex;\n\treturn LOCK_SCRIPT_REGEX.p2pkh.test(hex);\n}\n\nexport function is_p2sh_script(script: Bytes): boolean {\n\tconst hex = Buff.bytes(script).hex;\n\treturn LOCK_SCRIPT_REGEX.p2sh.test(hex);\n}\n\nexport function is_p2wpkh_script(script: Bytes): boolean {\n\tconst hex = Buff.bytes(script).hex;\n\treturn LOCK_SCRIPT_REGEX.p2wpkh.test(hex);\n}\n\nexport function is_p2wsh_script(script: Bytes): boolean {\n\tconst hex = Buff.bytes(script).hex;\n\treturn LOCK_SCRIPT_REGEX.p2wsh.test(hex);\n}\n\nexport function is_p2tr_script(script: Bytes): boolean {\n\tconst hex = Buff.bytes(script).hex;\n\treturn LOCK_SCRIPT_REGEX.p2tr.test(hex);\n}\n\nexport function is_opreturn_script(script: Bytes): boolean {\n\tconst hex = Buff.bytes(script).hex;\n\treturn LOCK_SCRIPT_REGEX.opreturn.test(hex);\n}\n","export const now = () => Math.floor(Date.now() / 1000);\nexport const sleep = (ms = 1000) => new Promise(res => setTimeout(res, ms));\nexport function create_timeout(promise, timeout) {\n return new Promise(async (resolve, reject) => {\n const timer = setTimeout(() => reject('timeout'), timeout);\n const res = await promise;\n clearTimeout(timer);\n resolve(res);\n });\n}\nexport function sort_obj(obj) {\n if (obj instanceof Map || Array.isArray(obj) || typeof obj !== 'object') {\n return obj;\n }\n else {\n return Object.keys(obj)\n .sort()\n .filter(([_, value]) => value !== undefined)\n .reduce((sorted, key) => {\n sorted[key] = obj[key];\n return sorted;\n }, {});\n }\n}\nexport function parse_error(err) {\n if (err instanceof Error)\n return err.message;\n if (typeof err === 'string')\n return err;\n return String(err);\n}\n","import { Buff } from '@vbyte/buff';\nimport { sort_obj } from './util.js';\nexport var Test;\n(function (Test) {\n function exists(value) {\n if (typeof value === 'undefined' || value === null) {\n return false;\n }\n return true;\n }\n Test.exists = exists;\n function is_equal(a, b) {\n return a === b;\n }\n Test.is_equal = is_equal;\n function is_object(value) {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n }\n Test.is_object = is_object;\n function is_deep_equal(a, b) {\n if (is_object(a))\n a = sort_obj(a);\n if (is_object(b))\n b = sort_obj(b);\n return String(a) === String(b);\n }\n Test.is_deep_equal = is_deep_equal;\n function has_items(array) {\n return Array.isArray(array) && array.length > 0;\n }\n Test.has_items = has_items;\n function is_string(value) {\n return typeof value === 'string';\n }\n Test.is_string = is_string;\n function is_number(value) {\n return Number.isInteger(value) && !Number.isNaN(value);\n }\n Test.is_number = is_number;\n function is_bigint(value) {\n return typeof value === 'bigint';\n }\n Test.is_bigint = is_bigint;\n function is_uchar(value) {\n return is_number(value) && value >= 0 && value <= 0xFF;\n }\n Test.is_uchar = is_uchar;\n function is_ushort(value) {\n return is_number(value) && value >= 0 && value <= 0xFFFF;\n }\n Test.is_ushort = is_ushort;\n function is_uint(value) {\n return is_number(value) && value >= 0 && value <= 0xFFFFFFFF;\n }\n Test.is_uint = is_uint;\n function is_u8a(value) {\n return value instanceof Uint8Array;\n }\n Test.is_u8a = is_u8a;\n function is_bytes(value) {\n return Buff.is_bytes(value);\n }\n Test.is_bytes = is_bytes;\n function is_base58(value) {\n if (typeof value !== 'string')\n return false;\n return /^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]+$/.test(value);\n }\n Test.is_base58 = is_base58;\n function is_base64(value) {\n if (typeof value !== 'string')\n return false;\n return /^[a-zA-Z0-9+/]+={0,2}$/.test(value);\n }\n Test.is_base64 = is_base64;\n function is_b64url(value) {\n if (typeof value !== 'string')\n return false;\n return /^[a-zA-Z0-9\\-_]+={0,2}$/.test(value);\n }\n Test.is_b64url = is_b64url;\n function is_bech32(value) {\n if (typeof value !== 'string')\n return false;\n return /^[a-z]+1[023456789acdefghjklmnpqrstuvwxyz]+$/.test(value);\n }\n Test.is_bech32 = is_bech32;\n function is_hex(value) {\n if (!is_string(value))\n return false;\n return (value.match(/[^a-fA-F0-9]/) === null && value.length % 2 === 0);\n }\n Test.is_hex = is_hex;\n function is_hash(value) {\n return (is_string(value) && is_hex(value) && value.length === 64);\n }\n Test.is_hash = is_hash;\n})(Test || (Test = {}));\n","import { Buff } from '@vbyte/buff';\nimport { Test } from './test.js';\nexport var Assert;\n(function (Assert) {\n function ok(value, message) {\n if (value === false) {\n throw new Error(message ?? 'Assertion failed!');\n }\n }\n Assert.ok = ok;\n function exists(value, msg) {\n if (!Test.exists(value)) {\n throw new Error(msg ?? 'Value is null or undefined!');\n }\n }\n Assert.exists = exists;\n function is_empty(value, msg) {\n if (value !== null && value !== undefined) {\n throw new Error(msg ?? 'value is not null or undefined!');\n }\n }\n Assert.is_empty = is_empty;\n function is_instance(value, type, msg) {\n if (!(value instanceof type)) {\n throw new Error(msg ?? `value is not an instance of ${type.name}`);\n }\n }\n Assert.is_instance = is_instance;\n function is_equal(a, b, msg) {\n if (!Test.is_equal(a, b)) {\n throw new Error(msg ?? `values are not equal: ${String(a)} !== ${String(b)}`);\n }\n }\n Assert.is_equal = is_equal;\n function is_object(value, msg) {\n if (!Test.is_object(value)) {\n throw new Error(msg ?? `value is not an object: ${String(value)}`);\n }\n }\n Assert.is_object = is_object;\n function is_deep_equal(a, b, msg) {\n if (!Test.is_deep_equal(a, b)) {\n throw new Error(msg ?? `values are not deep equal: ${String(a)} !== ${String(b)}`);\n }\n }\n Assert.is_deep_equal = is_deep_equal;\n function is_number(value) {\n if (!Test.is_number(value)) {\n throw new TypeError(`invalid number: ${String(value)}`);\n }\n }\n Assert.is_number = is_number;\n function is_bigint(value) {\n if (!Test.is_bigint(value)) {\n throw new TypeError(`invalid bigint: ${String(value)}`);\n }\n }\n Assert.is_bigint = is_bigint;\n function is_hex(value) {\n if (!Test.is_hex(value)) {\n throw new TypeError(`invalid hex: ${String(value)}`);\n }\n }\n Assert.is_hex = is_hex;\n function is_uchar(value) {\n if (!Test.is_uchar(value)) {\n throw new TypeError(`invalid unsignedchar: ${String(value)}`);\n }\n }\n Assert.is_uchar = is_uchar;\n function is_ushort(value) {\n if (!Test.is_ushort(value)) {\n throw new TypeError(`invalid unsigned short: ${String(value)}`);\n }\n }\n Assert.is_ushort = is_ushort;\n function is_uint(value) {\n if (!Test.is_uint(value)) {\n throw new TypeError(`invalid unsigned int: ${String(value)}`);\n }\n }\n Assert.is_uint = is_uint;\n function is_u8a(value) {\n if (!Test.is_u8a(value)) {\n throw new TypeError(`invalid Uint8Array: ${String(value)}`);\n }\n }\n Assert.is_u8a = is_u8a;\n function is_hash(value, msg) {\n if (!Test.is_hash(value)) {\n throw new TypeError(msg ?? `invalid hash: ${String(value)}`);\n }\n }\n Assert.is_hash = is_hash;\n function is_bytes(value, msg) {\n if (!Test.is_bytes(value)) {\n throw new TypeError(msg ?? `invalid bytes: ${String(value)}`);\n }\n }\n Assert.is_bytes = is_bytes;\n function size(input, size, msg) {\n const bytes = Buff.bytes(input);\n if (bytes.length !== size) {\n throw new Error(msg ?? `invalid input size: ${bytes.length} !== ${size}`);\n }\n }\n Assert.size = size;\n function has_items(array, err_msg) {\n if (!Test.has_items(array)) {\n throw new Error(err_msg ?? 'array does not contain any items');\n }\n }\n Assert.has_items = has_items;\n function is_base58(value) {\n if (!Test.is_base58(value)) {\n throw new Error('invalid base58 string');\n }\n }\n Assert.is_base58 = is_base58;\n function is_base64(value) {\n if (!Test.is_base64(value)) {\n throw new Error('invalid base64 string');\n }\n }\n Assert.is_base64 = is_base64;\n function is_b64url(value) {\n if (!Test.is_b64url(value)) {\n throw new Error('invalid base64url string');\n }\n }\n Assert.is_b64url = is_b64url;\n function is_bech32(value) {\n if (!Test.is_bech32(value)) {\n throw new Error('invalid bech32 string');\n }\n }\n Assert.is_bech32 = is_bech32;\n})(Assert || (Assert = {}));\n","export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n//# sourceMappingURL=crypto.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\nexport class SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = SHA224_IV[0] | 0;\n this.B = SHA224_IV[1] | 0;\n this.C = SHA224_IV[2] | 0;\n this.D = SHA224_IV[3] | 0;\n this.E = SHA224_IV[4] | 0;\n this.F = SHA224_IV[5] | 0;\n this.G = SHA224_IV[6] | 0;\n this.H = SHA224_IV[7] | 0;\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = SHA512_IV[0] | 0;\n this.Al = SHA512_IV[1] | 0;\n this.Bh = SHA512_IV[2] | 0;\n this.Bl = SHA512_IV[3] | 0;\n this.Ch = SHA512_IV[4] | 0;\n this.Cl = SHA512_IV[5] | 0;\n this.Dh = SHA512_IV[6] | 0;\n this.Dl = SHA512_IV[7] | 0;\n this.Eh = SHA512_IV[8] | 0;\n this.El = SHA512_IV[9] | 0;\n this.Fh = SHA512_IV[10] | 0;\n this.Fl = SHA512_IV[11] | 0;\n this.Gh = SHA512_IV[12] | 0;\n this.Gl = SHA512_IV[13] | 0;\n this.Hh = SHA512_IV[14] | 0;\n this.Hl = SHA512_IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = SHA384_IV[0] | 0;\n this.Al = SHA384_IV[1] | 0;\n this.Bh = SHA384_IV[2] | 0;\n this.Bl = SHA384_IV[3] | 0;\n this.Ch = SHA384_IV[4] | 0;\n this.Cl = SHA384_IV[5] | 0;\n this.Dh = SHA384_IV[6] | 0;\n this.Dl = SHA384_IV[7] | 0;\n this.Eh = SHA384_IV[8] | 0;\n this.El = SHA384_IV[9] | 0;\n this.Fh = SHA384_IV[10] | 0;\n this.Fl = SHA384_IV[11] | 0;\n this.Gh = SHA384_IV[12] | 0;\n this.Gl = SHA384_IV[13] | 0;\n this.Hh = SHA384_IV[14] | 0;\n this.Hl = SHA384_IV[15] | 0;\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, Hash, toBytes } from \"./utils.js\";\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n ahash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n abytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes as abytes_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, } from '@noble/hashes/utils.js';\nexport { abytes, anumber, bytesToHex, bytesToUtf8, concatBytes, hexToBytes, isBytes, randomBytes, utf8ToBytes, } from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport function abool(title, value) {\n if (typeof value !== 'boolean')\n throw new Error(title + ' boolean expected, got ' + value);\n}\n// tmp name until v2\nexport function _abool2(value, title = '') {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\"`;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n// tmp name until v2\n/** Asserts something is Uint8Array. */\nexport function _abytes2(value, length, title = '') {\n const bytes = isBytes_(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n abytes_(bytes);\n return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes_(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'secret key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes_(hex);\n }\n catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n }\n else if (isBytes_(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes) {\n return Uint8Array.from(bytes);\n}\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as utf8ToBytes for ASCII or throws.\n */\nexport function asciiToBytes(ascii) {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\n// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\n// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_1n << BigInt(n)) - _1n;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n const u8n = (len) => new Uint8Array(len); // creates Uint8Array\n const u8of = (byte) => Uint8Array.of(byte); // another shortcut\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n(0)) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || isBytes_(val),\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error('invalid validator function');\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\nexport function isHash(val) {\n return typeof val === 'function' && Number.isSafeInteger(val.outputLen);\n}\nexport function _validateObject(object, fields, optFields = {}) {\n if (!object || typeof object !== 'object')\n throw new Error('expected valid options object');\n function checkField(fieldName, expectedType, isOpt) {\n const val = object[fieldName];\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));\n Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));\n}\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn) {\n const map = new WeakMap();\n return (arg, ...args) => {\n const val = map.get(arg);\n if (val !== undefined)\n return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n//# sourceMappingURL=utils.js.map","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { _validateObject, anumber, bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, } from \"../utils.js\";\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);\n// prettier-ignore\nconst _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num, power, modulo) {\n return FpPow(Field(modulo), num, power);\n}\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n if (modulo <= _0n)\n throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\nfunction assertIsSquare(Fp, root, n) {\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n}\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp, n) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\nfunction sqrt5mod8(Fp, n) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n assertIsSquare(Fp, root, n);\n return root;\n}\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P) {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return (Fp, n) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n)\n throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000)\n throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1)\n return sqrt3mod4;\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n if (Fp.is0(n))\n return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1)\n throw new Error('Cannot find square root');\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t))\n return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M)\n throw new Error('Cannot find square root');\n }\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P) {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n)\n return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n)\n return sqrt5mod8;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n)\n return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n _validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(Fp, num, power) {\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return Fp.ONE;\n if (power === _1n)\n return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp, nums, passZero = false) {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num))\n return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num))\n return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n// TODO: remove\nexport function FpDiv(Fp, lhs, rhs) {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n */\nexport function FpLegendre(Fp, n) {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no)\n throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp, n) {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined)\n anumber(nBitLength);\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?\nisLE = false, opts = {}) {\n if (ORDER <= _0n)\n throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength = undefined;\n let _sqrt = undefined;\n let modFromBytes = false;\n let allowedLengths = undefined;\n if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {\n if (opts.sqrt || isLE)\n throw new Error('cannot specify opts in two arguments');\n const _opts = bitLenOrOpts;\n if (_opts.BITS)\n _nbitLength = _opts.BITS;\n if (_opts.sqrt)\n _sqrt = _opts.sqrt;\n if (typeof _opts.isLE === 'boolean')\n isLE = _opts.isLE;\n if (typeof _opts.modFromBytes === 'boolean')\n modFromBytes = _opts.modFromBytes;\n allowedLengths = _opts.allowedLengths;\n }\n else {\n if (typeof bitLenOrOpts === 'number')\n _nbitLength = bitLenOrOpts;\n if (opts.sqrt)\n _sqrt = opts.sqrt;\n }\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);\n if (BYTES > 2048)\n throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP; // cached sqrtP\n const f = Object.freeze({\n ORDER,\n isLE,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n allowedLengths: allowedLengths,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n // is valid and invertible\n isValidNot0: (num) => !f.is0(num) && f.isValid(num),\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: _sqrt ||\n ((n) => {\n if (!sqrtP)\n sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes, skipValidation = true) => {\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes)\n scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!f.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n },\n // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n });\n return Object.freeze(f);\n}\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject } from \"../utils.js\";\nimport { Field, FpInvertBatch, nLength, validateField } from \"./modular.js\";\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nexport function negateCt(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\n}\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\nexport function normalizeZ(c, points) {\n const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\nfunction validateW(W, bits) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\nfunction calcWOpts(W, scalarBits) {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\nfunction calcOffsets(n, window, wOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\nfunction validateMSMPoints(points, c) {\n if (!Array.isArray(points))\n throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars, field) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error('invalid scalar at index ' + i);\n });\n}\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\nfunction getW(P) {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\nfunction assert0(n) {\n if (n !== _0n)\n throw new Error('invalid wNAF');\n}\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF {\n // Parametrized with a given Point class (not individual point)\n constructor(Point, bits) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n // non-const time multiplication ladder\n _unsafeLadder(elm, n, p = this.ZERO) {\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(point, W) {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points = [];\n let p = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n))\n throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n }\n else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n }\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n)\n break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n }\n else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n getPrecomputes(W, point, transform) {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W);\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function')\n comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n cached(point, scalar, transform) {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n unsafe(point, scalar, transform, prev) {\n const W = getW(point);\n if (W === 1)\n return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P, W) {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n hasCache(elm) {\n return getW(elm) !== 1;\n }\n}\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe(Point, point, k1, k2) {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n p1 = p1.add(acc);\n if (k2 & _1n)\n p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka secret keys / bigints)\n */\nexport function pippenger(c, fieldN, points, scalars) {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength)\n throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12)\n windowSize = wbits - 3;\n else if (wbits > 4)\n windowSize = wbits - 2;\n else if (wbits > 0)\n windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe(c, fieldN, points, windowSize) {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero)\n for (let j = 0; j < windowSize; j++)\n res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr)\n continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n// TODO: remove\n/** @deprecated */\nexport function validateBasic(curve) {\n validateField(curve.Fp);\n validateObject(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\nfunction createField(order, field, isLE) {\n if (field) {\n if (field.ORDER !== order)\n throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n }\n else {\n return Field(order, { isLE });\n }\n}\n/** Validates CURVE opts and creates fields */\nexport function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {\n if (FpFnLE === undefined)\n FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object')\n throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h']) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b];\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n//# sourceMappingURL=curve.js.map","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils';\nimport { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToHexUnpadded, randomBytes as randomBytesWeb, } from \"../utils.js\";\nimport { _createCurveFields, mulEndoUnsafe, negateCt, normalizeZ, pippenger, wNAF, } from \"./curve.js\";\nimport { Field, FpInvertBatch, getMinHashLength, mapHashToField, nLength, validateField, } from \"./modular.js\";\n// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)\nconst divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;\n/**\n * Splits scalar for GLV endomorphism.\n */\nexport function _splitEndoScalar(k, basis, n) {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg)\n k1 = -k1;\n if (k2neg)\n k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n}\nfunction validateSigFormat(format) {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format;\n}\nfunction validateSigOpts(opts, def) {\n const optsn = {};\n for (let optName of Object.keys(def)) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS, 'lowS');\n abool(optsn.prehash, 'prehash');\n if (optsn.format !== undefined)\n validateSigFormat(optsn.format);\n return optsn;\n}\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 128)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 127;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num) {\n const { Err: E } = DER;\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data) {\n const { Err: E } = DER;\n if (data[0] & 128)\n throw new E('invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 128))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = ensureBytes('signature', hex);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function _normFnElement(Fn, key) {\n const { BYTES: expected } = Fn;\n let num;\n if (typeof key === 'bigint') {\n num = key;\n }\n else {\n let bytes = ensureBytes('private key', key);\n try {\n num = Fn.fromBytes(bytes);\n }\n catch (error) {\n throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);\n }\n }\n if (!Fn.isValidNot0(num))\n throw new Error('invalid private key: out of range [1..N-1]');\n return num;\n}\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * @example\n```js\nconst opts = {\n p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n h: BigInt(1),\n a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),\n b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n};\nconst p256_Point = weierstrass(opts);\n```\n */\nexport function weierstrassN(params, extraOpts = {}) {\n const validated = _createCurveFields('weierstrass', params, extraOpts);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n _validateObject(extraOpts, {}, {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n wrapPrivateKey: 'boolean',\n });\n const { endo } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n const lengths = getWLengths(Fp, Fn);\n function assertCompressionIsSupported() {\n if (!Fp.isOdd)\n throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n // Implements IEEE P1363 point encoding\n function pointToBytes(_c, point, isCompressed) {\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd(y);\n return concatBytes(pprefix(hasEvenY), bx);\n }\n else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x))\n throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;\n const isHeadOdd = (head & 1) === 1; // ECDSA-specific\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y))\n throw new Error('bad point: is not on curve');\n return { x, y };\n }\n else {\n throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);\n }\n }\n const encodePoint = extraOpts.toBytes || pointToBytes;\n const decodePoint = extraOpts.fromBytes || pointFromBytes;\n function weierstrassEquation(x) {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b\n }\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y² == x³ + ax + b */\n function isValidXY(x, y) {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2)))\n throw new Error('bad curve params: a or b');\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title, n, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n)))\n throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n function aprjpoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n function splitEndoScalarN(k) {\n if (!endo || !endo.basises)\n throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)\n const toAffineMemo = memoized((p, iz) => {\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE))\n return { x: X, y: Y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x, y };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is invalid representation of ZERO.\n if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\n }\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).\n * Default Point works in 2d / affine coordinates: (x, y).\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X, Y, Z) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n static fromBytes(bytes) {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n static fromHex(hex) {\n return Point.fromBytes(ensureBytes('pointHex', hex));\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n *\n * @param windowSize\n * @param isLazy true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy)\n this.multiply(_3n); // random number\n return this;\n }\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity() {\n assertValidMemo(this);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n /** Compare one point to another. */\n equals(other) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate() {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n const { endo } = extraOpts;\n if (!Fn.isValidNot0(scalar))\n throw new Error('invalid scalar: out of range'); // 0 is invalid\n let point, fake; // Fake point is used to const-time mult\n const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n }\n else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc) {\n const { endo } = extraOpts;\n const p = this;\n if (!Fn.isValid(sc))\n throw new Error('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0())\n return Point.ZERO;\n if (sc === _1n)\n return p; // fast-path\n if (wnaf.hasCache(this))\n return this.multiply(sc);\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n }\n else {\n return wnaf.unsafe(p, sc);\n }\n }\n multiplyAndAddUnsafe(Q, a, b) {\n const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));\n return sum.is0() ? undefined : sum;\n }\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ) {\n return toAffineMemo(this, invertedZ);\n }\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree() {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n)\n return true;\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n clearCofactor() {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(cofactor);\n }\n isSmallOrder() {\n // can we use this.clearCofactor()?\n return this.multiplyUnsafe(cofactor).is0();\n }\n toBytes(isCompressed = true) {\n abool(isCompressed, 'isCompressed');\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n return bytesToHex(this.toBytes(isCompressed));\n }\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n // TODO: remove\n get px() {\n return this.X;\n }\n get py() {\n return this.X;\n }\n get pz() {\n return this.Z;\n }\n toRawBytes(isCompressed = true) {\n return this.toBytes(isCompressed);\n }\n _setWindowSize(windowSize) {\n this.precompute(windowSize);\n }\n static normalizeZ(points) {\n return normalizeZ(Point, points);\n }\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(_normFnElement(Fn, privateKey));\n }\n }\n // base / generator point\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n Point.Fp = Fp;\n // scalar field\n Point.Fn = Fn;\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY) {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n validateField(Fp);\n const { A, B, Z } = opts;\n if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, Z);\n if (!Fp.isOdd)\n throw new Error('Field does not have .isOdd()');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\nfunction getWLengths(Fp, Fn) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n signature: 2 * Fn.BYTES,\n };\n}\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n */\nexport function ecdh(Point, ecdhOpts = {}) {\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });\n function isValidSecretKey(secretKey) {\n try {\n return !!_normFnElement(Fn, secretKey);\n }\n catch (error) {\n return false;\n }\n }\n function isValidPublicKey(publicKey, isCompressed) {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp)\n return false;\n if (isCompressed === false && l !== publicKeyUncompressed)\n return false;\n return !!Point.fromBytes(publicKey);\n }\n catch (error) {\n return false;\n }\n }\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed = randomBytes_(lengths.seed)) {\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n }\n /**\n * Computes public key for a secret key. Checks for validity of the secret key.\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(secretKey, isCompressed = true) {\n return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);\n }\n function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n if (typeof item === 'bigint')\n return false;\n if (item instanceof Point)\n return true;\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n if (Fn.allowedLengths || secretKey === publicKey)\n return undefined;\n const l = ensureBytes('key', item).length;\n return l === publicKey || l === publicKeyUncompressed;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {\n if (isProbPub(secretKeyA) === true)\n throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false)\n throw new Error('second arg must be public key');\n const s = _normFnElement(Fn, secretKeyA);\n const b = Point.fromHex(publicKeyB); // checks for being on-curve\n return b.multiply(s).toBytes(isCompressed);\n }\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n // TODO: remove\n isValidPrivateKey: isValidSecretKey,\n randomPrivateKey: randomSecretKey,\n normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),\n precompute(windowSize = 8, point = Point.BASE) {\n return point.precompute(windowSize, false);\n },\n };\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n * We need `hash` for 2 features:\n * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`\n * 2. k generation in `sign`, using HMAC-drbg(hash)\n *\n * ECDSAOpts are only rarely needed.\n *\n * @example\n * ```js\n * const p256_Point = weierstrass(...);\n * const p256_sha256 = ecdsa(p256_Point, sha256);\n * const p256_sha224 = ecdsa(p256_Point, sha224);\n * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });\n * ```\n */\nexport function ecdsa(Point, hash, ecdsaOpts = {}) {\n ahash(hash);\n _validateObject(ecdsaOpts, {}, {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n });\n const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;\n const hmac = ecdsaOpts.hmac ||\n ((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs)));\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts = {\n prehash: false,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,\n format: undefined, //'compact' as ECDSASigFormat,\n extraEntropy: false,\n };\n const defaultSigOpts_format = 'compact';\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title, num) {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function validateSigLength(bytes, format) {\n validateSigFormat(format);\n const size = lengths.signature;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer, `${format} signature`);\n }\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null)\n this.recovery = recovery;\n Object.freeze(this);\n }\n static fromBytes(bytes, format = defaultSigOpts_format) {\n validateSigLength(bytes, format);\n let recid;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = Fn.BYTES;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n static fromHex(hex, format) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(messageHash) {\n const FIELD_ORDER = Fp.ORDER;\n const { r, s, recovery: rec } = this;\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n // ECDSA recovery is hard for cofactor > 1 curves.\n // In sign, `r = q.x mod n`, and here we recover q.x from r.\n // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.\n // However, for cofactor>1, r+n may not get q.x:\n // r+n*i would need to be done instead where i is unknown.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit non-prime-order signatures (recid > 1).\n const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;\n if (hasCofactor && rec > 1)\n throw new Error('recovery id is ambiguous for h>1 curve');\n const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj))\n throw new Error('recovery id 2 or 3 invalid');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0())\n throw new Error('point at infinify');\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n toBytes(format = defaultSigOpts_format) {\n validateSigFormat(format);\n if (format === 'der')\n return hexToBytes(DER.hexFromSig(this));\n const r = Fn.toBytes(this.r);\n const s = Fn.toBytes(this.s);\n if (format === 'recovered') {\n if (this.recovery == null)\n throw new Error('recovery bit must be present');\n return concatBytes(Uint8Array.of(this.recovery), r, s);\n }\n return concatBytes(r, s);\n }\n toHex(format) {\n return bytesToHex(this.toBytes(format));\n }\n // TODO: remove\n assertValidity() { }\n static fromCompact(hex) {\n return Signature.fromBytes(ensureBytes('sig', hex), 'compact');\n }\n static fromDER(hex) {\n return Signature.fromBytes(ensureBytes('sig', hex), 'der');\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;\n }\n toDERRawBytes() {\n return this.toBytes('der');\n }\n toDERHex() {\n return bytesToHex(this.toBytes('der'));\n }\n toCompactRawBytes() {\n return this.toBytes('compact');\n }\n toCompactHex() {\n return bytesToHex(this.toBytes('compact'));\n }\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = ecdsaOpts.bits2int ||\n function bits2int_def(bytes) {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192)\n throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = ecdsaOpts.bits2int_modN ||\n function bits2int_modN_def(bytes) {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // Pads output with zero as per spec\n const ORDER_MASK = bitMask(fnBits);\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num) {\n // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n function validateMsgAndHash(message, prehash) {\n abytes(message, undefined, 'message');\n return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;\n }\n /**\n * Steps A, D of RFC6979 3.2.\n * Creates RFC6979 seed; converts msg/privKey to numbers.\n * Used only in sign, not in verify.\n *\n * Warning: we cannot assume here that message has same amount of bytes as curve order,\n * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.\n */\n function prepSig(message, privateKey, opts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(message);\n const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n // To transform k => Signature:\n // q = k⋅G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // mod n, not mod p\n if (!Fn.isValidNot0(k))\n return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = Fn.neg(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n /**\n * Signs message hash with a secret key.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message, secretKey, opts = {}) {\n message = ensureBytes('message', message);\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig;\n }\n function tryParsingSig(sg) {\n // Try to deduce format\n let sig = undefined;\n const isHex = typeof sg === 'string' || isBytes(sg);\n const isObj = !isHex &&\n sg !== null &&\n typeof sg === 'object' &&\n typeof sg.r === 'bigint' &&\n typeof sg.s === 'bigint';\n if (!isHex && !isObj)\n throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n if (isObj) {\n sig = new Signature(sg.r, sg.s);\n }\n else if (isHex) {\n try {\n sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n }\n if (!sig) {\n try {\n sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');\n }\n catch (error) {\n return false;\n }\n }\n }\n if (!sig)\n return false;\n return sig;\n }\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * u1 = hs^-1 mod n\n * u2 = rs^-1 mod n\n * R = u1⋅G + u2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, message, publicKey, opts = {}) {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = ensureBytes('publicKey', publicKey);\n message = validateMsgAndHash(ensureBytes('message', message), prehash);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n const sig = format === undefined\n ? tryParsingSig(signature)\n : Signature.fromBytes(ensureBytes('sig', signature), format);\n if (sig === false)\n return false;\n try {\n const P = Point.fromBytes(publicKey);\n if (lowS && sig.hasHighS())\n return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P\n if (R.is0())\n return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n }\n catch (e) {\n return false;\n }\n }\n function recoverPublicKey(signature, message, opts = {}) {\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash,\n });\n}\n/** @deprecated use `weierstrass` in newer releases */\nexport function weierstrassPoints(c) {\n const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);\n const Point = weierstrassN(CURVE, curveOpts);\n return _weierstrass_new_output_to_legacy(c, Point);\n}\nfunction _weierstrass_legacy_opts_to_new(c) {\n const CURVE = {\n a: c.a,\n b: c.b,\n p: c.Fp.ORDER,\n n: c.n,\n h: c.h,\n Gx: c.Gx,\n Gy: c.Gy,\n };\n const Fp = c.Fp;\n let allowedLengths = c.allowedPrivateKeyLengths\n ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))\n : undefined;\n const Fn = Field(CURVE.n, {\n BITS: c.nBitLength,\n allowedLengths: allowedLengths,\n modFromBytes: c.wrapPrivateKey,\n });\n const curveOpts = {\n Fp,\n Fn,\n allowInfinityPoint: c.allowInfinityPoint,\n endo: c.endo,\n isTorsionFree: c.isTorsionFree,\n clearCofactor: c.clearCofactor,\n fromBytes: c.fromBytes,\n toBytes: c.toBytes,\n };\n return { CURVE, curveOpts };\n}\nfunction _ecdsa_legacy_opts_to_new(c) {\n const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);\n const ecdsaOpts = {\n hmac: c.hmac,\n randomBytes: c.randomBytes,\n lowS: c.lowS,\n bits2int: c.bits2int,\n bits2int_modN: c.bits2int_modN,\n };\n return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };\n}\nexport function _legacyHelperEquat(Fp, a, b) {\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².\n * @returns y²\n */\n function weierstrassEquation(x) {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b\n }\n return weierstrassEquation;\n}\nfunction _weierstrass_new_output_to_legacy(c, Point) {\n const { Fp, Fn } = Point;\n function isWithinCurveOrder(num) {\n return inRange(num, _1n, Fn.ORDER);\n }\n const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);\n return Object.assign({}, {\n CURVE: c,\n Point: Point,\n ProjectivePoint: Point,\n normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),\n weierstrassEquation,\n isWithinCurveOrder,\n });\n}\nfunction _ecdsa_new_output_to_legacy(c, _ecdsa) {\n const Point = _ecdsa.Point;\n return Object.assign({}, _ecdsa, {\n ProjectivePoint: Point,\n CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),\n });\n}\n// _ecdsa_legacy\nexport function weierstrass(c) {\n const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);\n const Point = weierstrassN(CURVE, curveOpts);\n const signs = ecdsa(Point, hash, ecdsaOpts);\n return _ecdsa_new_output_to_legacy(c, signs);\n}\n//# sourceMappingURL=weierstrass.js.map","/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createCurve } from \"./_shortw_utils.js\";\nimport { createHasher, isogenyMap, } from \"./abstract/hash-to-curve.js\";\nimport { Field, mapHashToField, mod, pow2 } from \"./abstract/modular.js\";\nimport { _normFnElement, mapToCurveSimpleSWU, } from \"./abstract/weierstrass.js\";\nimport { bytesToNumberBE, concatBytes, ensureBytes, inRange, numberToBytesBE, utf8ToBytes, } from \"./utils.js\";\n// Seems like generator was produced from some seed:\n// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\nconst secp256k1_ENDO = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1_CURVE.p;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });\n/**\n * secp256k1 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * const msg = new TextEncoder().encode('hello');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey) === true;\n * ```\n */\nexport const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(utf8ToBytes(tag));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toBytes(true).slice(1);\nconst Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();\nconst hasEven = (y) => y % _2n === _0n;\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n const { Fn, BASE } = Pointk1;\n const d_ = _normFnElement(Fn, priv);\n const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n return { scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n const Fp = Fpk1;\n if (!Fp.isValidNot0(x))\n throw new Error('invalid x: Fail if x ≥ p');\n const xx = Fp.create(x * x);\n const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y))\n y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(secretKey) {\n return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, secretKey, auxRand = randomBytes(32)) {\n const { Fn } = Pointk1;\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const { Fn, BASE } = Pointk1;\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!inRange(r, _1n, secp256k1_CURVE.p))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1_CURVE.n))\n return false;\n // int(challenge(bytes(r)||bytes(P)||m))%n\n const e = challenge(Fn.toBytes(r), pointToBytes(P), m);\n // R = s⋅G - e⋅P, where -eP == (n-e)P\n const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n if (R.is0() || !hasEven(y) || x !== r)\n return false;\n return true;\n }\n catch (error) {\n return false;\n }\n}\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed = randomBytes(seedLength)) => {\n return mapHashToField(seed, secp256k1_CURVE.n);\n };\n // TODO: remove\n secp256k1.utils.randomSecretKey;\n function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };\n }\n return {\n keygen,\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: {\n randomSecretKey: randomSecretKey,\n randomPrivateKey: randomSecretKey,\n taggedHash,\n // TODO: remove\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n mod,\n },\n lengths: {\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n },\n };\n})();\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n}))();\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(secp256k1.Point, (scalars) => {\n const { x, y } = mapSWU(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\n/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */\nexport const hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();\n/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */\nexport const encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { weierstrass } from \"./abstract/weierstrass.js\";\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash) {\n return { hash };\n}\n/** @deprecated use new `weierstrass()` and `ecdsa()` methods */\nexport function createCurve(curveDef, defHash) {\n const create = (hash) => weierstrass({ ...curveDef, hash: hash });\n return { ...create(defHash), create };\n}\n//# sourceMappingURL=_shortw_utils.js.map","import { Buff } from '@vbyte/buff';\nimport { Assert } from './assert.js';\nimport { secp256k1, schnorr } from '@noble/curves/secp256k1';\nimport { Field } from '@noble/curves/abstract/modular';\nconst _0n = BigInt(0);\nconst _2n = BigInt(2);\nconst _N = secp256k1.CURVE.n;\nconst FD = Field(_N, 32, true);\nconst GP = secp256k1.Point.BASE;\nexport function get_seckey(secret, even_y = false) {\n let sk = serialize_bytes(secret).big % _N;\n if (even_y) {\n const pt = GP.multiply(sk);\n return (pt.y % _2n === _0n)\n ? Buff.big(sk)\n : Buff.big(_N - sk);\n }\n else {\n return Buff.big(sk);\n }\n}\nexport function get_pubkey(seckey, format) {\n const sk = serialize_bytes(seckey).big;\n const pt = GP.multiply(sk);\n const pk = pt.toHex(true);\n return serialize_pubkey(pk, format);\n}\nexport function tweak_seckey(seckey, tweak, even_y = false) {\n const sk = get_seckey(seckey, even_y).big;\n const twk = serialize_bytes(tweak).big;\n const tweaked_sk = FD.add(sk, twk);\n const new_secret = Buff.big(tweaked_sk);\n return get_seckey(new_secret, false);\n}\nexport function tweak_pubkey(pubkey, tweak, format, even_y = false) {\n const twk_big = serialize_bytes(tweak).big;\n const pub_pt = lift_point(pubkey);\n const tweak_pt = GP.multiply(twk_big);\n let tweaked_pt = pub_pt.add(tweak_pt);\n if (even_y && tweaked_pt.y % _2n !== _0n) {\n tweaked_pt = tweaked_pt.negate();\n }\n const pk = tweaked_pt.toHex(true);\n return serialize_pubkey(pk, format);\n}\nexport function verify_seckey(seckey) {\n const sk = serialize_bytes(seckey);\n Assert.size(sk, 32, 'ecdsa secret keys must be 32 bytes long');\n Assert.ok(sk.big < _N, 'ecdsa secret keys must be less than the curve order');\n Assert.ok(sk.big > 0, 'ecdsa secret keys must be greater than zero');\n}\nexport function verify_pubkey(pubkey, format) {\n const pk = serialize_bytes(pubkey);\n if (format === 'bip340') {\n Assert.size(pk, 32, 'bip340 public keys must be 32 bytes long');\n }\n else if (format === 'ecdsa') {\n Assert.size(pk, 33, 'ecdsa public keys must be 33 bytes long');\n }\n else {\n throw new Error('invalid format: ' + format);\n }\n verify_point(pk);\n}\nexport function sign_ecdsa(seckey, message) {\n const msg = serialize_bytes(message);\n const sig = secp256k1.sign(msg, seckey).toDERRawBytes();\n return Buff.bytes(sig);\n}\nexport function sign_bip340(seckey, message) {\n const msg = serialize_bytes(message);\n const sig = schnorr.sign(msg, seckey);\n return serialize_bytes(sig);\n}\nexport function verify_ecdsa(signature, message, pubkey) {\n const sig = serialize_bytes(signature);\n const msg = serialize_bytes(message);\n const pk = serialize_pubkey(pubkey, 'ecdsa');\n return secp256k1.verify(sig, msg, pk);\n}\nexport function verify_bip340(signature, message, pubkey) {\n const sig = serialize_bytes(signature);\n const msg = serialize_bytes(message);\n const pk = serialize_pubkey(pubkey, 'bip340');\n return schnorr.verify(sig, msg, pk);\n}\nexport function verify_point(pubkey) {\n try {\n const pt = lift_point(pubkey);\n pt.assertValidity();\n }\n catch (err) {\n throw new Error('invalid secp256k1 point: ' + pubkey);\n }\n}\nexport function lift_point(pubkey) {\n try {\n const pk = serialize_pubkey(pubkey, 'ecdsa');\n return secp256k1.Point.fromHex(pk);\n }\n catch (err) {\n throw new Error('invalid pubkey: ' + pubkey);\n }\n}\nexport function serialize_pubkey(pubkey, format) {\n try {\n const pk = serialize_bytes(pubkey);\n if (pk.length === 33 && format === 'bip340') {\n return pk.slice(1);\n }\n else if (pk.length === 32 && format === 'ecdsa') {\n const prefix = Buff.num(0x02, 1);\n return Buff.join([prefix, pk]);\n }\n else {\n return pk;\n }\n }\n catch (err) {\n throw new Error('invalid pubkey: ' + String(pubkey));\n }\n}\nexport function get_pubkey_format(pubkey) {\n const pk = serialize_bytes(pubkey);\n if (pk.length === 33)\n return 'ecdsa';\n if (pk.length === 32)\n return 'bip340';\n throw new Error('invalid pubkey: ' + String(pubkey));\n}\nexport function serialize_bytes(bytes) {\n try {\n return Buff.bytes(bytes);\n }\n catch (err) {\n throw new Error('invalid bytes: ' + String(bytes));\n }\n}\n","/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://datatracker.ietf.org/doc/html/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from \"./_md.js\";\nimport { clean, createHasher, rotl } from \"./utils.js\";\n/** Initial SHA1 state */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n// Reusable temporary buffer\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n/** SHA1 legacy hash class. */\nexport class SHA1 extends HashMD {\n constructor() {\n super(64, 20, 8, false);\n this.A = SHA1_IV[0] | 0;\n this.B = SHA1_IV[1] | 0;\n this.C = SHA1_IV[2] | 0;\n this.D = SHA1_IV[3] | 0;\n this.E = SHA1_IV[4] | 0;\n }\n get() {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n set(A, B, C, D, E) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n }\n else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n }\n else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n }\n else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n this.set(A, B, C, D, E);\n }\n roundClean() {\n clean(SHA1_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */\nexport const sha1 = /* @__PURE__ */ createHasher(() => new SHA1());\n/** Per-round constants */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));\n/** md5 initial state: same as sha1, but 4 u32 instead of 5. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n// Reusable temporary buffer\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n/** MD5 legacy hash class. */\nexport class MD5 extends HashMD {\n constructor() {\n super(64, 16, 8, true);\n this.A = MD5_IV[0] | 0;\n this.B = MD5_IV[1] | 0;\n this.C = MD5_IV[2] | 0;\n this.D = MD5_IV[3] | 0;\n }\n get() {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n set(A, B, C, D) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g, s;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n s = [7, 12, 17, 22];\n }\n else if (i < 32) {\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n s = [5, 9, 14, 20];\n }\n else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n s = [4, 11, 16, 23];\n }\n else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n s = [6, 10, 15, 21];\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, s[i % 4]);\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n this.set(A, B, C, D);\n }\n roundClean() {\n clean(MD5_W);\n }\n destroy() {\n this.set(0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n */\nexport const md5 = /* @__PURE__ */ createHasher(() => new MD5());\n// RIPEMD-160\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++)\n for (let j of res)\n j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction ripemd_f(group, x, y, z) {\n if (group === 0)\n return x ^ y ^ z;\n if (group === 1)\n return (x & y) | (~x & z);\n if (group === 2)\n return (x | ~y) ^ z;\n if (group === 3)\n return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable temporary buffer\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\nexport class RIPEMD160 extends HashMD {\n constructor() {\n super(64, 20, 8, true);\n this.h0 = 0x67452301 | 0;\n this.h1 = 0xefcdab89 | 0;\n this.h2 = 0x98badcfe | 0;\n this.h3 = 0x10325476 | 0;\n this.h4 = 0xc3d2e1f0 | 0;\n }\n get() {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n set(h0, h1, h2, h3, h4) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);\n }\n roundClean() {\n clean(BUF_160);\n }\n destroy() {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\n */\nexport const ripemd160 = /* @__PURE__ */ createHasher(() => new RIPEMD160());\n//# sourceMappingURL=legacy.js.map","import { Buff } from '@vbyte/buff';\nimport { hmac as noble_hmac } from '@noble/hashes/hmac';\nimport { pbkdf2 as noble_pbkdf2 } from '@noble/hashes/pbkdf2';\nimport { ripemd160 as noble_r160 } from '@noble/hashes/legacy';\nimport { sha256 as noble_s256, sha512 as noble_s512 } from '@noble/hashes/sha2';\nexport function hash160(...input) {\n const buffer = Buff.join(input);\n const digest = noble_r160(noble_s256(buffer));\n return new Buff(digest);\n}\nexport function sha256(...input) {\n const buffer = Buff.join(input);\n const digest = noble_s256(buffer);\n return new Buff(digest);\n}\nexport function hash256(...input) {\n const buffer = Buff.join(input);\n const digest = noble_s256(noble_s256(buffer));\n return new Buff(digest);\n}\nexport function hashtag(tag) {\n const hash = sha256(Buff.str(tag));\n return Buff.join([hash, hash]);\n}\nexport function hash340(tag, ...input) {\n const htag = hashtag(tag);\n const data = input.map(e => new Buff(e));\n const pimg = Buff.join([htag, ...data]);\n return sha256(pimg);\n}\nexport function hmac256(key, ...input) {\n const mask = new Buff(key);\n const buffer = Buff.join(input);\n const digest = noble_hmac(noble_s256, mask, buffer);\n return new Buff(digest);\n}\nexport function hmac512(key, ...input) {\n const mask = new Buff(key);\n const buffer = Buff.join(input);\n const digest = noble_hmac(noble_s512, mask, buffer);\n return new Buff(digest);\n}\nexport function pkdf256(secret, salt, options) {\n const { c = 1, dk_len = 32 } = options ?? {};\n const sec_u8 = new Buff(secret);\n const salt_u8 = new Buff(salt);\n const digest = noble_pbkdf2(noble_s256, sec_u8, salt_u8, { c, dkLen: dk_len });\n return new Buff(digest);\n}\nexport function pkdf512(secret, salt, options) {\n const { c = 1, dk_len = 32 } = options ?? {};\n const sec_u8 = new Buff(secret);\n const salt_u8 = new Buff(salt);\n const digest = noble_pbkdf2(noble_s512, sec_u8, salt_u8, { c, dkLen: dk_len });\n return new Buff(digest);\n}\n","/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nfunction isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\nfunction isArrayOf(isString, arr) {\n if (!Array.isArray(arr))\n return false;\n if (arr.length === 0)\n return true;\n if (isString) {\n return arr.every((item) => typeof item === 'string');\n }\n else {\n return arr.every((item) => Number.isSafeInteger(item));\n }\n}\n// no abytes: seems to have 10% slowdown. Why?!\nfunction afn(input) {\n if (typeof input !== 'function')\n throw new Error('function expected');\n return true;\n}\nfunction astr(label, input) {\n if (typeof input !== 'string')\n throw new Error(`${label}: string expected`);\n return true;\n}\nfunction anumber(n) {\n if (!Number.isSafeInteger(n))\n throw new Error(`invalid integer: ${n}`);\n}\nfunction aArr(input) {\n if (!Array.isArray(input))\n throw new Error('array expected');\n}\nfunction astrArr(label, input) {\n if (!isArrayOf(true, input))\n throw new Error(`${label}: array of strings expected`);\n}\nfunction anumArr(label, input) {\n if (!isArrayOf(false, input))\n throw new Error(`${label}: array of numbers expected`);\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction chain(...args) {\n const id = (a) => a;\n // Wrap call in closure so JIT can inline calls\n const wrap = (a, b) => (c) => a(b(c));\n // Construct chain of args[-1].encode(args[-2].encode([...]))\n const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n // Construct chain of args[0].decode(args[1].decode(...))\n const decode = args.map((x) => x.decode).reduce(wrap, id);\n return { encode, decode };\n}\n/**\n * Encodes integer radix representation to array of strings using alphabet and back.\n * Could also be array of strings.\n * @__NO_SIDE_EFFECTS__\n */\nfunction alphabet(letters) {\n // mapping 1 to \"b\"\n const lettersA = typeof letters === 'string' ? letters.split('') : letters;\n const len = lettersA.length;\n astrArr('alphabet', lettersA);\n // mapping \"b\" to 1\n const indexes = new Map(lettersA.map((l, i) => [l, i]));\n return {\n encode: (digits) => {\n aArr(digits);\n return digits.map((i) => {\n if (!Number.isSafeInteger(i) || i < 0 || i >= len)\n throw new Error(`alphabet.encode: digit index outside alphabet \"${i}\". Allowed: ${letters}`);\n return lettersA[i];\n });\n },\n decode: (input) => {\n aArr(input);\n return input.map((letter) => {\n astr('alphabet.decode', letter);\n const i = indexes.get(letter);\n if (i === undefined)\n throw new Error(`Unknown letter: \"${letter}\". Allowed: ${letters}`);\n return i;\n });\n },\n };\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction join(separator = '') {\n astr('join', separator);\n return {\n encode: (from) => {\n astrArr('join.decode', from);\n return from.join(separator);\n },\n decode: (to) => {\n astr('join.decode', to);\n return to.split(separator);\n },\n };\n}\n/**\n * Pad strings array so it has integer number of bits\n * @__NO_SIDE_EFFECTS__\n */\nfunction padding(bits, chr = '=') {\n anumber(bits);\n astr('padding', chr);\n return {\n encode(data) {\n astrArr('padding.encode', data);\n while ((data.length * bits) % 8)\n data.push(chr);\n return data;\n },\n decode(input) {\n astrArr('padding.decode', input);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('padding: invalid, string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n const last = end - 1;\n const byte = last * bits;\n if (byte % 8 === 0)\n throw new Error('padding: invalid, string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction normalize(fn) {\n afn(fn);\n return { encode: (from) => from, decode: (to) => fn(to) };\n}\n/**\n * Slow: O(n^2) time complexity\n */\nfunction convertRadix(data, from, to) {\n // base 1 is impossible\n if (from < 2)\n throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);\n if (to < 2)\n throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);\n aArr(data);\n if (!data.length)\n return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data, (d) => {\n anumber(d);\n if (d < 0 || d >= from)\n throw new Error(`invalid integer: ${d}`);\n return d;\n });\n const dlen = digits.length;\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < dlen; i++) {\n const digit = digits[i];\n const fromCarry = from * carry;\n const digitBase = fromCarry + digit;\n if (!Number.isSafeInteger(digitBase) ||\n fromCarry / from !== carry ||\n digitBase - digit !== fromCarry) {\n throw new Error('convertRadix: carry overflow');\n }\n const div = digitBase / to;\n carry = digitBase % to;\n const rounded = Math.floor(div);\n digits[i] = rounded;\n if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done)\n continue;\n else if (!rounded)\n pos = i;\n else\n done = false;\n }\n res.push(carry);\n if (done)\n break;\n }\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++)\n res.push(0);\n return res.reverse();\n}\nconst gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));\nconst radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to));\nconst powers = /* @__PURE__ */ (() => {\n let res = [];\n for (let i = 0; i < 40; i++)\n res.push(2 ** i);\n return res;\n})();\n/**\n * Implemented with numbers, because BigInt is 5x slower\n */\nfunction convertRadix2(data, from, to, padding) {\n aArr(data);\n if (from <= 0 || from > 32)\n throw new Error(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32)\n throw new Error(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);\n }\n let carry = 0;\n let pos = 0; // bitwise position in current element\n const max = powers[from];\n const mask = powers[to] - 1;\n const res = [];\n for (const n of data) {\n anumber(n);\n if (n >= max)\n throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32)\n throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to)\n res.push(((carry >> (pos - to)) & mask) >>> 0);\n const pow = powers[pos];\n if (pow === undefined)\n throw new Error('invalid carry');\n carry &= pow - 1; // clean carry, otherwise it will cause overflow\n }\n carry = (carry << (to - pos)) & mask;\n if (!padding && pos >= from)\n throw new Error('Excess padding');\n if (!padding && carry > 0)\n throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0)\n res.push(carry >>> 0);\n return res;\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix(num) {\n anumber(num);\n const _256 = 2 ** 8;\n return {\n encode: (bytes) => {\n if (!isBytes(bytes))\n throw new Error('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), _256, num);\n },\n decode: (digits) => {\n anumArr('radix.decode', digits);\n return Uint8Array.from(convertRadix(digits, num, _256));\n },\n };\n}\n/**\n * If both bases are power of same number (like `2**8 <-> 2**64`),\n * there is a linear algorithm. For now we have implementation for power-of-two bases only.\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix2(bits, revPadding = false) {\n anumber(bits);\n if (bits <= 0 || bits > 32)\n throw new Error('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new Error('radix2: carry overflow');\n return {\n encode: (bytes) => {\n if (!isBytes(bytes))\n throw new Error('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits) => {\n anumArr('radix2.decode', digits);\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\nfunction unsafeWrapper(fn) {\n afn(fn);\n return function (...args) {\n try {\n return fn.apply(null, args);\n }\n catch (e) { }\n };\n}\nfunction checksum(len, fn) {\n anumber(len);\n afn(fn);\n return {\n encode(data) {\n if (!isBytes(data))\n throw new Error('checksum.encode: input should be Uint8Array');\n const sum = fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(sum, data.length);\n return res;\n },\n decode(data) {\n if (!isBytes(data))\n throw new Error('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const oldChecksum = data.slice(-len);\n const newChecksum = fn(payload).slice(0, len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i])\n throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\n// prettier-ignore\nexport const utils = {\n alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,\n};\n// RFC 4648 aka RFC 3548\n// ---------------------\n/**\n * base16 encoding from RFC 4648.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\n/**\n * base32 encoding from RFC 4648. Has padding.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''));\n/**\n * base32 encoding from RFC 4648. No padding.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), join(''));\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''));\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), join(''));\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * https://www.crockford.com/base32.html\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')));\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// prettier-ignore\nconst hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === 'function' &&\n typeof Uint8Array.fromBase64 === 'function')();\nconst decodeBase64Builtin = (s, isUrl) => {\n astr('base64', s);\n const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;\n const alphabet = isUrl ? 'base64url' : 'base64';\n if (s.length > 0 && !re.test(s))\n throw new Error('invalid base64');\n return Uint8Array.fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n/**\n * base64 from RFC 4648. Padded.\n * Use `base64nopad` for unpadded version.\n * Also check out `base64url`, `base64urlnopad`.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64 = hasBase64Builtin ? {\n encode(b) { abytes(b); return b.toBase64(); },\n decode(s) { return decodeBase64Builtin(s, false); },\n} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join(''));\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), join(''));\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url = hasBase64Builtin ? {\n encode(b) { abytes(b); return b.toBase64({ alphabet: 'base64url' }); },\n decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join(''));\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), join(''));\n// base58 code\n// -----------\nconst genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => chain(radix(58), alphabet(abc), join(''));\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * base58.decode('01abcdef');\n * // => '3UhJW'\n * ```\n */\nexport const base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');\n/**\n * base58: flickr version. Check out `base58`.\n */\nexport const base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ');\n/**\n * base58: XRP version. Check out `base58`.\n */\nexport const base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz');\n// Data len (index) -> encoded block len\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n */\nexport const base58xmr = {\n encode(data) {\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');\n }\n return res;\n },\n decode(str) {\n let res = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0)\n throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n};\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n */\nexport const createBase58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), base58);\n/**\n * Use `createBase58check` instead.\n * @deprecated\n */\nexport const base58check = createBase58check;\nconst BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre) {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1)\n chk ^= POLYMOD_GENERATORS[i];\n }\n return chk;\n}\nfunction bechChecksum(prefix, words, encodingConst = 1) {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126)\n throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++)\n chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words)\n chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++)\n chk = bech32Polymod(chk);\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]], 30, 5, false));\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction genBech32(encoding) {\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n function encode(prefix, words, limit = 90) {\n astr('bech32.encode prefix', prefix);\n if (isBytes(words))\n words = Array.from(words);\n anumArr('bech32.encode', words);\n const plen = prefix.length;\n if (plen === 0)\n throw new TypeError(`Invalid prefix length ${plen}`);\n const actualLength = plen + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n const lowered = prefix.toLowerCase();\n const sum = bechChecksum(lowered, words, ENCODING_CONST);\n return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`;\n }\n function decode(str, limit = 90) {\n astr('bech32.decode input', str);\n const slen = str.length;\n if (slen < 8 || (limit !== false && slen > limit))\n throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);\n // don't allow mixed case\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n const sepIndex = lowered.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = lowered.slice(0, sepIndex);\n const data = lowered.slice(sepIndex + 1);\n if (data.length < 6)\n throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(data).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!data.endsWith(sum))\n throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n const decodeUnsafe = unsafeWrapper(decode);\n function decodeToBytes(str) {\n const { prefix, words } = decode(str, false);\n return { prefix, words, bytes: fromWords(words) };\n }\n function encodeFromBytes(prefix, bytes) {\n return encode(prefix, toWords(bytes));\n }\n return {\n encode,\n decode,\n encodeFromBytes,\n decodeToBytes,\n decodeUnsafe,\n fromWords,\n fromWordsUnsafe,\n toWords,\n };\n}\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32 = genBech32('bech32');\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32m = genBech32('bech32m');\n/**\n * UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8 = {\n encode: (data) => new TextDecoder().decode(data),\n decode: (str) => new TextEncoder().encode(str),\n};\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === 'function' &&\n typeof Uint8Array.fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin = {\n encode(data) { abytes(data); return data.toHex(); },\n decode(s) { astr('hex', s); return Uint8Array.fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex = hasHexBuiltin\n ? hexBuiltin\n : chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => {\n if (typeof s !== 'string' || s.length % 2 !== 0)\n throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);\n return s.toLowerCase();\n }));\n// prettier-ignore\nconst CODERS = {\n utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\nconst coderTypeError = 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';\n/** @deprecated */\nexport const bytesToString = (type, bytes) => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))\n throw new TypeError(coderTypeError);\n if (!isBytes(bytes))\n throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\n/** @deprecated */\nexport const str = bytesToString; // as in python, but for bytes only\n/** @deprecated */\nexport const stringToBytes = (type, str) => {\n if (!CODERS.hasOwnProperty(type))\n throw new TypeError(coderTypeError);\n if (typeof str !== 'string')\n throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str);\n};\n/** @deprecated */\nexport const bytes = stringToBytes;\n//# sourceMappingURL=index.js.map","import { sha256 } from '@noble/hashes/sha2';\nimport { Assert } from './assert.js';\nimport { createBase58check, base64, base64urlnopad, bech32, bech32m } from '@scure/base';\nexport var B58chk;\n(function (B58chk) {\n B58chk.encode = (data) => {\n Assert.is_u8a(data);\n return createBase58check(sha256).encode(data);\n };\n B58chk.decode = (data) => {\n Assert.is_base58(data);\n return createBase58check(sha256).decode(data);\n };\n})(B58chk || (B58chk = {}));\nexport var Base64;\n(function (Base64) {\n Base64.encode = (data) => {\n Assert.is_u8a(data);\n return base64.encode(data);\n };\n Base64.decode = (data) => {\n Assert.is_base64(data);\n return base64.decode(data);\n };\n})(Base64 || (Base64 = {}));\nexport var B64url;\n(function (B64url) {\n B64url.encode = (data) => {\n Assert.is_u8a(data);\n return base64urlnopad.encode(data);\n };\n B64url.decode = (data) => {\n Assert.is_b64url(data);\n return base64urlnopad.decode(data);\n };\n})(B64url || (B64url = {}));\nexport var Bech32;\n(function (Bech32) {\n Bech32.to_words = bech32.toWords;\n Bech32.to_bytes = bech32.fromWords;\n Bech32.encode = (prefix, words, limit = false) => {\n assert_prefix(prefix);\n assert_words(words);\n return bech32.encode(prefix, words, limit);\n };\n Bech32.decode = (data, limit = false) => {\n Assert.is_bech32(data);\n return bech32.decode(data, limit);\n };\n})(Bech32 || (Bech32 = {}));\nexport var Bech32m;\n(function (Bech32m) {\n Bech32m.to_words = bech32m.toWords;\n Bech32m.to_bytes = bech32m.fromWords;\n Bech32m.encode = (prefix, words, limit = false) => {\n assert_prefix(prefix);\n assert_words(words);\n return bech32m.encode(prefix, words, limit);\n };\n Bech32m.decode = (data, limit = false) => {\n Assert.is_bech32(data);\n return bech32m.decode(data, limit);\n };\n})(Bech32m || (Bech32m = {}));\nfunction assert_prefix(value) {\n if (typeof value !== 'string' || value.length === 0) {\n throw new Error(`invalid prefix: ${String(value)}`);\n }\n}\nfunction assert_words(value) {\n if (!(Array.isArray(value) &&\n value.every(word => typeof word === 'number'))) {\n throw new Error(`invalid words: ${String(value)}`);\n }\n}\n","import { Buff } from \"@vbyte/buff\";\n\nimport { Assert, B58chk, Bech32, Bech32m } from \"@vbyte/micro-lib\";\n\nimport type { AddressFormat, EncoderConfig } from \"@/types/address.js\";\n\nconst ENCODING_REGEX = {\n\tbase58: /^[13mn2][a-km-zA-HJ-NP-Z1-9]{25,34}$/,\n\tbech32: /^(bc|tb|bcrt)1q[ac-hj-np-z02-9]{6,87}$/,\n\tbech32m: /^(bc|tb|bcrt)1p[ac-hj-np-z02-9]{6,87}$/,\n};\n\nconst VERSION = {\n\tbech32: 0,\n\tbech32m: 1,\n};\n\n/**\n * Decode an address.\n *\n * @param address - The address to decode.\n * @returns The decoded address.\n */\nexport function decode_address(address: string): EncoderConfig {\n\t// Get the address format.\n\tconst format = get_address_format(address);\n\t// If the format is not found, throw an error.\n\tif (format === null)\n\t\tthrow new Error(`unrecognized address format: ${address}`);\n\t// Decode the address based on the format.\n\tif (format === \"base58\") return base58_decode(address);\n\tif (format === \"bech32\") return bech32_decode(address);\n\tif (format === \"bech32m\") return bech32m_decode(address);\n\t// If we didn't find a matching decoder, throw.\n\tthrow new Error(\"unable to find a matching address configuration\");\n}\n\n/**\n * Encode an address.\n *\n * @param address - The address to encode.\n * @returns The encoded address as a string, or null if the address is not\n * recognized.\n */\nexport function encode_address(config: EncoderConfig): string {\n\t// Encode the address based on the format.\n\tif (config.format === \"base58\") return base58_encode(config);\n\tif (config.format === \"bech32\") return bech32_encode(config);\n\tif (config.format === \"bech32m\") return bech32m_encode(config);\n\t// If the format is not recognized, throw an error.\n\tthrow new Error(`unrecognized encoding format: ${config.format}`);\n}\n\n/**\n * Get the encoding type for a given address.\n *\n * @param address - The address to get the encoding type for.\n * @returns The encoding type, or null if the address is not recognized.\n */\nfunction get_address_format(address: string): AddressFormat | null {\n\t// For each encoding type, check if the address matches the regex.\n\tfor (const [format, regex] of Object.entries(ENCODING_REGEX)) {\n\t\t// If the address matches the regex, return the format.\n\t\tif (regex.test(address)) return format as AddressFormat;\n\t\t// If the address does not match the regex, continue to the next encoding type.\n\t}\n\t// If no encoding type matches the address, return null.\n\treturn null;\n}\n\n/**\n * Encode data as a base58 string.\n *\n * @param config - The encoder configuration.\n * @returns The encoded base58 string.\n */\nfunction base58_encode(config: EncoderConfig): string {\n\t// Assert the format is correct.\n\tAssert.ok(config.format === \"base58\", \"encoding mismatch\");\n\t// Assert the version is specified.\n\tAssert.exists(config.version, \"must specify a version\");\n\t// Convert the data into bytes with a version prefix.\n\tconst bytes = Buff.join([config.version, config.data]);\n\t// Encode the data as a base58 string.\n\treturn B58chk.encode(bytes);\n}\n\n/**\n * Decode data as a base58 string.\n *\n * @param encoded - The base58 string to decode.\n * @returns The decoded data.\n */\nfunction base58_decode(encoded: string): EncoderConfig {\n\t// Decode the encoded data.\n\tconst bytes = B58chk.decode(encoded);\n\t// Get the data from the decoded bytes.\n\tconst data = bytes.slice(1);\n\t// Get the version from the decoded bytes.\n\tconst version = bytes[0];\n\t// Return the decoded address.\n\treturn { data, format: \"base58\", version };\n}\n\n/**\n * Encode data as a bech32 string.\n *\n * @param config - The encoder configuration.\n * @returns The encoded bech32 string.\n */\nfunction bech32_encode(config: EncoderConfig): string {\n\t// Assert the format is correct.\n\tAssert.ok(config.format === \"bech32\", \"encoding mismatch\");\n\t// Assert the prefix is specified.\n\tAssert.exists(config.prefix, \"prefix is required\");\n\t// Convert the data into bytes.\n\tconst bytes = Buff.bytes(config.data);\n\t// Convert the bytes into words.\n\tconst words = Bech32.to_words(bytes);\n\t// Encode the data as a bech32 string.\n\treturn Bech32.encode(config.prefix, [VERSION.bech32, ...words]);\n}\n\n/**\n * Decode data as a bech32 string.\n *\n * @param encoded - The bech32 string to decode.\n * @returns The decoded data.\n */\nfunction bech32_decode(encoded: string): EncoderConfig {\n\t// Decode the encoded data.\n\tconst { prefix, words } = Bech32.decode(encoded);\n\t// Get the version and rest of the words.\n\tconst [version, ...rest] = words;\n\t// Assert the version is correct.\n\tAssert.ok(version === VERSION.bech32, \"bech32 version mismatch\");\n\t// Convert the rest of the words into bytes.\n\tconst data = Bech32.to_bytes(rest);\n\t// Return the decoded address.\n\treturn { data, format: \"bech32\", prefix, version };\n}\n\n/**\n * Encode data as a bech32 string.\n *\n * @param config - The encoder configuration.\n * @returns The encoded bech32 string.\n */\nfunction bech32m_encode(config: EncoderConfig): string {\n\t// Assert the format is correct.\n\tAssert.ok(config.format === \"bech32m\", \"encoding mismatch\");\n\t// Assert the prefix is specified.\n\tAssert.exists(config.prefix, \"prefix is required\");\n\t// Convert the data into bytes.\n\tconst bytes = Buff.bytes(config.data);\n\t// Convert the bytes into words.\n\tconst words = Bech32m.to_words(bytes);\n\t// Encode the data as a bech32m string.\n\treturn Bech32m.encode(config.prefix, [VERSION.bech32m, ...words]);\n}\n\n/**\n * Decode data as a bech32 string.\n *\n * @param encoded - The bech32 string to decode.\n * @returns The decoded data.\n */\nfunction bech32m_decode(encoded: string): EncoderConfig {\n\t// Decode the encoded data.\n\tconst { prefix, words } = Bech32m.decode(encoded);\n\t// Get the version and rest of the words.\n\tconst [version, ...rest] = words;\n\t// Assert the version is correct.\n\tAssert.ok(version === VERSION.bech32m, \"bech32m version mismatch\");\n\t// Convert the rest of the words into bytes.\n\tconst data = Bech32m.to_bytes(rest);\n\t// Return the decoded address.\n\treturn { data, format: \"bech32m\", prefix, version };\n}\n","import type { AddressType, ScriptInfo } from \"@/types/index.js\";\n\n/**\n * Get the address script.\n *\n * @param script_key - The script key.\n * @param script_type - The script type.\n * @returns The address script.\n */\nexport function get_address_script(\n\tscript_key: string,\n\tscript_type: AddressType,\n): ScriptInfo {\n\tswitch (script_type) {\n\t\tcase \"p2pkh\":\n\t\t\treturn get_p2pkh_script(script_key);\n\t\tcase \"p2sh\":\n\t\t\treturn get_p2sh_script(script_key);\n\t\tcase \"p2wpkh\":\n\t\t\treturn get_p2w_pkh_script(script_key);\n\t\tcase \"p2wsh\":\n\t\t\treturn get_p2w_sh_script(script_key);\n\t\tcase \"p2tr\":\n\t\t\treturn get_p2tr_script(script_key);\n\t\tdefault:\n\t\t\tthrow new Error(`unrecognized script type: ${script_type}`);\n\t}\n}\n\nfunction get_p2pkh_script(script_key: string) {\n\treturn {\n\t\thex: `76a914${script_key}88ac`,\n\t\tasm: [\"OP_DUP\", \"OP_HASH160\", script_key, \"OP_EQUALVERIFY\", \"OP_CHECKSIG\"],\n\t};\n}\n\nfunction get_p2sh_script(script_key: string) {\n\treturn {\n\t\thex: `a914${script_key}87`,\n\t\tasm: [\"OP_HASH160\", script_key, \"OP_EQUAL\"],\n\t};\n}\n\nfunction get_p2w_pkh_script(script_key: string) {\n\treturn {\n\t\thex: `0014${script_key}`,\n\t\tasm: [\"OP_0\", script_key],\n\t};\n}\n\nfunction get_p2w_sh_script(script_key: string) {\n\treturn {\n\t\thex: `0020${script_key}`,\n\t\tasm: [\"OP_0\", script_key],\n\t};\n}\n\nfunction get_p2tr_script(script_key: string) {\n\treturn {\n\t\thex: `5120${script_key}`,\n\t\tasm: [\"OP_1\", script_key],\n\t};\n}\n","import { Buff } from \"@vbyte/buff\";\nimport type {\n\tAddressConfig,\n\tAddressConfigEntry,\n\tAddressInfo,\n\tChainNetwork,\n\tLockScriptType,\n} from \"@/types/index.js\";\nimport { decode_address } from \"./encode.js\";\nimport { get_address_script } from \"./script.js\";\n\nconst CONFIG_TABLE: AddressConfigEntry[] = [\n\t[\"1\", \"p2pkh\", \"main\", 20, \"base58\", 0x00],\n\t[\"3\", \"p2sh\", \"main\", 20, \"base58\", 0x05],\n\t[\"m\", \"p2pkh\", \"testnet\", 20, \"base58\", 0x6f],\n\t[\"n\", \"p2pkh\", \"testnet\", 20, \"base58\", 0x6f],\n\t[\"2\", \"p2sh\", \"testnet\", 20, \"base58\", 0xc4],\n\t[\"m\", \"p2pkh\", \"regtest\", 20, \"base58\", 0x6f],\n\t[\"n\", \"p2pkh\", \"regtest\", 20, \"base58\", 0x6f],\n\t[\"2\", \"p2sh\", \"regtest\", 20, \"base58\", 0xc4],\n\t[\"bc\", \"p2wpkh\", \"main\", 20, \"bech32\", 0],\n\t[\"tb\", \"p2wpkh\", \"testnet\", 20, \"bech32\", 0],\n\t[\"bcrt\", \"p2wpkh\", \"regtest\", 20, \"bech32\", 0],\n\t[\"bc\", \"p2wsh\", \"main\", 32, \"bech32\", 0],\n\t[\"tb\", \"p2wsh\", \"testnet\", 32, \"bech32\", 0],\n\t[\"bcrt\", \"p2wsh\", \"regtest\", 32, \"bech32\", 0],\n\t[\"bc\", \"p2tr\", \"main\", 32, \"bech32m\", 1],\n\t[\"tb\", \"p2tr\", \"testnet\", 32, \"bech32m\", 1],\n\t[\"bcrt\", \"p2tr\", \"regtest\", 32, \"bech32m\", 1],\n];\n\n/**\n * Lookup an address configuration by its type and network.\n *\n * @param address_network - The network of the address.\n * @param address_type - The type of the address.\n * @returns The address information, or null if the address is not recognized.\n */\nexport function get_address_config(\n\taddress_network: ChainNetwork,\n\taddress_type: LockScriptType,\n): AddressConfig | null {\n\t// For each configuration in the table,\n\tfor (const [prefix, type, network, size, format, version] of CONFIG_TABLE) {\n\t\t// Check if the address matches the configuration\n\t\tif (type === address_type && network === address_network) {\n\t\t\t// Return the address configuration.\n\t\t\treturn { type, prefix, network, size, format, version };\n\t\t}\n\t}\n\t// If no configuration matches the address, return null.\n\treturn null;\n}\n\n/**\n * Parse an address into its data and script.\n *\n * @param address - The address to parse.\n * @returns The address data and script.\n */\nexport function get_address_info(address: string): AddressInfo {\n\t// Decode the address.\n\tconst dec = decode_address(address);\n\t// For each configuration in the table,\n\tfor (const [prefix, type, network, size, format, version] of CONFIG_TABLE) {\n\t\t// Check if the address matches the configuration\n\t\tif (format !== dec.format) continue;\n\t\tif (size !== dec.data.length) continue;\n\t\tif (version !== dec.version) continue;\n\n\t\tif (dec.prefix) {\n\t\t\tif (prefix !== dec.prefix) continue;\n\t\t} else {\n\t\t\tif (!address.startsWith(prefix)) continue;\n\t\t}\n\n\t\t// Convert the decoded data into a hex string.\n\t\tconst data = Buff.bytes(dec.data).hex;\n\t\tconst script = get_address_script(data, type);\n\t\t// Return the address configuration and data.\n\t\treturn { data, script, type, prefix, network, size, format, version };\n\t}\n\t// Otherwise, throw an error\n\tthrow new Error(\"address configuration is invalid\");\n}\n","import { Buff, type Bytes } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/micro-lib\";\nimport { hash160 } from \"@vbyte/micro-lib/hash\";\nimport { LOCK_SCRIPT_TYPE } from \"@/const.js\";\nimport { is_p2pkh_script } from \"@/lib/script/lock.js\";\nimport type { AddressInfo, ChainNetwork } from \"@/types/index.js\";\nimport { encode_address } from \"./encode.js\";\nimport { get_address_config, get_address_info } from \"./util.js\";\n\nconst ADDRESS_TYPE = LOCK_SCRIPT_TYPE.P2PKH;\n\nexport namespace P2PKH {\n\texport const create_address = create_p2pkh_address;\n\texport const create_script = create_p2pkh_script;\n\texport const encode_address = encode_p2pkh_address;\n\texport const encode_script = encode_p2pkh_script;\n\texport const decode_address = decode_p2pkh_address;\n\texport const decode_script = decode_p2pkh_script;\n}\n\nfunction create_p2pkh_address(\n\tpubkey: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Create the p2pkh script.\n\tconst script = create_p2pkh_script(pubkey);\n\t// Encode the script as an address.\n\treturn encode_p2pkh_address(script, network);\n}\n\nfunction create_p2pkh_script(pubkey: Bytes): Buff {\n\t// Convert the public key into bytes.\n\tconst bytes = Buff.bytes(pubkey);\n\t// Assert the public key is 33 bytes.\n\tAssert.size(bytes, 33, \"invalid pubkey size\");\n\t// Convert the bytes into a hash.\n\tconst hash = hash160(bytes);\n\t// Return the script.\n\treturn encode_p2pkh_script(hash);\n}\n\nfunction encode_p2pkh_script(pk_hash: Bytes): Buff {\n\treturn Buff.join([\"76a914\", pk_hash, \"88ac\"]);\n}\n\nfunction encode_p2pkh_address(\n\tscript: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Get the public key hash from the script.\n\tconst pk_hash = decode_p2pkh_script(script);\n\t// Get the address configuration.\n\tconst config = get_address_config(network, ADDRESS_TYPE);\n\t// Assert the configuration exists.\n\tAssert.exists(\n\t\tconfig,\n\t\t`unrecognized address config: ${ADDRESS_TYPE} on ${network}`,\n\t);\n\t// Assert the payload size is correct.\n\tAssert.size(\n\t\tpk_hash,\n\t\tconfig.size,\n\t\t`invalid payload size: ${pk_hash.length} !== ${config.size}`,\n\t);\n\t// Encode the address.\n\treturn encode_address({\n\t\tdata: pk_hash,\n\t\tformat: \"base58\",\n\t\tversion: config.version,\n\t});\n}\n\nfunction decode_p2pkh_address(address: string): AddressInfo {\n\t// Parse the address.\n\tconst parsed = get_address_info(address);\n\t// Assert the address type is correct.\n\tAssert.ok(\n\t\tparsed.type === \"p2pkh\",\n\t\t`address type mismatch: ${parsed.type} !== ${ADDRESS_TYPE}`,\n\t);\n\t// Return the parsed address.\n\treturn parsed;\n}\n\nfunction decode_p2pkh_script(script: Bytes): Buff {\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Assert the script is a p2pkh script.\n\tAssert.ok(is_p2pkh_script(script), `invalid p2pkh script`);\n\t// Return the public key hash from the script.\n\treturn bytes.slice(3, 23);\n}\n","import { Buff, type Bytes } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/micro-lib\";\nimport { hash160 } from \"@vbyte/micro-lib/hash\";\nimport { LOCK_SCRIPT_TYPE } from \"@/const.js\";\nimport { is_p2sh_script } from \"@/lib/script/lock.js\";\nimport type { AddressInfo, ChainNetwork } from \"@/types/index.js\";\nimport { encode_address } from \"./encode.js\";\nimport { get_address_config, get_address_info } from \"./util.js\";\n\nconst ADDRESS_TYPE = LOCK_SCRIPT_TYPE.P2SH;\n\nexport namespace P2SH {\n\texport const create_address = create_p2sh_address;\n\texport const create_script = create_p2sh_script;\n\texport const encode_address = encode_p2sh_address;\n\texport const encode_script = encode_p2sh_script;\n\texport const decode_address = decode_p2sh_address;\n\texport const decode_script = decode_p2sh_script;\n}\n\nfunction create_p2sh_address(\n\tscript: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Convert the bytes into a hash.\n\tconst hash = hash160(bytes);\n\t// Create the p2sh script.\n\tconst p2sh_script = encode_p2sh_script(hash);\n\t// Encode the address.\n\treturn encode_p2sh_address(p2sh_script, network);\n}\n\nfunction create_p2sh_script(script: Bytes): Buff {\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Convert the bytes into a hash.\n\tconst hash = hash160(bytes);\n\t// Return the script.\n\treturn encode_p2sh_script(hash);\n}\n\nfunction encode_p2sh_script(script_hash: Bytes): Buff {\n\treturn Buff.join([\"a914\", script_hash, \"87\"]);\n}\n\nfunction encode_p2sh_address(\n\tscript_pk: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Get the script hash from the script.\n\tconst script_hash = decode_p2sh_script(script_pk);\n\t// Get the address configuration.\n\tconst config = get_address_config(network, ADDRESS_TYPE);\n\t// Assert the configuration exists.\n\tAssert.exists(\n\t\tconfig,\n\t\t`unrecognized address config: ${ADDRESS_TYPE} on ${network}`,\n\t);\n\t// Assert the payload size is correct.\n\tAssert.size(\n\t\tscript_hash,\n\t\tconfig.size,\n\t\t`invalid payload size: ${script_hash.length} !== ${config.size}`,\n\t);\n\t// Encode the address.\n\treturn encode_address({\n\t\tdata: script_hash,\n\t\tformat: \"base58\",\n\t\tversion: config.version,\n\t});\n}\n\nfunction decode_p2sh_address(address: string): AddressInfo {\n\t// Parse the address.\n\tconst parsed = get_address_info(address);\n\t// Assert the address type is correct.\n\tAssert.ok(\n\t\tparsed.type === \"p2sh\",\n\t\t`address type mismatch: ${parsed.type} !== ${ADDRESS_TYPE}`,\n\t);\n\t// Return the parsed address.\n\treturn parsed;\n}\n\nfunction decode_p2sh_script(script: Bytes): Buff {\n\t// Assert the script is a p2sh script.\n\tAssert.ok(is_p2sh_script(script), `invalid p2sh script`);\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Return the script hash from the script.\n\treturn bytes.slice(2, 22);\n}\n","import { Buff, type Bytes } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/micro-lib\";\nimport { LOCK_SCRIPT_TYPE } from \"@/const.js\";\nimport { is_p2tr_script } from \"@/lib/script/lock.js\";\nimport type { AddressInfo, ChainNetwork } from \"@/types/index.js\";\nimport { encode_address } from \"./encode.js\";\nimport { get_address_config, get_address_info } from \"./util.js\";\n\nconst ADDRESS_TYPE = LOCK_SCRIPT_TYPE.P2TR;\n\nexport namespace P2TR {\n\texport const create_address = create_p2tr_address;\n\texport const create_script = create_p2tr_script;\n\texport const encode_address = encode_p2tr_address;\n\texport const encode_script = encode_p2tr_script;\n\texport const decode_address = decode_p2tr_address;\n\texport const decode_script = decode_p2tr_script;\n}\n\nfunction create_p2tr_address(\n\tpubkey: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Create the p2tr script.\n\tconst script = create_p2tr_script(pubkey);\n\t// Encode the script as an address.\n\treturn encode_p2tr_address(script, network);\n}\n\nfunction create_p2tr_script(pubkey: Bytes): Buff {\n\t// Convert the public key into bytes.\n\tconst bytes = Buff.bytes(pubkey);\n\t// Assert the public key is 32 bytes.\n\tAssert.size(bytes, 32, \"invalid pubkey size\");\n\t// Return the script.\n\treturn encode_p2tr_script(bytes);\n}\n\nfunction encode_p2tr_script(pubkey: Bytes): Buff {\n\treturn Buff.join([\"5120\", pubkey]);\n}\n\nfunction encode_p2tr_address(\n\tscript_pk: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Get the public key from the script.\n\tconst pubkey = decode_p2tr_script(script_pk);\n\t// Get the address configuration.\n\tconst config = get_address_config(network, ADDRESS_TYPE);\n\t// Assert the configuration exists.\n\tAssert.exists(\n\t\tconfig,\n\t\t`unrecognized address config: ${ADDRESS_TYPE} on ${network}`,\n\t);\n\t// Assert the payload size is correct.\n\tAssert.size(\n\t\tpubkey,\n\t\tconfig.size,\n\t\t`invalid payload size: ${pubkey.length} !== ${config.size}`,\n\t);\n\t// Encode the address.\n\treturn encode_address({\n\t\tdata: pubkey,\n\t\tformat: \"bech32m\",\n\t\tprefix: config.prefix,\n\t});\n}\n\nfunction decode_p2tr_address(address: string): AddressInfo {\n\t// Parse the address.\n\tconst parsed = get_address_info(address);\n\t// Assert the address type is correct.\n\tAssert.ok(\n\t\tparsed.type === \"p2tr\",\n\t\t`address type mismatch: ${parsed.type} !== ${ADDRESS_TYPE}`,\n\t);\n\t// Return the parsed address.\n\treturn parsed;\n}\n\nfunction decode_p2tr_script(script: Bytes): Buff {\n\t// Assert the script is a p2tr script.\n\tAssert.ok(is_p2tr_script(script), `invalid p2tr script`);\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Return the public key from the script.\n\treturn bytes.slice(2, 34);\n}\n","import { Buff, type Bytes } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/micro-lib\";\nimport { hash160 } from \"@vbyte/micro-lib/hash\";\nimport { LOCK_SCRIPT_TYPE } from \"@/const.js\";\nimport { is_p2wpkh_script } from \"@/lib/script/lock.js\";\nimport type { AddressInfo, ChainNetwork } from \"@/types/index.js\";\nimport { encode_address } from \"./encode.js\";\nimport { get_address_config, get_address_info } from \"./util.js\";\n\nconst ADDRESS_TYPE = LOCK_SCRIPT_TYPE.P2WPKH;\n\nexport namespace P2WPKH {\n\texport const create_address = create_p2wpkh_address;\n\texport const create_script = create_p2wpkh_script;\n\texport const encode_address = encode_p2wpkh_address;\n\texport const encode_script = encode_p2wpkh_script;\n\texport const decode_address = decode_p2wpkh_address;\n\texport const decode_script = decode_p2wpkh_script;\n}\n\nfunction create_p2wpkh_address(\n\tpubkey: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Create the p2wpkh script.\n\tconst script = create_p2wpkh_script(pubkey);\n\t// Encode the script as an address.\n\treturn encode_p2wpkh_address(script, network);\n}\n\nfunction create_p2wpkh_script(pubkey: Bytes): Buff {\n\t// Convert the public key into bytes.\n\tconst bytes = Buff.bytes(pubkey);\n\t// Assert the public key is 33 bytes.\n\tAssert.size(bytes, 33, \"invalid pubkey size\");\n\t// Convert the bytes into a hash.\n\tconst hash = hash160(bytes);\n\t// Return the script.\n\treturn encode_p2wpkh_script(hash);\n}\n\nfunction encode_p2wpkh_script(pk_hash: Bytes): Buff {\n\treturn Buff.join([\"0014\", pk_hash]);\n}\n\nfunction encode_p2wpkh_address(\n\tscript_pk: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Get the public key hash from the script.\n\tconst pk_hash = decode_p2wpkh_script(script_pk);\n\t// Get the address configuration.\n\tconst config = get_address_config(network, ADDRESS_TYPE);\n\t// Assert the configuration exists.\n\tAssert.exists(\n\t\tconfig,\n\t\t`unrecognized address config: ${ADDRESS_TYPE} on ${network}`,\n\t);\n\t// Assert the payload size is correct.\n\tAssert.size(\n\t\tpk_hash,\n\t\tconfig.size,\n\t\t`invalid payload size: ${pk_hash.length} !== ${config.size}`,\n\t);\n\t// Encode the address.\n\treturn encode_address({\n\t\tdata: pk_hash,\n\t\tformat: \"bech32\",\n\t\tprefix: config.prefix,\n\t});\n}\n\nfunction decode_p2wpkh_address(address: string): AddressInfo {\n\t// Parse the address.\n\tconst parsed = get_address_info(address);\n\t// Assert the address type is correct.\n\tAssert.ok(\n\t\tparsed.type === \"p2wpkh\",\n\t\t`address type mismatch: ${parsed.type} !== ${ADDRESS_TYPE}`,\n\t);\n\t// Return the parsed address.\n\treturn parsed;\n}\n\nfunction decode_p2wpkh_script(script: Bytes): Buff {\n\t// Assert the script is a p2wpkh script.\n\tAssert.ok(is_p2wpkh_script(script), `invalid p2wpkh script`);\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Return the public key hash from the script.\n\treturn bytes.slice(2, 22);\n}\n","import { Buff, type Bytes } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/micro-lib\";\nimport { sha256 } from \"@vbyte/micro-lib/hash\";\nimport { LOCK_SCRIPT_TYPE } from \"@/const.js\";\nimport { is_p2wsh_script } from \"@/lib/script/lock.js\";\nimport type { AddressInfo, ChainNetwork } from \"@/types/index.js\";\nimport { encode_address } from \"./encode.js\";\nimport { get_address_config, get_address_info } from \"./util.js\";\n\nconst ADDRESS_TYPE = LOCK_SCRIPT_TYPE.P2WSH;\n\nexport namespace P2WSH {\n\texport const create_address = create_p2wsh_address;\n\texport const create_script = create_p2wsh_script;\n\texport const encode_address = encode_p2wsh_address;\n\texport const encode_script = encode_p2wsh_script;\n\texport const decode_address = decode_p2wsh_address;\n\texport const decode_script = decode_p2wsh_script;\n}\n\nfunction create_p2wsh_address(\n\tscript: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Create the p2wsh script.\n\tconst wsh_script = create_p2wsh_script(script);\n\t// Encode the script as an address.\n\treturn encode_p2wsh_address(wsh_script, network);\n}\n\nfunction create_p2wsh_script(script: Bytes): Buff {\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Convert the bytes into a hash.\n\tconst hash = sha256(bytes);\n\t// Return the script.\n\treturn encode_p2wsh_script(hash);\n}\n\nfunction encode_p2wsh_script(script_hash: Bytes): Buff {\n\treturn Buff.join([\"0020\", script_hash]);\n}\n\nfunction encode_p2wsh_address(\n\tscript_pk: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Get the script hash from the script.\n\tconst script_hash = decode_p2wsh_script(script_pk);\n\t// Get the address configuration.\n\tconst config = get_address_config(network, ADDRESS_TYPE);\n\t// Assert the configuration exists.\n\tAssert.exists(\n\t\tconfig,\n\t\t`unrecognized address config: ${ADDRESS_TYPE} on ${network}`,\n\t);\n\t// Assert the payload size is correct.\n\tAssert.size(\n\t\tscript_hash,\n\t\tconfig.size,\n\t\t`invalid payload size: ${script_hash.length} !== ${config.size}`,\n\t);\n\t// Encode the address.\n\treturn encode_address({\n\t\tdata: script_hash,\n\t\tformat: \"bech32\",\n\t\tprefix: config.prefix,\n\t});\n}\n\nfunction decode_p2wsh_address(address: string): AddressInfo {\n\t// Parse the address.\n\tconst parsed = get_address_info(address);\n\t// Assert the address type is correct.\n\tAssert.ok(\n\t\tparsed.type === \"p2wsh\",\n\t\t`address type mismatch: ${parsed.type} !== ${ADDRESS_TYPE}`,\n\t);\n\t// Return the parsed address.\n\treturn parsed;\n}\n\nfunction decode_p2wsh_script(script: Bytes): Buff {\n\t// Assert the script is a p2wsh script.\n\tAssert.ok(is_p2wsh_script(script), `invalid p2wsh script`);\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Return the script hash from the script.\n\treturn bytes.slice(2, 34);\n}\n","import { Buff, type Bytes } from \"@vbyte/buff\";\nimport { LOCK_SCRIPT_TYPE } from \"@/const.js\";\nimport { get_lock_script_type } from \"@/lib/script/lock.js\";\nimport type { AddressInfo, ChainNetwork } from \"@/types/index.js\";\n\nimport { P2PKH } from \"./p2pkh.js\";\nimport { P2SH } from \"./p2sh.js\";\nimport { P2TR } from \"./p2tr.js\";\nimport { P2WPKH } from \"./p2wpkh.js\";\nimport { P2WSH } from \"./p2wsh.js\";\nimport { get_address_info } from \"./util.js\";\n\n/**\n * Get the address for a given locking script.\n *\n * @param script - The locking script.\n * @param network - The network to use.\n * @returns The address.\n */\nexport function get_address(\n\tscript: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Get the address configuration.\n\tconst type = get_lock_script_type(bytes);\n\t// If the script type is not recognized, throw an error.\n\tif (type === null)\n\t\tthrow new Error(\"Unknown or unsupported locking script type\");\n\t// Create the address based on the script type.\n\tswitch (type) {\n\t\tcase LOCK_SCRIPT_TYPE.P2PKH:\n\t\t\treturn P2PKH.encode_address(script, network);\n\t\tcase LOCK_SCRIPT_TYPE.P2SH:\n\t\t\treturn P2SH.encode_address(script, network);\n\t\tcase LOCK_SCRIPT_TYPE.P2WPKH:\n\t\t\treturn P2WPKH.encode_address(script, network);\n\t\tcase LOCK_SCRIPT_TYPE.P2WSH:\n\t\t\treturn P2WSH.encode_address(script, network);\n\t\tcase LOCK_SCRIPT_TYPE.P2TR:\n\t\t\treturn P2TR.encode_address(script, network);\n\t\tdefault:\n\t\t\tthrow new Error(`unknown script type: ${type}`);\n\t}\n}\n\nexport function parse_address(address: string): AddressInfo {\n\treturn get_address_info(address);\n}\n","import { Assert } from \"@vbyte/micro-lib\";\n\nimport type { LocktimeData } from \"@/types/index.js\";\n\n// The threshold between block height and timestamp.\nconst LOCKTIME_THRESHOLD = 500000000;\n\nexport namespace LocktimeField {\n\texport const encode = encode_locktime;\n\texport const decode = decode_locktime;\n}\n\n/**\n * Encodes a LockTimeData object into a string representation.\n * According to BIP-65, the value is simply the numeric value as a string.\n */\nexport function encode_locktime(locktime: LocktimeData): number {\n\tswitch (locktime.type) {\n\t\tcase \"timelock\":\n\t\t\tAssert.ok(locktime.stamp >= LOCKTIME_THRESHOLD, \"Invalid timestamp\");\n\t\t\treturn locktime.stamp;\n\t\tcase \"heightlock\":\n\t\t\tAssert.ok(locktime.height > 0, \"height must be greater than 0\");\n\t\t\tAssert.ok(locktime.height < LOCKTIME_THRESHOLD, \"invalid block height\");\n\t\t\treturn locktime.height;\n\t\tdefault:\n\t\t\tthrow new Error(\"Invalid locktime type\");\n\t}\n}\n\n/**\n * Parses a string or number into a LockTimeData object.\n * According to BIP-65, values below LOCKTIME_THRESHOLD are interpreted as block heights,\n * while values at or above this threshold are interpreted as timestamps.\n */\nexport function decode_locktime(locktime: number): LocktimeData | null {\n\t// Check if the value is valid (non-negative)\n\tif (Number.isNaN(locktime) || locktime <= 0) {\n\t\treturn null;\n\t}\n\t// Return the appropriate locktime type.\n\tif (locktime < LOCKTIME_THRESHOLD) {\n\t\treturn {\n\t\t\ttype: \"heightlock\",\n\t\t\theight: locktime,\n\t\t};\n\t} else {\n\t\treturn {\n\t\t\ttype: \"timelock\",\n\t\t\tstamp: locktime,\n\t\t};\n\t}\n}\n","export namespace RefPointer {\n\texport const outpoint = {\n\t\tencode: encode_outpoint,\n\t\tdecode: decode_outpoint,\n\t\tverify: verify_outpoint,\n\t\tassert: assert_outpoint,\n\t};\n\texport const record_id = {\n\t\tencode: encode_inscription_id,\n\t\tdecode: decode_inscription_id,\n\t\tverify: verify_inscription_id,\n\t\tassert: assert_inscription_id,\n\t};\n\texport const rune_id = {\n\t\tencode: encode_rune_id,\n\t\tdecode: decode_rune_id,\n\t\tverify: verify_rune_id,\n\t\tassert: assert_rune_id,\n\t};\n}\n\nfunction encode_inscription_id(txid: string, order: number = 0): string {\n\treturn `${txid}i${order}`;\n}\n\nfunction decode_inscription_id(inscription_id: string): {\n\ttxid: string;\n\torder: number;\n} {\n\tassert_inscription_id(inscription_id);\n\tconst [txid, order] = inscription_id.split(\"i\");\n\treturn { txid, order: parseInt(order, 10) };\n}\n\nfunction verify_inscription_id(inscription_id: string): boolean {\n\treturn inscription_id.match(/^[a-f0-9]{64}i\\d+$/) !== null;\n}\n\nfunction assert_inscription_id(inscription_id: string): void {\n\tif (!verify_inscription_id(inscription_id)) {\n\t\tthrow new Error(`invalid inscription id: ${inscription_id}`);\n\t}\n}\n\nfunction encode_rune_id(block_height: number, block_index: number): string {\n\treturn `${block_height}:${block_index}`;\n}\n\nfunction decode_rune_id(rune_id: string): {\n\tblock_height: number;\n\tblock_index: number;\n} {\n\tassert_rune_id(rune_id);\n\tconst [block_height, block_index] = rune_id.split(\":\");\n\treturn {\n\t\tblock_height: parseInt(block_height, 10),\n\t\tblock_index: parseInt(block_index, 10),\n\t};\n}\n\nfunction verify_rune_id(rune_id: string): boolean {\n\treturn rune_id.match(/^\\d+:\\d+$/) !== null;\n}\n\nfunction assert_rune_id(rune_id: string): void {\n\tif (!verify_rune_id(rune_id)) {\n\t\tthrow new Error(`invalid rune id: ${rune_id}`);\n\t}\n}\n\nfunction encode_outpoint(txid: string, vout: number): string {\n\treturn `${txid}:${vout}`;\n}\n\nfunction decode_outpoint(outpoint: string): { txid: string; vout: number } {\n\tassert_outpoint(outpoint);\n\tconst [txid, vout] = outpoint.split(\":\");\n\treturn { txid, vout: parseInt(vout, 10) };\n}\n\nfunction verify_outpoint(outpoint: string): boolean {\n\treturn outpoint.match(/^[a-f0-9]{64}:[0-9]+$/) !== null;\n}\n\nfunction assert_outpoint(outpoint: string): void {\n\tif (!verify_outpoint(outpoint)) {\n\t\tthrow new Error(`invalid outpoint: ${outpoint}`);\n\t}\n}\n","export const OPCODE_MAP = {\n\tOP_0: 0x00,\n\tOP_PUSHDATA1: 0x4c,\n\tOP_PUSHDATA2: 0x4d,\n\tOP_PUSHDAT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1ADD: 0x8b,\n\tOP_1SUB: 0x8c,\n\tOP_SUCCESS141: 0x8d,\n\tOP_SUCCESS142: 0x8e,\n\tOP_NEGATE: 0x8f,\n\tOP_ABS: 0x90,\n\tOP_NOT: 0x91,\n\tOP_0NOTEQUAL: 0x92,\n\tOP_ADD: 0x93,\n\tOP_SUB: 0x94,\n\tOP_SUCCESS149: 0x95,\n\tOP_SUCCESS150: 0x96,\n\tOP_SUCCESS151: 0x97,\n\tOP_SUCCESS152: 0x98,\n\tOP_SUCCESS153: 0x99,\n\tOP_BOOLAND: 0x9a,\n\tOP_BOOLOR: 0x9b,\n\tOP_NUMEQUAL: 0x9c,\n\tOP_NUMEQUALVERIFY: 0x9d,\n\tOP_NUMNOTEQUAL: 0x9e,\n\tOP_LESSTHAN: 0x9f,\n\tOP_GREATERTHAN: 0xa0,\n\tOP_LESSTHANOREQUAL: 0xa1,\n\tOP_GREATERTHANOREQUAL: 0xa2,\n\tOP_MIN: 0xa3,\n\tOP_MAX: 0xa4,\n\tOP_WITHIN: 0xa5,\n\tOP_RIPEMD160: 0xa6,\n\tOP_SHA1: 0xa7,\n\tOP_SHA256: 0xa8,\n\tOP_HASH160: 0xa9,\n\tOP_HASH256: 0xaa,\n\tOP_CODESEPARATOR: 0xab,\n\tOP_CHECKSIG: 0xac,\n\tOP_CHECKSIGVERIFY: 0xad,\n\tOP_CHECKMULTISIG: 0xae,\n\tOP_CHECKMULTISIGVERIFY: 0xaf,\n\tOP_NOP1: 0xb0,\n\tOP_CHECKLOCKTIMEVERIFY: 0xb1,\n\tOP_CHECKSEQUENCEVERIFY: 0xb2,\n\tOP_NOP4: 0xb3,\n\tOP_NOP5: 0xb4,\n\tOP_NOP6: 0xb5,\n\tOP_NOP7: 0xb6,\n\tOP_NOP8: 0xb7,\n\tOP_NOP9: 0xb8,\n\tOP_NOP10: 0xb9,\n\tOP_CHECKSIGADD: 0xba,\n};\n\n/**\n * Get the sting-representation of an opcode\n * based on its number value.\n */\nexport function get_op_code(num: number): string {\n\tif (num > 186 && num < 255) {\n\t\treturn `OP_SUCCESS${String(num)}`;\n\t}\n\tfor (const [k, v] of Object.entries(OPCODE_MAP)) {\n\t\tif (v === num) return k;\n\t}\n\tthrow new Error(`OPCODE not found:${String(num)}`);\n}\n\n/**\n * Get the number-representation of an opcode\n * based on its asm string value.\n */\nexport function get_asm_code(string: string): number {\n\tfor (const [k, v] of Object.entries(OPCODE_MAP)) {\n\t\tif (k === string) return Number(v);\n\t}\n\tthrow new Error(`OPCODE not found:${string}`);\n}\n\n/**\n * Get the type of word based on its number value.\n */\nexport function get_op_type(word: number): string {\n\tswitch (true) {\n\t\tcase word === 0:\n\t\t\treturn \"opcode\";\n\t\tcase word >= 1 && word <= 75:\n\t\t\treturn \"varint\";\n\t\tcase word === 76:\n\t\t\treturn \"pushdata1\";\n\t\tcase word === 77:\n\t\t\treturn \"pushdata2\";\n\t\tcase word === 78:\n\t\t\treturn \"pushdata4\";\n\t\tcase word <= 254:\n\t\t\treturn \"opcode\";\n\t\tdefault:\n\t\t\tthrow new Error(`Invalid word range: ${word}`);\n\t}\n}\n\n/**\n * Check if the provided value is a valid script opcode.\n */\nexport function is_valid_op(word: number): boolean {\n\tconst MIN_RANGE = 75;\n\tconst MAX_RANGE = 254;\n\n\tconst DISABLED_OPCODES: number[] = [];\n\n\tswitch (true) {\n\t\tcase typeof word !== \"number\":\n\t\t\treturn false;\n\t\tcase word === 0:\n\t\t\treturn true;\n\t\tcase DISABLED_OPCODES.includes(word):\n\t\t\treturn false;\n\t\tcase MIN_RANGE < word && word < MAX_RANGE:\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n","import { Buff, type Bytes, Stream } from \"@vbyte/buff\";\nimport type { ScriptInfo } from \"@/types/script.js\";\nimport { get_op_code, get_op_type, is_valid_op } from \"./words.js\";\n\nexport function parse_script(script: Bytes): ScriptInfo {\n\tconst bytes = Buff.bytes(script);\n\treturn {\n\t\tasm: decode_script(bytes),\n\t\thex: bytes.hex,\n\t};\n}\n\n/**\n * Decode a bitcoin script into asm instructions.\n */\nexport function decode_script(script: Bytes): string[] {\n\tconst stream = new Stream(script);\n\n\tconst stack: string[] = [];\n\tconst stack_size = stream.size;\n\n\tlet word: number;\n\tlet word_type: string;\n\tlet word_size: number;\n\n\tlet count = 0;\n\n\twhile (count < stack_size) {\n\t\tword = stream.read(1).num;\n\t\tword_type = get_op_type(word);\n\t\tcount++;\n\t\tswitch (word_type) {\n\t\t\tcase \"varint\":\n\t\t\t\ttry {\n\t\t\t\t\tstack.push(stream.read(word).hex);\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Malformed script: varint push at position ${count - 1} requires ${word} bytes but stream exhausted`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcount += word;\n\t\t\t\tbreak;\n\t\t\tcase \"pushdata1\":\n\t\t\t\ttry {\n\t\t\t\t\tword_size = stream.read(1).reverse().num;\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Malformed script: PUSHDATA1 at position ${count - 1} missing size byte`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tstack.push(stream.read(word_size).hex);\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Malformed script: PUSHDATA1 at position ${count - 1} requires ${word_size} bytes but stream exhausted`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcount += word_size + 1;\n\t\t\t\tbreak;\n\t\t\tcase \"pushdata2\":\n\t\t\t\ttry {\n\t\t\t\t\tword_size = stream.read(2).reverse().num;\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Malformed script: PUSHDATA2 at position ${count - 1} missing size bytes`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tstack.push(stream.read(word_size).hex);\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Malformed script: PUSHDATA2 at position ${count - 1} requires ${word_size} bytes but stream exhausted`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcount += word_size + 2;\n\t\t\t\tbreak;\n\t\t\tcase \"pushdata4\":\n\t\t\t\ttry {\n\t\t\t\t\tword_size = stream.read(4).reverse().num;\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Malformed script: PUSHDATA4 at position ${count - 1} missing size bytes`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tstack.push(stream.read(word_size).hex);\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Malformed script: PUSHDATA4 at position ${count - 1} requires ${word_size} bytes but stream exhausted`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcount += word_size + 4;\n\t\t\t\tbreak;\n\t\t\tcase \"opcode\":\n\t\t\t\tif (!is_valid_op(word)) {\n\t\t\t\t\tthrow new Error(`Invalid OPCODE: ${word}`);\n\t\t\t\t}\n\t\t\t\tstack.push(get_op_code(word));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Word type undefined: ${word}`);\n\t\t}\n\t}\n\treturn stack;\n}\n\n/**\n * Check if a script is valid.\n */\nexport function is_valid_script(script: string | Uint8Array): boolean {\n\ttry {\n\t\tconst stack = decode_script(script);\n\t\treturn stack.length > 0;\n\t} catch {\n\t\treturn false;\n\t}\n}\n","import { Buff, Stream } from \"@vbyte/buff\";\nimport { MAX_SCRIPT_SIZE, OP_1_OFFSET } from \"@/const.js\";\nimport { get_asm_code } from \"./words.js\";\n\n// The maximum size of a word in bytes.\nconst MAX_WORD_SIZE = 520;\n\n/**\n * Encode script asm instructions into a byte buffer.\n *\n * @param words - Array of script words (opcodes, hex data, strings, numbers, or bytes)\n * @param varint - If true, prefix the script with its length as a varint\n * @returns Encoded script as a Buff\n *\n * @example\n * ```typescript\n * // Encode a P2PKH script\n * const script = encode_script(['OP_DUP', 'OP_HASH160', pubkeyHash, 'OP_EQUALVERIFY', 'OP_CHECKSIG'])\n *\n * // Encode with varint prefix\n * const scriptWithLen = encode_script(['OP_1', pubkey, 'OP_1', 'OP_CHECKMULTISIG'], true)\n * ```\n */\nexport function encode_script(\n\twords: (string | number | Uint8Array)[],\n\tvarint = false,\n): Buff {\n\tif (words.length === 0) return Buff.num(0, 1);\n\n\tconst bytes = [];\n\n\tfor (const word of words) {\n\t\tbytes.push(encode_script_word(word));\n\t}\n\n\tconst buffer = Buff.join(bytes);\n\n\t// Validate script size against Bitcoin consensus limit\n\tif (buffer.length > MAX_SCRIPT_SIZE) {\n\t\tthrow new Error(\n\t\t\t`script size ${buffer.length} exceeds consensus limit of ${MAX_SCRIPT_SIZE} bytes`,\n\t\t);\n\t}\n\n\treturn varint\n\t\t? buffer.prepend(Buff.create_varint(buffer.length, \"le\"))\n\t\t: buffer;\n}\n\n/** Check if the word is a valid opcode,\n * and return its integer value.\n */\nexport function encode_script_word(\n\tword: string | number | Uint8Array,\n): Uint8Array {\n\tlet buff: Buff;\n\n\t// If word is a string:\n\tif (typeof word === \"string\") {\n\t\t// If word is an opcode:\n\t\tif (word.startsWith(\"OP_\")) {\n\t\t\t// Get the opcode number value.\n\t\t\tconst asm_code = get_asm_code(word);\n\t\t\t// Return the opcode as a single byte.\n\t\t\treturn Buff.num(asm_code, 1);\n\t\t\t// If word is valid hex:\n\t\t} else if (Buff.is_hex(word)) {\n\t\t\t// Encode as hex.\n\t\t\tbuff = Buff.hex(word);\n\t\t} else {\n\t\t\t// Encode as UTF8 string.\n\t\t\tbuff = Buff.str(word);\n\t\t}\n\t\t// If word is a number:\n\t} else if (typeof word === \"number\") {\n\t\t// Encode the number value.\n\t\tbuff = Buff.num(word);\n\t\t// If word is a Uint8Array:\n\t} else if (word instanceof Uint8Array) {\n\t\t// Encode as bytes.\n\t\tbuff = new Buff(word);\n\t} else {\n\t\t// If word is not a string, number, or Uint8Array, throw an error.\n\t\tthrow new Error(`invalid word type:${typeof word}`);\n\t}\n\n\t// Format and return the word based on its size.\n\tif (buff.length === 1 && buff[0] <= 16) {\n\t\t// Number values 0-16 must be treated as opcodes.\n\t\tif (buff[0] !== 0) buff[0] += OP_1_OFFSET;\n\t} else if (buff.length > MAX_WORD_SIZE) {\n\t\t// Number values larger than max size must be split into chunks.\n\t\tlet words: Buff[];\n\t\t// Split bytes into chunks, based on max word size.\n\t\twords = split_script_word(buff);\n\t\t// Prefix a varint length byte for each chunk.\n\t\twords = words.map((e) => prefix_word_size(e));\n\t\t// Concatenate the chunks\n\t\tbuff = Buff.join(words);\n\t} else {\n\t\t// Else, return the word with a varint prefix.\n\t\tbuff = prefix_word_size(buff);\n\t}\n\t// Return the final result.\n\treturn buff;\n}\n\n/**\n * Split a word into smaller chunks.\n */\nexport function split_script_word(word: Uint8Array): Buff[] {\n\tconst words = [];\n\tconst buff = new Stream(word);\n\twhile (buff.size > MAX_WORD_SIZE) {\n\t\t// Push a word chunk to the array.\n\t\twords.push(buff.read(MAX_WORD_SIZE));\n\t}\n\t// Push the remainder to the array.\n\twords.push(buff.read(buff.size));\n\treturn words;\n}\n\n/**\n * Prefix a word with its size, encoded as a varint.\n */\nexport function prefix_word_size(word: Uint8Array): Buff {\n\tconst varint = get_size_varint(word.length);\n\treturn Buff.join([varint, word]);\n}\n\n/**\n * Return a varint that encodes a size value.\n */\nexport function get_size_varint(size: number): Buff {\n\tconst OP_PUSHDATA1 = Buff.num(0x4c, 1);\n\tconst OP_PUSHDATA2 = Buff.num(0x4d, 1);\n\tswitch (true) {\n\t\tcase size <= 0x4b:\n\t\t\treturn Buff.num(size);\n\t\tcase size > 0x4b && size < 0x100:\n\t\t\treturn Buff.join([OP_PUSHDATA1, Buff.num(size, 1, \"le\")]);\n\t\tcase size >= 0x100 && size <= MAX_WORD_SIZE:\n\t\t\treturn Buff.join([OP_PUSHDATA2, Buff.num(size, 2, \"le\")]);\n\t\tdefault:\n\t\t\tthrow new Error(`Invalid word size:${size.toString()}`);\n\t}\n}\n","import { Buff, type Bytes, Stream } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/micro-lib\";\nimport { decode_script } from \"@/lib/script/decode.js\";\nimport { encode_script } from \"@/lib/script/encode.js\";\n\nimport type { InscriptionData } from \"@/types/index.js\";\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _26n = BigInt(26);\n\nexport namespace InscriptionUtil {\n\texport type Type = InscriptionData;\n\texport const encode = encode_inscription;\n\texport const decode = decode_inscription;\n}\n\nexport function decode_inscription(script: Bytes): InscriptionData[] {\n\tconst envelopes = parse_envelopes(script);\n\treturn envelopes.map(parse_record);\n}\n\nexport function encode_inscription(data: InscriptionData[]): Buff {\n\treturn Buff.join(data.map(create_envelope));\n}\n\nfunction create_envelope(data: InscriptionData): Buff {\n\tconst asm: string[] = [\"OP_0\", \"OP_IF\", \"6f7264\"];\n\n\tif (typeof data.delegate === \"string\") {\n\t\tconst id = encode_id(data.delegate);\n\t\tasm.push(\"OP_11\", id);\n\t}\n\n\tif (typeof data.ref === \"string\") {\n\t\tasm.push(\"OP_WITHIN\", data.ref);\n\t}\n\n\tif (typeof data.parent === \"string\") {\n\t\tconst id = encode_id(data.parent);\n\t\tasm.push(\"OP_3\", id);\n\t}\n\n\tif (typeof data.opcode === \"number\") {\n\t\tconst code = encode_pointer(data.opcode);\n\t\tasm.push(\"OP_NOP\", code);\n\t}\n\n\tif (typeof data.pointer === \"number\") {\n\t\tconst ptr = encode_pointer(data.pointer);\n\t\tasm.push(\"OP_2\", ptr);\n\t}\n\n\tif (typeof data.rune === \"string\") {\n\t\tconst label = encode_rune_label(data.rune);\n\t\tasm.push(\"OP_13\", label);\n\t}\n\n\tif (typeof data.mimetype === \"string\") {\n\t\tconst label = encode_label(data.mimetype);\n\t\tasm.push(\"OP_1\", label);\n\t}\n\n\tif (typeof data.content === \"string\") {\n\t\tconst chunks = encode_content(data.content);\n\t\tasm.push(\"OP_0\", ...chunks);\n\t}\n\n\tasm.push(\"OP_ENDIF\");\n\n\treturn encode_script(asm);\n}\n\nfunction parse_envelopes(script: Bytes): string[][] {\n\tconst words = decode_script(script);\n\tconst start_idx = words.indexOf(\"OP_0\");\n\n\tAssert.ok(start_idx !== -1, \"inscription envelope not found\");\n\n\tconst envelopes = [];\n\n\tfor (let idx = start_idx; idx < words.length; idx++) {\n\t\tAssert.ok(words[idx + 1] === \"OP_IF\", \"OP_IF missing from envelope\");\n\t\tAssert.ok(words[idx + 2] === \"6f7264\", \"magic bytes missing from envelope\");\n\n\t\tconst stop_idx = words.indexOf(\"OP_ENDIF\");\n\t\tAssert.ok(stop_idx !== -1, \"inscription envelope missing END_IF statement\");\n\n\t\tconst env = words.slice(idx + 3, stop_idx);\n\t\tenvelopes.push(env);\n\t\tidx += stop_idx;\n\t}\n\n\treturn envelopes;\n}\n\nfunction parse_record(envelope: Bytes[]) {\n\tconst record: InscriptionData = {};\n\n\tfor (let i = 0; i < envelope.length; i++) {\n\t\tswitch (envelope[i]) {\n\t\t\tcase \"OP_1\":\n\t\t\t\trecord.mimetype = decode_label(envelope[i + 1]);\n\t\t\t\ti += 1;\n\t\t\t\tbreak;\n\t\t\tcase \"OP_2\":\n\t\t\t\trecord.pointer = decode_pointer(envelope[i + 1]);\n\t\t\t\ti += 1;\n\t\t\t\tbreak;\n\t\t\tcase \"OP_3\":\n\t\t\t\trecord.parent = decode_id(envelope[i + 1]);\n\t\t\t\ti += 1;\n\t\t\t\tbreak;\n\t\t\tcase \"OP_11\":\n\t\t\t\trecord.delegate = decode_id(envelope[i + 1]);\n\t\t\t\ti += 1;\n\t\t\t\tbreak;\n\t\t\tcase \"OP_13\":\n\t\t\t\trecord.rune = decode_rune_label(envelope[i + 1]);\n\t\t\t\ti += 1;\n\t\t\t\tbreak;\n\t\t\tcase \"OP_WITHIN\":\n\t\t\t\trecord.ref = decode_bytes(envelope[i + 1]);\n\t\t\t\ti += 1;\n\t\t\t\tbreak;\n\t\t\tcase \"OP_NOP\":\n\t\t\t\trecord.opcode = decode_pointer(envelope[i + 1]);\n\t\t\t\ti += 1;\n\t\t\t\tbreak;\n\t\t\tcase \"OP_0\":\n\t\t\t\trecord.content = decode_content(envelope.slice(i + 1));\n\t\t\t\treturn record;\n\t\t}\n\t}\n\treturn record;\n}\n\nfunction decode_bytes(bytes: Bytes): string {\n\treturn Buff.bytes(bytes).hex;\n}\n\nfunction encode_id(identifier: string): string {\n\tAssert.ok(identifier.includes(\"i\"), \"identifier must include an index\");\n\tconst parts = identifier.split(\"i\");\n\tconst bytes = Buff.hex(parts[0]);\n\tconst idx = Number(parts[1]);\n\tconst txid = bytes.reverse().hex;\n\treturn idx !== 0 ? txid + Buff.num(idx).hex : txid;\n}\n\nfunction decode_id(identifier: Bytes): string {\n\tconst bytes = Buff.bytes(identifier);\n\tconst idx = bytes.at(-1) ?? 0;\n\tconst txid = bytes.slice(0, -1).reverse().hex;\n\treturn `${txid}i${String(idx)}`;\n}\n\nfunction encode_pointer(pointer: number): string {\n\treturn Buff.num(pointer).reverse().hex;\n}\n\nfunction decode_pointer(bytes: Bytes): number {\n\treturn Buff.bytes(bytes).reverse().num;\n}\n\nfunction encode_label(label: string): string {\n\treturn Buff.str(label).hex;\n}\n\nfunction decode_label(label: Bytes): string {\n\treturn Buff.bytes(label).str;\n}\n\nfunction encode_content(content: string): string[] {\n\tconst bytes = Buff.is_hex(content) ? Buff.hex(content) : Buff.str(content);\n\tconst stream = new Stream(bytes);\n\tconst chunks: string[] = [];\n\twhile (stream.size > 0) {\n\t\tif (stream.size > 520) {\n\t\t\tconst chunk = stream.read(520);\n\t\t\tchunks.push(chunk.hex);\n\t\t} else {\n\t\t\tconst chunk = stream.read(stream.size);\n\t\t\tchunks.push(chunk.hex);\n\t\t}\n\t}\n\treturn chunks;\n}\n\nfunction decode_content(\n\tchunks: Bytes[],\n\tformat: \"hex\" | \"utf8\" = \"hex\",\n): string {\n\tconst data = Buff.join(chunks);\n\treturn format === \"hex\" ? data.hex : data.str;\n}\n\nfunction encode_rune_label(label: string): string {\n\tconst str = label.toUpperCase();\n\tlet big = _0n;\n\tfor (const char of str) {\n\t\tif (char >= \"A\" && char <= \"Z\") {\n\t\t\tbig = big * _26n + BigInt(char.charCodeAt(0) - (\"A\".charCodeAt(0) - 1));\n\t\t} else {\n\t\t}\n\t}\n\tbig = big - _1n;\n\treturn Buff.big(big).reverse().hex;\n}\n\nfunction decode_rune_label(label: Bytes): string {\n\t// Convert hex to BigInt, with byte order reversed\n\tlet big = Buff.bytes(label).reverse().big;\n\t// Add 1 as per the encoding algorithm\n\tbig = big + _1n;\n\t// Initialize result string\n\tlet result = \"\";\n\t// Convert the BigInt back to a string of alphabet characters\n\twhile (big > _0n) {\n\t\t// Get remainder after division by 26\n\t\tconst mod = big % _26n;\n\t\t// Convert remainder to character (0 maps to 'Z', 1 to 'A', 2 to 'B', etc.)\n\t\tif (mod === _0n) {\n\t\t\tresult = `Z${result}`;\n\t\t\tbig = big / _26n - _1n; // Adjust for special case of 'Z'\n\t\t} else {\n\t\t\t// Map 1 to 'A', 2 to 'B', etc.\n\t\t\tconst charCode = Number(mod) + \"A\".charCodeAt(0) - 1;\n\t\t\tresult = String.fromCharCode(charCode) + result;\n\t\t\tbig = big / _26n;\n\t\t}\n\t}\n\treturn result;\n}\n","/**\n * Bitcoin Transaction Sequence Field Manipulation\n *\n * This module provides functionality for encoding and decoding the sequence field in Bitcoin transactions.\n * The sequence field is a 32-bit integer that can be used for various purposes:\n *\n * 1. Relative timelocks (BIP-68).\n * 2. Custom protocol data.\n *\n * The implementation follows BIP-68 for timelock functionality, and extends it with a custom protocol\n * that allows additional metadata to be encoded in the sequence field (to be used by on-chain indexers).\n */\n\nimport type { SequenceConfig, SequenceData } from \"@/types/index.js\";\n\n/* ===== [ Constants ] ===================================================== */\n\nconst TIMELOCK_DISABLE = 0x80000000; // Bit 31: When set, disables relative timelock per BIP-68.\nconst TIMELOCK_TYPE = 0x00400000; // Bit 22: When set, indicates timestamp-based lock; when clear, indicates block-height-based lock.\nconst TIMELOCK_VALUE_MASK = 0x0000ffff; // Bits 0-15: Mask for extracting timelock value (16 bits).\nconst TIMELOCK_VALUE_MAX = 0xffff; // Maximum value for timelock (2^16 - 1).\nconst TIMELOCK_GRANULARITY = 512; // Seconds per timestamp unit (BIP-68 specification).\n\n/* ===== [ API ] ============================================================ */\n\nexport namespace SequenceField {\n\texport const encode = encode_sequence;\n\texport const decode = decode_sequence;\n}\n\n/* ===== [ Encoder ] ======================================================== */\n\n/**\n * Encodes a SequenceData object into a 32-bit integer sequence value\n *\n * @param data - The sequence data to encode\n * @returns A 32-bit integer representing the encoded sequence\n * @throws Error if the input data is invalid or exceeds maximum values\n */\nexport function encode_sequence(data: SequenceConfig): number {\n\t// If the timelock is based on a block height,\n\tif (data.mode === \"height\") {\n\t\t// Validate the height value.\n\t\tconst height = parse_height(data.height);\n\t\t// For heightlock, only encode the height value (TIMELOCK_TYPE bit remains clear)\n\t\treturn (height & TIMELOCK_VALUE_MASK) >>> 0;\n\t}\n\t// If the timelock is based on a timestamp,\n\tif (data.mode === \"stamp\") {\n\t\t// Convert timestamp to 512-second granularity units as per BIP-68.\n\t\tconst stamp = parse_stamp(data.stamp);\n\t\t// Set the TIMELOCK_TYPE bit and encode the timestamp value.\n\t\treturn (TIMELOCK_TYPE | (stamp & TIMELOCK_VALUE_MASK)) >>> 0;\n\t}\n\t// Throw an error if the mode is unrecognized.\n\tthrow new Error(`invalid timelock mode: ${data.mode}`);\n}\n\n/* ===== [ Decoder ] ========================================================= */\n\n/**\n * Decodes a 32-bit sequence value into a SequenceData object\n *\n * @param sequence - The 32-bit sequence value to decode\n * @returns A SequenceData object or null if the sequence doesn't represent special data\n * @throws Error if the sequence value is invalid or exceeds maximum values\n */\nexport function decode_sequence(\n\tsequence: number | string,\n): SequenceData | null {\n\t// Parse and validate the sequence value.\n\tconst seq = parse_sequence(sequence);\n\t// If the sequence is disabled, return null.\n\tif (seq & TIMELOCK_DISABLE) return null;\n\t// Extract the value.\n\tconst value = seq & TIMELOCK_VALUE_MASK;\n\t// Check for timestamp-based lock (TIMELOCK_TYPE bit is set).\n\tif (seq & TIMELOCK_TYPE) {\n\t\t// Convert granularity units back to seconds for timestamp.\n\t\tconst stamp = value * TIMELOCK_GRANULARITY;\n\t\t// Validate the timestamp value.\n\t\tif (stamp > 0xffffffff) {\n\t\t\tthrow new Error(\"Decoded timestamp exceeds 32-bit limit\");\n\t\t}\n\t\t// Return the decoded timelock.\n\t\treturn { mode: \"stamp\", stamp };\n\t} else {\n\t\t// Validate the height value.\n\t\tif (value > TIMELOCK_VALUE_MAX) {\n\t\t\tthrow new Error(\"Decoded height exceeds maximum\");\n\t\t}\n\t\t// Return the decoded heightlock.\n\t\treturn { mode: \"height\", height: value };\n\t}\n}\n\n/* ===== [ Helpers ] ========================================================= */\n\n/**\n * Parses a sequence value into a number.\n *\n * @param sequence - The sequence value to parse.\n * @returns The parsed sequence value.\n * @throws Error if the sequence value is invalid.\n */\nfunction parse_sequence(sequence: number | string): number {\n\tconst seq = typeof sequence === \"string\" ? parseInt(sequence, 16) : sequence;\n\tif (!Number.isInteger(seq) || seq < 0 || seq > 0xffffffff) {\n\t\tthrow new Error(`invalid sequence value: ${seq}`);\n\t}\n\treturn seq;\n}\n\n/**\n * Parses a timestamp value into a 512-second granularity units.\n *\n * @param stamp - The timestamp value to parse.\n * @returns The parsed timestamp value.\n * @throws Error if the timestamp value is invalid.\n */\nfunction parse_stamp(stamp?: number): number {\n\tif (stamp === undefined || !Number.isInteger(stamp)) {\n\t\tthrow new Error(`timestamp must be a number`);\n\t}\n\t// Convert timestamp to 512-second granularity units as per BIP-68.\n\tconst ts = Math.floor(stamp / TIMELOCK_GRANULARITY);\n\t// Validate the timestamp value.\n\tif (!Number.isInteger(ts) || ts < 0 || ts > TIMELOCK_VALUE_MAX) {\n\t\tthrow new Error(\n\t\t\t`timelock value must be an integer between 0 and ${TIMELOCK_VALUE_MAX} (in 512-second increments)`,\n\t\t);\n\t}\n\treturn ts;\n}\n\n/**\n * Parses a height value into a number.\n *\n * @param height - The height value to parse.\n * @returns The parsed height value.\n * @throws Error if the height value is invalid.\n */\nfunction parse_height(height?: number): number {\n\tif (\n\t\theight === undefined ||\n\t\t!Number.isInteger(height) ||\n\t\theight < 0 ||\n\t\theight > TIMELOCK_VALUE_MAX\n\t) {\n\t\tthrow new Error(\n\t\t\t`Heightlock value must be an integer between 0 and ${TIMELOCK_VALUE_MAX}`,\n\t\t);\n\t}\n\treturn height;\n}\n","import { Buff } from \"@vbyte/buff\";\n\nexport function prefix_script_size(script: string | Uint8Array): string {\n\treturn Buff.bytes(script).prefix_varint(\"le\").hex;\n}\n\nexport function parse_script_pubkeys(script: string | Uint8Array): string[] {\n\t// Convert the script to a string if it's a Uint8Array\n\tconst scriptHex =\n\t\ttypeof script === \"string\" ? script : Buff.bytes(script).hex;\n\n\t// Define the regex pattern to match the specified pattern\n\t// 20 = pushdata byte for 32 bytes (0x20)\n\t// [0-9a-f]{64} = 32-byte hex string (64 hex characters)\n\t// (ac|ad|ba) = OP_CHECKSIG (0xac), OP_CHECKSIGVERIFY (0xad), or OP_CHECKSIGADD (0xba)\n\tconst pubkeyPattern = /20([0-9a-f]{64})(ac|ad|ba)/gi;\n\n\t// Find all matches in the script\n\tconst matches = [...scriptHex.matchAll(pubkeyPattern)];\n\n\t// Extract the public keys from the matches\n\treturn matches.map((match) => match[1]);\n}\n\n// export function parse_witness_pubkeys (\n// witness : string[] | TxWitnessData\n// ) : string[] {\n// // Parse the witness data if it is an array.\n// if (witness instanceof Array) {\n// witness = parse_witness_data(witness)\n// }\n// // Define the set of pubkeys.\n// const pubkeys = new Set<string>()\n// // Get the witness type.\n// const type = witness.type\n// // If the witness type is a p2tr-ts:\n// if (type === 'p2tr-ts') {\n// // Parse the internal pubkey from the cblock.\n// const int_pk = witness.cblock?.slice(2, 66)\n// // If the internal pubkey is present, add it to the list.\n// if (int_pk !== undefined) pubkeys.add(int_pk)\n// // Parse any pubkeys witness parameters.\n// witness.params\n// .filter(p => p.length === 64)\n// .forEach(p => pubkeys.add(p))\n// // Parse any pubkeys from the script.\n// parse_taproot_pubkeys(witness.script!)\n// .forEach(p => pubkeys.add(p))\n// // If the witness type is a p2w-pkh:\n// } else if (type === 'p2w-pkh') {\n// // Parse the witness parameter pubkey.\n// const params_pk = witness.params.find(p => p.length === 66)\n// // If the parameter pubkey is present, add it to the list.\n// if (params_pk !== undefined) pubkeys.add(params_pk)\n// // If the witness type is a p2w-sh:\n// } else if (type === 'p2w-sh') {\n// // Parse any witness parameter pubkeys.\n// witness.params\n// .filter(p => p.length === 66)\n// .forEach(p => pubkeys.add(p))\n// // Parse any script pubkeys.\n// parse_segwit_pubkeys(witness.script!)\n// .forEach(p => pubkeys.add(p))\n// }\n// // Return the list of pubkeys.\n// return Array.from(pubkeys)\n// }\n\n// function parse_segwit_pubkeys (script : string) : string[] {\n// const regex = /21([0-9a-f]{66})(ac|ad)/gi\n// const matches = [...script.matchAll(regex)]\n// return matches.map(match => match[1])\n// }\n\n// function parse_taproot_pubkeys (script : string) : string[] {\n// const regex = /20([0-9a-f]{64})(ac|ad|ba)/gi\n// const matches = [...script.matchAll(regex)]\n// return matches.map(match => match[1])\n// }\n","import { Stream } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/micro-lib/assert\";\nimport { COINBASE, MAX_VARINT_SIZE } from \"@/const.js\";\n\nimport type {\n\tTxCoinbaseInput,\n\tTxDecodedData,\n\tTxInput,\n\tTxOutput,\n\tTxVirtualInput,\n} from \"@/types/index.js\";\n\n/** Maximum transaction size in bytes (4MB, Bitcoin consensus limit) */\nconst MAX_TX_SIZE = 4_000_000;\n\n/** Maximum number of inputs/outputs per transaction */\nconst MAX_TX_ELEMENTS = 100_000;\n\nexport function decode_tx(\n\ttxdata: string | Uint8Array,\n\tuse_segwit = true,\n): TxDecodedData {\n\t// Assert the txdata is a bytes object.\n\tAssert.is_bytes(txdata, \"txdata must be hex or bytes\");\n\n\t// Check transaction size limit\n\tconst txSize = typeof txdata === \"string\" ? txdata.length / 2 : txdata.length;\n\tif (txSize > MAX_TX_SIZE) {\n\t\tthrow new Error(\n\t\t\t`Transaction size ${txSize} exceeds maximum ${MAX_TX_SIZE} bytes`,\n\t\t);\n\t}\n\n\t// Setup a byte-stream.\n\tconst stream = new Stream(txdata);\n\t// Parse tx version.\n\tconst version = read_version(stream);\n\t// Check and enable any flags that are set.\n\tlet has_witness = check_witness_flag(stream);\n\t// If use_segwit is false, set has_witness to false.\n\thas_witness = use_segwit ? has_witness : false;\n\t// Parse our inputs and outputs.\n\tconst vin = read_inputs(stream);\n\tconst vout = read_outputs(stream);\n\t// If witness flag is set, parse witness data.\n\tif (has_witness) {\n\t\tfor (const txin of vin) {\n\t\t\ttxin.witness = read_witness(stream);\n\t\t}\n\t}\n\t// Parse locktime.\n\tconst locktime = read_locktime(stream);\n\t// Return transaction object with calculated fields.\n\treturn { version, vin, vout, locktime };\n}\n\nfunction read_version(stream: Stream): number {\n\treturn stream.read(4).reverse().to_num();\n}\n\nfunction check_witness_flag(stream: Stream): boolean {\n\tconst [marker, flag]: number[] = [...stream.peek(2)];\n\tif (marker === 0) {\n\t\tstream.read(2);\n\t\tif (flag === 1) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthrow new Error(`Invalid witness flag: ${flag}`);\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction read_inputs(stream: Stream): TxInput[] {\n\tconst inputs = [];\n\tconst vinCount = stream.read_varint();\n\tif (vinCount > MAX_TX_ELEMENTS) {\n\t\tthrow new Error(\n\t\t\t`Input count ${vinCount} exceeds maximum ${MAX_TX_ELEMENTS}`,\n\t\t);\n\t}\n\tfor (let i = 0; i < vinCount; i++) {\n\t\tconst txinput = read_vin(stream);\n\t\tinputs.push(txinput);\n\t}\n\treturn inputs;\n}\n\nfunction read_vin(stream: Stream): TxInput {\n\tconst txid = stream.read(32).reverse().hex;\n\tconst vout = stream.read(4).reverse().num;\n\tconst script_sig = read_payload(stream);\n\tconst sequence = stream.read(4).reverse().num;\n\tconst witness: string[] = [];\n\tif (txid === COINBASE.TXID && vout === COINBASE.VOUT) {\n\t\treturn {\n\t\t\tcoinbase: script_sig,\n\t\t\tprevout: null,\n\t\t\tscript_sig: null,\n\t\t\tsequence,\n\t\t\ttxid,\n\t\t\tvout,\n\t\t\twitness,\n\t\t} as TxCoinbaseInput;\n\t} else {\n\t\treturn {\n\t\t\tcoinbase: null,\n\t\t\tprevout: null,\n\t\t\tscript_sig,\n\t\t\tsequence,\n\t\t\ttxid,\n\t\t\tvout,\n\t\t\twitness,\n\t\t} as TxVirtualInput;\n\t}\n}\n\nfunction read_outputs(stream: Stream): TxOutput[] {\n\tconst outputs = [];\n\tconst vcount = stream.read_varint();\n\tif (vcount > MAX_TX_ELEMENTS) {\n\t\tthrow new Error(\n\t\t\t`Output count ${vcount} exceeds maximum ${MAX_TX_ELEMENTS}`,\n\t\t);\n\t}\n\tfor (let i = 0; i < vcount; i++) {\n\t\ttry {\n\t\t\toutputs.push(read_vout(stream));\n\t\t} catch (_error) {\n\t\t\tthrow new Error(`failed to decode output at index ${i}`);\n\t\t}\n\t}\n\treturn outputs;\n}\n\nfunction read_vout(stream: Stream): TxOutput {\n\tconst value = stream.read(8).reverse().big;\n\tconst script_pk = read_payload(stream);\n\tAssert.exists(script_pk, \"failed to decode script_pk\");\n\treturn { value, script_pk };\n}\n\nfunction read_witness(stream: Stream): string[] {\n\tconst stack = [];\n\tconst count = stream.read_varint();\n\tif (count > MAX_TX_ELEMENTS) {\n\t\tthrow new Error(\n\t\t\t`Witness element count ${count} exceeds maximum ${MAX_TX_ELEMENTS}`,\n\t\t);\n\t}\n\tfor (let i = 0; i < count; i++) {\n\t\tconst element = read_payload(stream);\n\t\tif (element === null) {\n\t\t\tthrow new Error(`failed to decode witness element at index ${i}`);\n\t\t}\n\t\tstack.push(element);\n\t}\n\treturn stack;\n}\n\nexport function read_payload(stream: Stream): string | null {\n\tconst size = stream.read_varint(\"le\");\n\tif (size > MAX_VARINT_SIZE) {\n\t\tthrow new Error(`Payload size ${size} exceeds maximum ${MAX_VARINT_SIZE}`);\n\t}\n\treturn size > 0 ? stream.read(size).hex : null;\n}\n\nfunction read_locktime(stream: Stream): number {\n\treturn stream.read(4).reverse().to_num();\n}\n","/** A special constant with type `never` */\nexport const NEVER = Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepString = step.toString();\n let stepDecCount = (stepString.split(\".\")[1] || \"\").length;\n if (stepDecCount === 0 && /\\d?e-\\d?/.test(stepString)) {\n const match = stepString.match(/\\d?e-(\\d?)/);\n if (match?.[1]) {\n stepDecCount = Number.parseInt(match[1]);\n }\n }\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nconst EVALUATING = Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = cached(() => {\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: [], // delete existing checks\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\";\n full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues });\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues });\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, issue.path));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\nexport const cuid = /^[cC][^\\s-]{8,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emoji = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\n// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// const dateSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const time = timeSource({ precision: args.precision });\n const opts = [\"Z\"];\n if (args.local)\n opts.push(\"\");\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n if (def.value < curr) {\n if (def.inclusive)\n bag.maximum = def.value;\n else\n bag.exclusiveMaximum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n if (def.value > curr) {\n if (def.inclusive)\n bag.minimum = def.value;\n else\n bag.exclusiveMinimum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n var _a;\n (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n });\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n if (isInt)\n bag.pattern = regexes.integer;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.size;\n bag.maximum = def.size;\n bag.size = def.size;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.length;\n bag.maximum = def.length;\n bag.length = def.length;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n if (def.pattern) {\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(def.pattern);\n }\n });\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.mime = def.mime;\n });\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export class Doc {\n constructor(args = []) {\n this.content = [];\n this.indent = 0;\n if (this)\n this.args = args;\n }\n indented(fn) {\n this.indent += 1;\n fn(this);\n this.indent -= 1;\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const args = this?.args;\n const content = this?.content ?? [``];\n const lines = [...content.map((x) => ` ${x}`)];\n // console.log(lines.join(\"\\n\"));\n return new F(...args, lines.join(\"\\n\"));\n }\n}\n","export const version = {\n major: 4,\n minor: 3,\n patch: 5,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\n }\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer\n // inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary\n // initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n // Lazy initialize ~standard to avoid creating objects for every schema\n util.defineLazy(inst, \"~standard\", () => ({\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\n },\n vendor: \"zod\",\n version: 1,\n }));\n});\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n // @ts-ignore\n const url = new URL(trimmed);\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n // Set the output value based on normalize flag\n if (def.normalize) {\n // Use normalized URL\n payload.value = url.href;\n }\n else {\n // Preserve the original input (trimmed)\n payload.value = trimmed;\n }\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv4`;\n});\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv6`;\n inst._zod.check = (payload) => {\n try {\n // @ts-ignore\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n const parts = payload.value.split(\"/\");\n try {\n if (parts.length !== 2)\n throw new Error();\n const [address, prefix] = parts;\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n // @ts-ignore\n new URL(`http://[${address}]`);\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64\";\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64url\";\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? \"Infinity\"\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = Array(input.length);\n const proms = [];\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalOut) {\n if (result.issues.length) {\n // For optional-out schemas, ignore errors on absent keys\n if (isOptionalOut && !(key in input)) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (result.value === undefined) {\n if (key in input) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n // iterate over input keys\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const isOptionalOut = _catchall.optout === \"optional\";\n for (const key in input) {\n if (keySet.has(key))\n continue;\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalOut);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n // const sh = def.shape;\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n if (!desc?.get) {\n const sh = def.shape;\n Object.defineProperty(def, \"shape\", {\n get: () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", {\n value: newSh,\n });\n return newSh;\n },\n });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n const isOptionalOut = el._zod.optout === \"optional\";\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalOut);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {};`);\n for (const key of normalized.keys) {\n const id = ids[key];\n const k = util.esc(key);\n const schema = shape[key];\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(key)};`);\n if (isOptionalOut) {\n // For optional-out schemas, ignore errors on absent keys\n doc.write(`\n if (${id}.issues.length) {\n if (${k} in input) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const single = def.options.length === 1;\n const first = def.options[0]._zod.run;\n inst._zod.parse = (payload, ctx) => {\n if (single) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const successes = results.filter((r) => r.issues.length === 0);\n if (successes.length === 1) {\n final.value = successes[0].value;\n return final;\n }\n if (successes.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const single = def.options.length === 1;\n const first = def.options[0]._zod.run;\n inst._zod.parse = (payload, ctx) => {\n if (single) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n if (def.unionFallback) {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nfunction mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) report each key as unrecognized\n const unrecKeys = new Map();\n let unrecIssue;\n for (const iss of left.issues) {\n if (iss.code === \"unrecognized_keys\") {\n unrecIssue ?? (unrecIssue = iss);\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).l = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n for (const iss of right.issues) {\n if (iss.code === \"unrecognized_keys\") {\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).r = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n // Report only keys unrecognized by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length && unrecIssue) {\n result.issues.push({ ...unrecIssue, keys: bothKeys });\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = [];\n const proms = [];\n const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== \"optional\");\n const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex;\n if (!def.rest) {\n const tooBig = input.length > items.length;\n const tooSmall = input.length < optStart - 1;\n if (tooBig || tooSmall) {\n payload.issues.push({\n ...(tooBig\n ? { code: \"too_big\", maximum: items.length, inclusive: true }\n : { code: \"too_small\", minimum: items.length }),\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n }\n let i = -1;\n for (const item of items) {\n i++;\n if (i >= input.length)\n if (i >= optStart)\n continue;\n const result = item._zod.run({\n value: input[i],\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n if (def.rest) {\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({\n value: el,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n const values = def.keyType._zod.values;\n if (values) {\n payload.value = {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[key] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[key] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key failed with \"expected number\", retry with Number(key)\n const checkNumericKey = typeof key === \"string\" &&\n regexes.number.test(key) &&\n keyResult.issues.length &&\n keyResult.issues.some((iss) => iss.code === \"invalid_type\" && iss.expected === \"number\");\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = new Map();\n for (const [key, value] of input) {\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = new Set();\n for (const item of input) {\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n if (def.values.length === 0) {\n throw new Error(\"Cannot create literal schema with no valid values\");\n }\n const values = new Set(def.values);\n inst._zod.values = values;\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(result, input) {\n if (result.issues.length && input === undefined) {\n return { issues: [], value: undefined };\n }\n return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, payload.value));\n return handleOptionalResult(result, payload.value);\n }\n if (payload.value === undefined) {\n return payload;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"pattern\", () => def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => {\n const v = def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n if (left.issues.length) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n payload.value = Object.freeze(payload.value);\n return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._def = def;\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n return function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n };\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n };\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // let _innerType!: any;\n // util.defineLazy(def, \"getter\", () => {\n // if (!_innerType) {\n // _innerType = def.getter();\n // }\n // return () => _innerType;\n // });\n util.defineLazy(inst._zod, \"innerType\", () => def.getter());\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n util.defineLazy(inst._zod, \"optout\", () => inst._zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n external: params?.external ?? undefined,\n };\n}\nexport function process(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n process(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n Object.assign(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && result.schema._prefault)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema\n // defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes\n // multiple schemas map to the same seen object.\n // e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${id}` };\n }\n if (entry[1] === root) {\n return { ref: \"#\" };\n }\n // self-contained schema\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + defId };\n };\n // stored cached version in `def` property\n // remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema\n // or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n // biome-ignore lint:\n continue;\n }\n }\n }\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n Object.assign(schema, refSchema);\n }\n // restore child's own properties (child wins)\n Object.assign(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema\n // This handles cases like: readonly().meta({id}).describe()\n // where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n Object.assign(result, root.def ?? root.schema);\n // build defs object\n const defs = ctx.external?.defs ?? {};\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n defs[seen.defId] = seen.def;\n }\n }\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed\n // each call to finalize() is functionally independent\n // though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\nimport { getEnumValues } from \"./util.js\";\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n .bag;\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // JSON Schema format: \"time\" requires a full time with offset or Z\n // z.iso.time() does not include timezone information, so format: \"time\" should never be used\n if (format === \"time\") {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const regexes = [...patterns];\n if (regexes.length === 1)\n json.pattern = regexes[0].source;\n else if (regexes.length > 1) {\n json.allOf = [\n ...regexes.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n if (typeof format === \"string\" && format.includes(\"int\"))\n json.type = \"integer\";\n else\n json.type = \"number\";\n if (typeof exclusiveMinimum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n if (typeof minimum === \"number\") {\n json.minimum = minimum;\n if (typeof exclusiveMinimum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMinimum >= minimum)\n delete json.minimum;\n else\n delete json.exclusiveMinimum;\n }\n }\n if (typeof exclusiveMaximum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n if (typeof maximum === \"number\") {\n json.maximum = maximum;\n if (typeof exclusiveMaximum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMaximum <= maximum)\n delete json.maximum;\n else\n delete json.exclusiveMaximum;\n }\n }\n if (typeof multipleOf === \"number\")\n json.multipleOf = multipleOf;\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt cannot be represented in JSON Schema\");\n }\n};\nexport const symbolProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Symbols cannot be represented in JSON Schema\");\n }\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Undefined cannot be represented in JSON Schema\");\n }\n};\nexport const voidProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Void cannot be represented in JSON Schema\");\n }\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Date cannot be represented in JSON Schema\");\n }\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, _params) => {\n const def = schema._zod.def;\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n }\n else {\n // do not add to vals\n }\n }\n else if (typeof val === \"bigint\") {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n }\n else {\n vals.push(Number(val));\n }\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"NaN cannot be represented in JSON Schema\");\n }\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const file = {\n type: \"string\",\n format: \"binary\",\n contentEncoding: \"binary\",\n };\n const { minimum, maximum, mime } = schema._zod.bag;\n if (minimum !== undefined)\n file.minLength = minimum;\n if (maximum !== undefined)\n file.maxLength = maximum;\n if (mime) {\n if (mime.length === 1) {\n file.contentMediaType = mime[0];\n Object.assign(_json, file);\n }\n else {\n Object.assign(_json, file); // shared props at root\n _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n }\n }\n else {\n Object.assign(_json, file);\n }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Custom types cannot be represented in JSON Schema\");\n }\n};\nexport const functionProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Function types cannot be represented in JSON Schema\");\n }\n};\nexport const transformProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Transforms cannot be represented in JSON Schema\");\n }\n};\nexport const mapProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Map cannot be represented in JSON Schema\");\n }\n};\nexport const setProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Set cannot be represented in JSON Schema\");\n }\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = process(def.element, ctx, { ...params, path: [...params.path, \"items\"] });\n};\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n json.properties = {};\n const shape = def.shape;\n for (const key in shape) {\n json.properties[key] = process(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n });\n }\n // required keys\n const allKeys = new Set(Object.keys(shape));\n const requiredKeys = new Set([...allKeys].filter((key) => {\n const v = def.shape[key]._zod;\n if (ctx.io === \"input\") {\n return v.optin === undefined;\n }\n else {\n return v.optout === undefined;\n }\n }));\n if (requiredKeys.size > 0) {\n json.required = Array.from(requiredKeys);\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = process(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)\n // This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = process(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = process(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? process(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (rest) {\n json.items = rest;\n }\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n json.minItems = prefixItems.length;\n if (!rest) {\n json.maxItems = prefixItems.length;\n }\n }\n else {\n json.items = prefixItems;\n if (rest) {\n json.additionalItems = rest;\n }\n }\n // length\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties\n // This correctly represents \"only validate keys matching the pattern\" semantics\n // and composes well with allOf (intersections)\n const keyType = def.keyType;\n const keyBag = keyType._zod.bag;\n const patterns = keyBag?.patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n json.patternProperties[pattern.source] = valueSchema;\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = process(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n }\n json.additionalProperties = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n if (keyValues) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues;\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.default = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io === \"input\")\n json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const innerType = ctx.io === \"input\" ? (def.in._zod.def.type === \"transform\" ? def.out : def.in) : def.out;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n process(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n schemas[key] = finalize(ctx, schema);\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n process(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function datetime(params) {\n return core._isoDateTime(ZodISODateTime, params);\n}\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function date(params) {\n return core._isoDate(ZodISODate, params);\n}\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function time(params) {\n return core._isoTime(ZodISOTime, params);\n}\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function duration(params) {\n return core._isoDuration(ZodISODuration, params);\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = core.$constructor(\"ZodError\", initializer, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport * as checks from \"./checks.js\";\nimport * as iso from \"./iso.js\";\nimport * as parse from \"./parse.js\";\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n core.$ZodType.init(inst, def);\n Object.assign(inst[\"~standard\"], {\n jsonSchema: {\n input: createStandardJSONSchemaMethod(inst, \"input\"),\n output: createStandardJSONSchemaMethod(inst, \"output\"),\n },\n });\n inst.toJSONSchema = createToJSONSchemaMethod(inst, {});\n inst.def = def;\n inst.type = def.type;\n Object.defineProperty(inst, \"_def\", { value: def });\n // base methods\n inst.check = (...checks) => {\n return inst.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...checks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), {\n parent: true,\n });\n };\n inst.with = inst.check;\n inst.clone = (def, params) => core.clone(inst, def, params);\n inst.brand = () => inst;\n inst.register = ((reg, meta) => {\n reg.add(inst, meta);\n return inst;\n });\n // parsing\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.spa = inst.safeParseAsync;\n // encoding/decoding\n inst.encode = (data, params) => parse.encode(inst, data, params);\n inst.decode = (data, params) => parse.decode(inst, data, params);\n inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);\n inst.decodeAsync = async (data, params) => parse.decodeAsync(inst, data, params);\n inst.safeEncode = (data, params) => parse.safeEncode(inst, data, params);\n inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);\n inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);\n inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);\n // refinements\n inst.refine = (check, params) => inst.check(refine(check, params));\n inst.superRefine = (refinement) => inst.check(superRefine(refinement));\n inst.overwrite = (fn) => inst.check(checks.overwrite(fn));\n // wrappers\n inst.optional = () => optional(inst);\n inst.exactOptional = () => exactOptional(inst);\n inst.nullable = () => nullable(inst);\n inst.nullish = () => optional(nullable(inst));\n inst.nonoptional = (params) => nonoptional(inst, params);\n inst.array = () => array(inst);\n inst.or = (arg) => union([inst, arg]);\n inst.and = (arg) => intersection(inst, arg);\n inst.transform = (tx) => pipe(inst, transform(tx));\n inst.default = (def) => _default(inst, def);\n inst.prefault = (def) => prefault(inst, def);\n // inst.coalesce = (def, params) => coalesce(inst, def, params);\n inst.catch = (params) => _catch(inst, params);\n inst.pipe = (target) => pipe(inst, target);\n inst.readonly = () => readonly(inst);\n // meta\n inst.describe = (description) => {\n const cl = inst.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n };\n Object.defineProperty(inst, \"description\", {\n get() {\n return core.globalRegistry.get(inst)?.description;\n },\n configurable: true,\n });\n inst.meta = (...args) => {\n if (args.length === 0) {\n return core.globalRegistry.get(inst);\n }\n const cl = inst.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n };\n // helpers\n inst.isOptional = () => inst.safeParse(undefined).success;\n inst.isNullable = () => inst.safeParse(null).success;\n inst.apply = (fn) => fn(inst);\n return inst;\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n const bag = inst._zod.bag;\n inst.format = bag.format ?? null;\n inst.minLength = bag.minimum ?? null;\n inst.maxLength = bag.maximum ?? null;\n // validations\n inst.regex = (...args) => inst.check(checks.regex(...args));\n inst.includes = (...args) => inst.check(checks.includes(...args));\n inst.startsWith = (...args) => inst.check(checks.startsWith(...args));\n inst.endsWith = (...args) => inst.check(checks.endsWith(...args));\n inst.min = (...args) => inst.check(checks.minLength(...args));\n inst.max = (...args) => inst.check(checks.maxLength(...args));\n inst.length = (...args) => inst.check(checks.length(...args));\n inst.nonempty = (...args) => inst.check(checks.minLength(1, ...args));\n inst.lowercase = (params) => inst.check(checks.lowercase(params));\n inst.uppercase = (params) => inst.check(checks.uppercase(params));\n // transforms\n inst.trim = () => inst.check(checks.trim());\n inst.normalize = (...args) => inst.check(checks.normalize(...args));\n inst.toLowerCase = () => inst.check(checks.toLowerCase());\n inst.toUpperCase = () => inst.check(checks.toUpperCase());\n inst.slugify = () => inst.check(checks.slugify());\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n inst.email = (params) => inst.check(core._email(ZodEmail, params));\n inst.url = (params) => inst.check(core._url(ZodURL, params));\n inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params));\n inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params));\n inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params));\n inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params));\n inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params));\n inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params));\n inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params));\n inst.ulid = (params) => inst.check(core._ulid(ZodULID, params));\n inst.base64 = (params) => inst.check(core._base64(ZodBase64, params));\n inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params));\n inst.xid = (params) => inst.check(core._xid(ZodXID, params));\n inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params));\n inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params));\n inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params));\n inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params));\n inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params));\n inst.e164 = (params) => inst.check(core._e164(ZodE164, params));\n // iso\n inst.datetime = (params) => inst.check(iso.datetime(params));\n inst.date = (params) => inst.check(iso.date(params));\n inst.time = (params) => inst.check(iso.time(params));\n inst.duration = (params) => inst.check(iso.duration(params));\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: /^https?$/,\n hostname: core.regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.int = (params) => inst.check(int(params));\n inst.safe = (params) => inst.check(int(params));\n inst.positive = (params) => inst.check(checks.gt(0, params));\n inst.nonnegative = (params) => inst.check(checks.gte(0, params));\n inst.negative = (params) => inst.check(checks.lt(0, params));\n inst.nonpositive = (params) => inst.check(checks.lte(0, params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n inst.step = (value, params) => inst.check(checks.multipleOf(value, params));\n // inst.finite = (params) => inst.check(core.finite(params));\n inst.finite = () => inst;\n const bag = inst._zod.bag;\n inst.minValue =\n Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n inst.maxValue =\n Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n inst.isFinite = true;\n inst.format = bag.format ?? null;\n});\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.positive = (params) => inst.check(checks.gt(BigInt(0), params));\n inst.negative = (params) => inst.check(checks.lt(BigInt(0), params));\n inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params));\n inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n const bag = inst._zod.bag;\n inst.minValue = bag.minimum ?? null;\n inst.maxValue = bag.maximum ?? null;\n inst.format = bag.format ?? null;\n});\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\n// int64\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\n// uint64\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n const c = inst._zod.bag;\n inst.minDate = c.minimum ? new Date(c.minimum) : null;\n inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n inst.min = (minLength, params) => inst.check(checks.minLength(minLength, params));\n inst.nonempty = (params) => inst.check(checks.minLength(1, params));\n inst.max = (maxLength, params) => inst.check(checks.maxLength(maxLength, params));\n inst.length = (len, params) => inst.check(checks.length(len, params));\n inst.unwrap = () => inst.element;\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.defineLazy(inst, \"shape\", () => {\n return def.shape;\n });\n inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));\n inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall });\n inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });\n inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });\n inst.extend = (incoming) => {\n return util.extend(inst, incoming);\n };\n inst.safeExtend = (incoming) => {\n return util.safeExtend(inst, incoming);\n };\n inst.merge = (other) => util.merge(inst, other);\n inst.pick = (mask) => util.pick(inst, mask);\n inst.omit = (mask) => util.omit(inst, mask);\n inst.partial = (...args) => util.partial(ZodOptional, inst, args[0]);\n inst.required = (...args) => util.required(ZodNonOptional, inst, args[0]);\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n inst.rest = (rest) => inst.clone({\n ...inst._zod.def,\n rest: rest,\n });\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n const k = core.clone(keyType);\n k._zod.values = undefined;\n return new ZodRecord({\n type: \"record\",\n keyType: k,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n inst.options = Object.values(def.entries);\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n payload.value = output;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn) {\n return core._superRefine(fn);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodCustom({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\n// /** @deprecated Use `z.pipe()` and `z.transform()` instead. */\nexport function preprocess(fn, schema) {\n return pipe(transform(fn), schema);\n}\n","import { z } from \"zod\";\n\ntype Literal = z.infer<typeof literal>;\ntype Json = Literal | { [key: string]: Json } | Json[];\n\nexport const big = z.bigint();\nexport const bool = z.boolean();\nexport const date = z.date();\nexport const num = z\n\t.number()\n\t.min(Number.MIN_SAFE_INTEGER)\n\t.max(Number.MAX_SAFE_INTEGER);\nexport const int = num.int();\nexport const u8a = z.instanceof(Uint8Array);\nexport const str = z.string();\nexport const stamp = int.min(500_000_000);\nexport const any = z.any();\nexport const zod = z;\nexport const char = int.min(0).max(0xff);\nexport const short = int.min(0).max(0xffff);\nexport const uint = int.min(0).max(0xffffffff);\n\nexport const float = z.number().refine((e) => String(e).includes(\".\"));\n\nexport const float2 = float.refine((e) => {\n\tconst parts = String(e).split(\".\").at(1);\n\treturn parts !== undefined && parts.length <= 2;\n});\n\nexport const hex = z\n\t.string()\n\t.regex(/^[0-9a-fA-F]*$/)\n\t.refine((e) => e.length % 2 === 0);\n\nexport const literal = z.union([z.string(), z.number(), z.boolean(), z.null()]);\n\nexport const json: z.ZodType<Json> = z.lazy(() =>\n\tz.union([literal, z.array(json), z.record(str, json)]),\n);\n\nexport const u8a20 = u8a.refine((e) => e.length === 20);\nexport const u8a32 = u8a.refine((e) => e.length === 32);\nexport const u8a33 = u8a.refine((e) => e.length === 33);\nexport const u8a64 = u8a.refine((e) => e.length === 64);\n\nexport const hex20 = hex.refine((e) => e.length === 40);\nexport const hex32 = hex.refine((e) => e.length === 64);\nexport const hex33 = hex.refine((e) => e.length === 66);\nexport const hex64 = hex.refine((e) => e.length === 128);\n\nexport const bytes = z.union([hex, u8a]);\nexport const byte32 = z.union([hex32, u8a32]);\nexport const byte33 = z.union([hex33, u8a33]);\nexport const byte64 = z.union([hex64, u8a64]);\n\nexport const base58 = z.string().regex(/^[1-9A-HJ-NP-Za-km-z]+$/);\nexport const base64 = z.string().regex(/^[a-zA-Z0-9+/]+={0,2}$/);\nexport const base64url = z.string().regex(/^[a-zA-Z0-9\\-_]+={0,2}$/);\nexport const bech32 = z\n\t.string()\n\t.regex(/^[a-z]+1[023456789acdefghjklmnpqrstuvwxyz]+$/);\n","import { z } from \"zod\";\n\nimport { byte32, uint } from \"./base.js\";\n\nexport const taptree = z.union([z.array(byte32), byte32]);\n\nexport const config = z.object({\n\tpubkey: byte32,\n\tleaves: taptree.array().optional(),\n\ttarget: byte32.optional(),\n\tversion: uint.optional(),\n});\n","import { z } from \"zod\";\nimport type { TxOutput, TxOutputTemplate } from \"@/types/index.js\";\nimport { hex, hex32, uint } from \"./base.js\";\n\nconst sats = z.bigint().min(0n).max(2_100_000_000_000_000n);\n\nexport const tx_output = z.object({\n\tvalue: sats,\n\tscript_pk: hex,\n}) satisfies z.ZodType<TxOutput>;\n\nexport const tx_input = z.object({\n\tcoinbase: hex.nullable(),\n\ttxid: hex32,\n\tvout: uint,\n\tprevout: tx_output.nullable(),\n\tscript_sig: hex.nullable(),\n\tsequence: uint,\n\twitness: z.array(hex),\n});\n\nexport const tx_data = z.object({\n\tversion: uint,\n\tvin: z.array(tx_input),\n\tvout: z.array(tx_output),\n\tlocktime: uint,\n});\n\nexport const vout_template = tx_output.extend({\n\tvalue: z.union([uint, sats]),\n}) satisfies z.ZodType<TxOutputTemplate>;\n\nexport const vin_template = tx_input.extend({\n\tcoinbase: hex.nullable().optional(),\n\tprevout: vout_template.nullable().optional(),\n\tscript_sig: hex.nullable().optional(),\n\tsequence: z.union([hex, uint]).optional(),\n\twitness: z.array(hex).optional(),\n});\n\nexport const tx_template = z.object({\n\tversion: uint.optional(),\n\tvin: z.array(vin_template),\n\tvout: z.array(vout_template),\n\tlocktime: uint.optional(),\n});\n","import * as Schema from \"@/schema/index.js\";\n\nimport type {\n\tTxData,\n\tTxInput,\n\tTxInputTemplate,\n\tTxOutput,\n\tTxOutputTemplate,\n\tTxSpendData,\n\tTxSpendInput,\n\tTxTemplate,\n} from \"@/types/index.js\";\n\nexport function assert_tx_template(\n\ttxdata: unknown,\n): asserts txdata is TxTemplate {\n\tSchema.tx.tx_template.parse(txdata);\n}\n\nexport function assert_has_prevouts(\n\tvin: TxInput[],\n): asserts vin is TxSpendInput[] {\n\tif (vin.some((txin) => txin.prevout === null)) {\n\t\tthrow new Error(\"transaction missing prevouts\");\n\t}\n}\n\nexport function assert_tx_data(txdata: unknown): asserts txdata is TxData {\n\tSchema.tx.tx_data.parse(txdata);\n}\n\nexport function assert_tx_spend_data(\n\ttxdata: unknown,\n): asserts txdata is TxSpendData {\n\t// Assert the txdata is a valid tx data object.\n\tassert_tx_data(txdata);\n\t// Assert the txdata has prevouts.\n\tassert_has_prevouts(txdata.vin);\n}\n\nexport function assert_tx_input(\n\ttx_input: unknown,\n): asserts tx_input is TxInput {\n\tSchema.tx.tx_input.parse(tx_input);\n}\n\nexport function assert_tx_output(\n\ttx_output: unknown,\n): asserts tx_output is TxOutput {\n\tSchema.tx.tx_output.parse(tx_output);\n}\n\nexport function assert_vin_template(\n\tvin: unknown,\n): asserts vin is TxInputTemplate {\n\tSchema.tx.vin_template.parse(vin);\n}\n\nexport function assert_vout_template(\n\tvout: unknown,\n): asserts vout is TxOutputTemplate {\n\tSchema.tx.vout_template.parse(vout);\n}\n","import { Buff } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/micro-lib\";\nimport { COINBASE } from \"@/const.js\";\nimport type { TxData, TxInput, TxOutput } from \"@/types/index.js\";\nimport { assert_tx_data } from \"./validate.js\";\n\nexport function encode_tx(txdata: TxData, use_segwit = true): Buff {\n\t// Assert the txdata is a valid tx data object.\n\tassert_tx_data(txdata);\n\t// Unpack the transaction data.\n\tconst { version, vin, vout, locktime } = txdata;\n\t// Create a buffer for the transaction.\n\tconst buffer: Buff[] = [encode_tx_version(version)];\n\t// If the transaction is a segwit transaction,\n\tif (use_segwit) {\n\t\t// Add the segwit marker to the buffer.\n\t\tbuffer.push(Buff.hex(\"0001\"));\n\t}\n\t// Add the inputs to the buffer.\n\tbuffer.push(encode_tx_inputs(vin));\n\t// Add the outputs to the buffer.\n\tbuffer.push(encode_tx_outputs(vout));\n\t// If the transaction is a segwit transaction,\n\tif (use_segwit) {\n\t\t// For each input in the transaction,\n\t\tfor (const input of vin) {\n\t\t\t// Add the witness data to the buffer.\n\t\t\tbuffer.push(encode_vin_witness(input.witness));\n\t\t}\n\t}\n\t// Add the locktime to the buffer.\n\tbuffer.push(encode_tx_locktime(locktime));\n\t// Return the buffer as a single payload.\n\treturn Buff.join(buffer);\n}\n\nexport function encode_tx_version(num: number): Buff {\n\t// Encode the transaction version as a 4-byte little-endian number.\n\treturn Buff.num(num, 4).reverse();\n}\n\nexport function encode_txin_txid(txid: string): Buff {\n\t// Encode the transaction ID as a 32-byte little-endian number.\n\treturn Buff.hex(txid, 32).reverse();\n}\n\nexport function encode_txin_vout(vout: number): Buff {\n\t// Encode the output index as a 4-byte little-endian number.\n\treturn Buff.num(vout, 4).reverse();\n}\n\nexport function encode_txin_sequence(sequence: number): Buff {\n\t// Encode the sequence number as a 4-byte little-endian number.\n\treturn Buff.num(sequence, 4).reverse();\n}\n\nexport function encode_tx_inputs(vin: TxInput[]): Buff {\n\t// Create a buffer for the inputs, starting with the array length.\n\tconst raw: Buff[] = [Buff.create_varint(vin.length, \"le\")];\n\t// For each input in the array,\n\tfor (const input of vin) {\n\t\t// Encode the input, and add it to the buffer.\n\t\traw.push(encode_vin(input));\n\t}\n\t// Return the buffer as a single payload.\n\treturn Buff.join(raw);\n}\n\nexport function encode_vin(txin: TxInput): Buff {\n\t// If the input is a coinbase,\n\tif (txin.coinbase !== null) {\n\t\t// Encode and return the coinbase as a single payload.\n\t\treturn Buff.join([\n\t\t\tencode_txin_txid(COINBASE.TXID),\n\t\t\tencode_txin_vout(COINBASE.VOUT),\n\t\t\tencode_script_data(txin.coinbase),\n\t\t\tencode_txin_sequence(txin.sequence),\n\t\t]);\n\t} else {\n\t\t// Encode and return the input as a single payload.\n\t\treturn Buff.join([\n\t\t\tencode_txin_txid(txin.txid),\n\t\t\tencode_txin_vout(txin.vout),\n\t\t\tencode_script_data(txin.script_sig),\n\t\t\tencode_txin_sequence(txin.sequence),\n\t\t]);\n\t}\n}\n\nexport function encode_vout_value(value: bigint): Buff {\n\t// Encode the value as an 8-byte little-endian number.\n\treturn Buff.big(value, 8).reverse();\n}\n\nexport function encode_tx_outputs(vout: TxOutput[]): Buff {\n\t// Create a buffer for the outputs, starting with the array length.\n\tconst buffer: Buff[] = [Buff.create_varint(vout.length, \"le\")];\n\t// For each output in the array,\n\tfor (const output of vout) {\n\t\t// Encode the output, and add it to the buffer.\n\t\tbuffer.push(encode_tx_vout(output));\n\t}\n\t// Return the buffer as a single payload.\n\treturn Buff.join(buffer);\n}\n\nexport function encode_tx_vout(txout: TxOutput): Buff {\n\t// Get the value and script pubkey from the output.\n\tconst { value, script_pk } = txout;\n\t// Return the data encoded as a single payload.\n\treturn Buff.join([encode_vout_value(value), encode_script_data(script_pk)]);\n}\n\nexport function encode_vin_witness(data: string[]): Buff {\n\t// Create a buffer for the witness data, starting with the array length.\n\tconst buffer: Buff[] = [Buff.create_varint(data.length)];\n\t// For each parameter in the witness array,\n\tfor (const param of data) {\n\t\t// Encode the parameter, and add it to the buffer.\n\t\tbuffer.push(encode_script_data(param));\n\t}\n\t// Return the buffer as a single payload.\n\treturn Buff.join(buffer);\n}\n\nexport function encode_tx_locktime(locktime: number): Buff {\n\t// Encode the locktime as a 4-byte little-endian number.\n\treturn Buff.num(locktime, 4).reverse();\n}\n\nexport function encode_script_data(script: string | null): Buff {\n\t// If the script is not null,\n\tif (script !== null) {\n\t\t// Assert that the script is a hex string.\n\t\tAssert.is_hex(script);\n\t\t// Encode the script, and add it to the buffer.\n\t\treturn Buff.hex(script).prefix_varint(\"le\");\n\t} else {\n\t\t// Return a single byte of zero.\n\t\treturn Buff.hex(\"00\");\n\t}\n}\n","import { Assert } from \"@vbyte/micro-lib/assert\";\nimport type { TxData, TxOutputTemplate } from \"@/types/index.js\";\nimport { create_tx, create_tx_output } from \"./create.js\";\nimport { decode_tx } from \"./decode.js\";\nimport { assert_tx_template } from \"./validate.js\";\n\nexport function parse_tx(\n\ttxdata: unknown,\n\tprevouts?: TxOutputTemplate[],\n): TxData {\n\t// Define the tx variable.\n\tlet tx: TxData;\n\t// If the txdata is a string or Uint8Array,\n\tif (typeof txdata === \"string\" || txdata instanceof Uint8Array) {\n\t\t// Decode the tx.\n\t\ttx = decode_tx(txdata);\n\t} else {\n\t\t// Assert the txdata is a valid tx template.\n\t\tassert_tx_template(txdata);\n\t\t// Create the tx.\n\t\ttx = create_tx(txdata);\n\t}\n\t// If the prevouts are provided,\n\tif (prevouts) {\n\t\t// Assert the prevouts are a non-empty array.\n\t\tAssert.has_items(prevouts, \"prevouts must be a non-empty array\");\n\t\t// Iterate over the inputs.\n\t\tfor (const [idx, vin] of tx.vin.entries()) {\n\t\t\t// Get the prevout.\n\t\t\tconst prevout = prevouts.at(idx);\n\t\t\t// Assert the prevout exists.\n\t\t\tAssert.exists(prevout, `prevout not found for input index: ${idx}`);\n\t\t\t// Create the prevout.\n\t\t\tvin.prevout = create_tx_output(prevout);\n\t\t}\n\t}\n\t// Return the tx.\n\treturn tx;\n}\n\nexport function serialize_tx(txdata: unknown): Record<string, unknown> {\n\tconst tx = parse_tx(txdata);\n\tconst version = tx.version;\n\tconst locktime = tx.locktime;\n\n\tconst vin: Record<string, unknown>[] = [];\n\tconst vout: Record<string, unknown>[] = [];\n\n\tfor (const e of tx.vin) {\n\t\tif (e.prevout !== null) {\n\t\t\tvin.push({\n\t\t\t\tscript_pk: e.prevout.script_pk,\n\t\t\t\tvalue: Number(e.prevout.value),\n\t\t\t});\n\t\t}\n\t}\n\n\tfor (const e of tx.vout) {\n\t\tvout.push({\n\t\t\tscript_pk: e.script_pk,\n\t\t\tvalue: Number(e.value),\n\t\t});\n\t}\n\n\treturn { version, locktime, vin, vout };\n}\n","import { Buff } from \"@vbyte/buff\";\nimport { Test } from \"@vbyte/micro-lib\";\nimport { Assert } from \"@vbyte/micro-lib/assert\";\nimport { hash256 } from \"@vbyte/micro-lib/hash\";\nimport { DEFAULT } from \"@/const.js\";\nimport type {\n\tTxData,\n\tTxOutput,\n\tTxOutputTemplate,\n\tTxValue,\n} from \"@/types/index.js\";\nimport { decode_tx } from \"./decode.js\";\nimport { encode_tx } from \"./encode.js\";\nimport { parse_tx } from \"./parse.js\";\nimport { assert_tx_template } from \"./validate.js\";\n\nexport function transcode_tx(\n\ttxdata: string | Uint8Array,\n\tuse_segwit = true,\n): Buff {\n\t// Decode the transaction data.\n\tconst decoded = decode_tx(txdata);\n\t// Re-encode and return the encoded transaction data.\n\treturn encode_tx(decoded, use_segwit);\n}\n\nexport function get_txid(txdata: string | Uint8Array | TxData): string {\n\tlet buffer: Uint8Array;\n\n\tif (txdata instanceof Uint8Array) {\n\t\t// Set the buffer to the transaction data.\n\t\tbuffer = transcode_tx(txdata, false);\n\t} else if (typeof txdata === \"object\") {\n\t\t// Assert the structure of the transaction data is valid.\n\t\tassert_tx_template(txdata);\n\t\t// Encode the transaction data.\n\t\tbuffer = encode_tx(txdata, false);\n\t} else if (typeof txdata === \"string\") {\n\t\t// Assert the transaction data is a hex string.\n\t\tAssert.is_hex(txdata);\n\t\t// Convert the hex string to a Uint8Array.\n\t\tbuffer = transcode_tx(txdata, false);\n\t} else {\n\t\tthrow new TypeError(`invalid txdata type: ${typeof txdata}`);\n\t}\n\t// Return the txid of the transaction data.\n\treturn hash256(buffer).reverse().hex;\n}\n\nexport function get_txhash(txdata: string | Uint8Array | TxData): string {\n\t// If the transaction data is an object,\n\tif (typeof txdata === \"object\") {\n\t\t// Assert the structure of the transaction data is valid.\n\t\tassert_tx_template(txdata);\n\t\t// Encode the transaction data.\n\t\ttxdata = encode_tx(txdata, true);\n\t}\n\t// Return the txhash of the transaction data.\n\treturn hash256(txdata).reverse().hex;\n}\n\nexport function get_tx_value(txdata: string | Uint8Array | TxData): TxValue {\n\t// Parse the transaction data.\n\tconst tx = parse_tx(txdata);\n\t// Assert the structure of the transaction data is valid.\n\tassert_tx_template(tx);\n\t// Calculate the value of the transaction.\n\tconst vin = tx.vin.reduce(\n\t\t(acc, txin) => acc + (txin.prevout?.value ?? 0n),\n\t\t0n,\n\t);\n\tconst vout = tx.vout.reduce((acc, txout) => acc + txout.value, 0n);\n\tconst fees = vin > vout ? vin - vout : 0n;\n\t// Return the value of the transaction.\n\treturn { fees, vin, vout };\n}\n\nexport function get_prevouts(txdata: TxData): TxOutput[] {\n\t// Assert the structure of the transaction data is valid.\n\tassert_tx_template(txdata);\n\t// Collect the prevouts from the transaction.\n\tconst prevouts = txdata.vin.map((e) => e.prevout);\n\t// Assert that all the prevouts are defined.\n\tAssert.ok(\n\t\tprevouts.every((e) => e !== null),\n\t\t\"prevouts missing from tx\",\n\t);\n\t// Return the array of prevouts.\n\treturn prevouts;\n}\n\nexport function normalize_sequence(sequence?: number | string | null): number {\n\t// If sequence is not defined, return a default sequence value.\n\tif (!Test.exists(sequence)) return DEFAULT.SEQUENCE;\n\t// If sequence is a hex string, decode it and return the number value.\n\tif (Test.is_hex(sequence))\n\t\treturn Buff.hex(sequence as string, 4).reverse().num;\n\t// If sequence is a valid unsigned integer, return the value.\n\tif (Test.is_uint(sequence)) return sequence;\n\t// Else, throw an error.\n\tthrow new Error(`invalid sequence value: ${String(sequence)}`);\n}\n\nexport function normalize_value(value: number | bigint): bigint {\n\t// If value is a unsigned integer, return it as a bigint.\n\tif (Test.is_uint(value)) return BigInt(value);\n\t// If value is a bigint, return it as-is.\n\tif (typeof value === \"bigint\") return value;\n\t// Else, throw an error.\n\tthrow new TypeError(`invalid output value: ${String(value)}`);\n}\n\nexport function normalize_prevout(prevout: TxOutputTemplate): TxOutput {\n\t// Return the output with a normalized value.\n\treturn {\n\t\tscript_pk: prevout.script_pk,\n\t\tvalue: normalize_value(prevout.value),\n\t};\n}\n","import { Assert } from \"@vbyte/micro-lib\";\nimport { COINBASE, DEFAULT } from \"@/const.js\";\nimport type {\n\tTxCoinbaseInput,\n\tTxData,\n\tTxInput,\n\tTxInputTemplate,\n\tTxOutput,\n\tTxOutputTemplate,\n\tTxSpendInput,\n\tTxTemplate,\n\tTxVirtualInput,\n} from \"@/types/index.js\";\nimport {\n\tnormalize_prevout,\n\tnormalize_sequence,\n\tnormalize_value,\n} from \"./util.js\";\nimport {\n\tassert_tx_template,\n\tassert_vin_template,\n\tassert_vout_template,\n} from \"./validate.js\";\n\nexport function create_coinbase_input(\n\tconfig: TxInputTemplate,\n): TxCoinbaseInput {\n\tassert_vin_template(config);\n\tAssert.exists(config.coinbase, \"coinbase is required\");\n\tconst txid = COINBASE.TXID;\n\tconst vout = COINBASE.VOUT;\n\tconst coinbase = config.coinbase;\n\tconst witness = config.witness ?? [];\n\tconst sequence = normalize_sequence(config.sequence);\n\treturn {\n\t\tcoinbase,\n\t\tprevout: null,\n\t\tscript_sig: null,\n\t\tsequence,\n\t\twitness,\n\t\ttxid,\n\t\tvout,\n\t};\n}\n\nexport function create_virtual_input(config: TxInputTemplate): TxVirtualInput {\n\tassert_vin_template(config);\n\tAssert.is_empty(config.coinbase, \"coinbase is not allowed\");\n\tAssert.is_empty(config.prevout, \"prevout is not allowed\");\n\tconst { txid, vout, script_sig = null, witness = [] } = config;\n\tconst sequence = normalize_sequence(config.sequence);\n\treturn {\n\t\ttxid,\n\t\tvout,\n\t\tcoinbase: null,\n\t\tprevout: null,\n\t\tscript_sig,\n\t\tsequence,\n\t\twitness,\n\t};\n}\n\nexport function create_spend_input(config: TxInputTemplate): TxSpendInput {\n\tassert_vin_template(config);\n\tAssert.exists(config.prevout, \"prevout is required\");\n\tconst { txid, vout, script_sig = null, witness = [] } = config;\n\tconst prevout = normalize_prevout(config.prevout);\n\tconst sequence = normalize_sequence(config.sequence);\n\treturn { txid, vout, coinbase: null, prevout, script_sig, sequence, witness };\n}\n\nexport function create_tx_input(config: TxInputTemplate): TxInput {\n\tif (config.coinbase) return create_coinbase_input(config);\n\tif (config.prevout) return create_spend_input(config);\n\treturn create_virtual_input(config);\n}\n\nexport function create_tx_output(config: TxOutputTemplate): TxOutput {\n\tassert_vout_template(config);\n\tconst script_pk = config.script_pk;\n\tconst value = normalize_value(config.value);\n\treturn { script_pk, value };\n}\n\nexport function create_tx(config?: Partial<TxTemplate>): TxData {\n\tassert_tx_template(config);\n\tconst { vin = [], vout = [] } = config ?? { vin: [], vout: [] };\n\tconst locktime = config.locktime ?? DEFAULT.LOCKTIME;\n\tconst version = config.version ?? DEFAULT.VERSION;\n\tconst inputs = vin.map((txin) => create_tx_input(txin));\n\tconst outputs = vout.map((txout) => create_tx_output(txout));\n\treturn { locktime, vin: inputs, vout: outputs, version };\n}\n","import { Buff, type Bytes } from \"@vbyte/buff\";\nimport type { TxData, TxInput, TxOutput, TxSize } from \"@/types/index.js\";\n\nimport {\n\tencode_tx,\n\tencode_tx_inputs,\n\tencode_tx_outputs,\n\tencode_tx_vout,\n\tencode_vin,\n\tencode_vin_witness,\n} from \"./encode.js\";\nimport { parse_tx } from \"./parse.js\";\n\nconst WIT_FLAG_BYTES = 2;\n\nexport function get_vsize(bytes: Bytes): number {\n\tconst weight = Buff.bytes(bytes).length;\n\tconst remain = weight % 4 > 0 ? 1 : 0;\n\treturn Math.ceil(weight / 4) + remain;\n}\n\nexport function get_txsize(txdata: string | TxData): TxSize {\n\tconst json = parse_tx(txdata);\n\tconst base = encode_tx(json, false).length;\n\tconst total = encode_tx(json, true).length;\n\tconst weight = base * 3 + total;\n\tconst remain = weight % 4 > 0 ? 1 : 0;\n\tconst vsize = Math.ceil(weight / 4) + remain;\n\treturn { base, total, vsize, weight };\n}\n\nexport function get_vin_size(vin: TxInput[]): number {\n\tconst bytes = encode_tx_inputs(vin);\n\treturn bytes.length;\n}\n\nexport function get_vout_size(vout: TxOutput[]): number {\n\tconst bytes = encode_tx_outputs(vout);\n\treturn bytes.length;\n}\n\nexport function get_segwit_size(txinputs: TxInput[]): number {\n\tconst segwit_data = txinputs\n\t\t.filter((e) => e.witness.length > 0)\n\t\t.map((e) => e.witness);\n\treturn (\n\t\tWIT_FLAG_BYTES +\n\t\tsegwit_data.reduce((acc, e) => acc + encode_vin_witness(e).length, 0)\n\t);\n}\n\nexport function get_txin_size(txinput: TxInput): number {\n\tconst bytes = encode_vin(txinput);\n\treturn bytes.length;\n}\n\nexport function get_txout_size(txoutput: TxOutput): number {\n\tconst bytes = encode_tx_vout(txoutput);\n\treturn bytes.length;\n}\n","import { Buff } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/micro-lib\";\nimport { sha256 } from \"@vbyte/micro-lib/hash\";\n\nimport type {\n\tSigHashOptions,\n\tTxData,\n\tTxInput,\n\tTxOutput,\n} from \"@/types/index.js\";\n\nexport function get_prevout(vin: TxInput): TxOutput {\n\tAssert.exists(\n\t\tvin.prevout,\n\t\t`Prevout data missing for input: ${String(vin.txid)}`,\n\t);\n\treturn vin.prevout;\n}\n\nexport function parse_txinput(\n\ttxdata: TxData,\n\tconfig?: SigHashOptions,\n): TxInput {\n\tlet { txindex, txinput } = config ?? {};\n\tif (txindex !== undefined) {\n\t\tif (txindex >= txdata.vin.length) {\n\t\t\t// If index is out of bounds, throw error.\n\t\t\tthrow new Error(`Input index out of bounds: ${String(txindex)}`);\n\t\t}\n\t\ttxinput = txdata.vin.at(txindex);\n\t}\n\tAssert.ok(txinput !== undefined);\n\treturn txinput;\n}\n\nexport function get_annex_data(witness?: string[]): Buff | undefined {\n\t// If no witness exists, return undefined.\n\tif (witness === undefined) return;\n\t// If there are less than two elements, return undefined.\n\tif (witness.length < 2) return;\n\t// Define the last element as the annex.\n\tconst annex = witness.at(-1);\n\t// If the annex is a string and starts with '50',\n\tif (typeof annex === \"string\" && annex.startsWith(\"50\")) {\n\t\t// Convert the annex to a buffer with a varint prefix.\n\t\tconst bytes = Buff.hex(annex).prefix_varint(\"be\");\n\t\t// Return the sha256 of the annex.\n\t\treturn sha256(bytes);\n\t}\n\t// Else, return undefined.\n\treturn undefined;\n}\n","import { Buff } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/micro-lib\";\nimport { hash160, hash256 } from \"@vbyte/micro-lib/hash\";\nimport * as CONST from \"@/const.js\";\n\nimport { decode_script, prefix_script_size } from \"@/lib/script/index.js\";\n\nimport {\n\tencode_tx_locktime,\n\tencode_tx_version,\n\tencode_txin_sequence,\n\tencode_txin_txid,\n\tencode_txin_vout,\n\tencode_vout_value,\n\tparse_tx,\n} from \"@/lib/tx/index.js\";\n\nimport type {\n\tSigHashOptions,\n\tTxData,\n\tTxInput,\n\tTxOutput,\n} from \"@/types/index.js\";\nimport { parse_txinput } from \"./util.js\";\n\nexport function hash_segwit_tx(\n\ttxdata: TxData,\n\toptions: SigHashOptions = {},\n): Buff {\n\t// Unpack the sigflag from our config object.\n\tconst { sigflag = 0x01, txindex } = options;\n\t// Normalize the tx into JSON format.\n\tconst tx = parse_tx(txdata);\n\t// Check if the ANYONECANPAY flag is set.\n\tconst is_anypay = (sigflag & 0x80) === 0x80;\n\t// Save a normalized version of the sigflag.\n\tconst flag = sigflag % 0x80;\n\t// Check if the sigflag exists as a valid type.\n\tif (!CONST.SIGHASH_SEGWIT.includes(flag)) {\n\t\tthrow new Error(`Invalid hash type: ${String(sigflag)}`);\n\t}\n\t// Unpack the tx object.\n\tconst { version, vin, vout, locktime } = tx;\n\t// Parse the input we are signing from the config.\n\tconst txinput = parse_txinput(tx, options);\n\t// Unpack the chosen input for signing.\n\tconst { txid, vout: prevIdx, prevout, sequence } = txinput;\n\t// Unpack the prevout for the chosen input.\n\tconst { value } = prevout ?? {};\n\t// Check if a prevout value is provided.\n\tif (value === undefined) {\n\t\tthrow new Error(\"Prevout value is empty!\");\n\t}\n\t// Initialize our script variable from the config.\n\tlet { pubkey, script } = options;\n\t// Check if a pubkey is provided (instead of a script).\n\tif (script === undefined && pubkey !== undefined) {\n\t\tconst pkhash = hash160(pubkey).hex;\n\t\tscript = `76a914${String(pkhash)}88ac`;\n\t}\n\t// Make sure that some form of script has been provided.\n\tif (script === undefined) {\n\t\tthrow new Error(\"No pubkey / script has been set!\");\n\t}\n\t// Throw if OP_CODESEPARATOR is used in a script.\n\tif (decode_script(script).includes(\"OP_CODESEPARATOR\")) {\n\t\tthrow new Error(\n\t\t\t\"This library does not currently support the use of OP_CODESEPARATOR in segwit scripts.\",\n\t\t);\n\t}\n\n\tconst sighash = [\n\t\tencode_tx_version(version),\n\t\tbip143_hash_prevouts(vin, is_anypay),\n\t\tbip143_hash_sequence(vin, flag, is_anypay),\n\t\tencode_txin_txid(txid),\n\t\tencode_txin_vout(prevIdx),\n\t\tprefix_script_size(script),\n\t\tencode_vout_value(value),\n\t\tencode_txin_sequence(sequence),\n\t\tbip143_hash_outputs(vout, flag, txindex),\n\t\tencode_tx_locktime(locktime),\n\t\tBuff.num(sigflag, 4).reverse(),\n\t];\n\n\treturn hash256(Buff.join(sighash));\n}\n\nexport function bip143_hash_prevouts(\n\tvin: TxInput[],\n\tisAnypay?: boolean,\n): Uint8Array {\n\tif (isAnypay === true) {\n\t\treturn Buff.num(0, 32);\n\t}\n\n\tconst stack = [];\n\n\tfor (const { txid, vout } of vin) {\n\t\tstack.push(encode_txin_txid(txid));\n\t\tstack.push(encode_txin_vout(vout));\n\t}\n\n\treturn hash256(Buff.join(stack));\n}\n\nexport function bip143_hash_sequence(\n\tvin: TxInput[],\n\tsigflag: number,\n\tisAnyPay: boolean,\n): Uint8Array {\n\tif (isAnyPay || sigflag !== 0x01) {\n\t\treturn Buff.num(0, 32);\n\t}\n\n\tconst stack = [];\n\n\tfor (const { sequence } of vin) {\n\t\tstack.push(encode_txin_sequence(sequence));\n\t}\n\treturn hash256(Buff.join(stack));\n}\n\nexport function bip143_hash_outputs(\n\tvout: TxOutput[],\n\tsigflag: number,\n\tidx?: number,\n): Uint8Array {\n\tconst stack = [];\n\n\tif (sigflag === 0x01) {\n\t\tfor (const { value, script_pk } of vout) {\n\t\t\tstack.push(encode_vout_value(value));\n\t\t\tstack.push(prefix_script_size(script_pk));\n\t\t}\n\t\treturn hash256(Buff.join(stack));\n\t}\n\n\tif (sigflag === 0x03) {\n\t\tAssert.ok(idx !== undefined, \"txindex required for SIGHASH_SINGLE\");\n\t\tAssert.ok(idx >= 0, \"txindex must be non-negative\");\n\t\tif (idx < vout.length) {\n\t\t\tconst { value, script_pk } = vout[idx];\n\t\t\tstack.push(encode_vout_value(value));\n\t\t\tstack.push(prefix_script_size(script_pk));\n\t\t\treturn hash256(Buff.join(stack));\n\t\t}\n\t}\n\n\treturn Buff.num(0, 32);\n}\n","import type { Buff } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/micro-lib\";\nimport { hash340 } from \"@vbyte/micro-lib/hash\";\nimport { TAPLEAF_DEFAULT_VERSION } from \"@/const.js\";\nimport { prefix_script_size } from \"@/lib/script/index.js\";\n\nconst DEFAULT_VERSION = TAPLEAF_DEFAULT_VERSION;\n\n/**\n * Encode a tapscript into a tapleaf hash.\n * Prefixes the script with its size and applies the TapLeaf tagged hash.\n *\n * @param script - The tapscript to encode (hex string or bytes)\n * @param version - Tapleaf version byte (default: 0xc0)\n * @returns Tapleaf hash as 32-byte Buff\n *\n * @example\n * ```typescript\n * const script = '20' + pubkey + 'ac' // <pubkey> OP_CHECKSIG\n * const tapleaf = encode_tapscript(script)\n * ```\n */\nexport function encode_tapscript(\n\tscript: string | Uint8Array,\n\tversion = DEFAULT_VERSION,\n): Buff {\n\tconst preimg = prefix_script_size(script);\n\treturn encode_tapleaf(preimg, version);\n}\n\n/**\n * Encode data into a tapleaf hash using the TapLeaf tagged hash.\n *\n * @param data - The data to hash (typically size-prefixed script)\n * @param version - Tapleaf version byte (default: 0xc0)\n * @returns Tapleaf hash as 32-byte Buff\n */\nexport function encode_tapleaf(\n\tdata: string | Uint8Array,\n\tversion = DEFAULT_VERSION,\n): Buff {\n\tconst vbyte = encode_leaf_version(version);\n\treturn hash340(\"TapLeaf\", vbyte, data);\n}\n\n/**\n * Encode two tapleaf/branch hashes into a tapbranch hash.\n * Combines two children using the TapBranch tagged hash.\n * Children are sorted lexicographically before hashing.\n *\n * @param leaf_a - First child hash (hex string)\n * @param leaf_b - Second child hash (hex string)\n * @returns Tapbranch hash as 32-byte Buff\n */\nexport function encode_tapbranch(leaf_a: string, leaf_b: string): Buff {\n\t// Compare leaves in lexical order.\n\tif (leaf_b < leaf_a) {\n\t\t// Swap leaves if needed.\n\t\t[leaf_a, leaf_b] = [leaf_b, leaf_a];\n\t}\n\t// Return digest of leaves as a branch hash.\n\treturn hash340(\"TapBranch\", leaf_a, leaf_b);\n}\n\n/**\n * Encode a tapleaf version byte by masking the parity bit.\n *\n * @param version - Tapleaf version (default: 0xc0)\n * @returns Version with parity bit cleared\n */\nexport function encode_leaf_version(version = 0xc0): number {\n\treturn version & 0xfe;\n}\n\n/**\n * Encode a taproot tweak from an internal pubkey and optional data.\n * Uses the TapTweak tagged hash.\n *\n * @param pubkey - 32-byte internal public key (x-only)\n * @param data - Optional commitment data (typically merkle root)\n * @returns Taptweak hash as 32-byte Buff\n * @throws Error if pubkey is not 32 bytes\n *\n * @example\n * ```typescript\n * // Key-only spend (no script tree)\n * const tweak = encode_taptweak(internalPubkey)\n *\n * // Script tree spend\n * const tweak = encode_taptweak(internalPubkey, merkleRoot)\n * ```\n */\nexport function encode_taptweak(\n\tpubkey: string | Uint8Array,\n\tdata: string | Uint8Array = new Uint8Array(),\n): Buff {\n\tAssert.size(pubkey, 32);\n\treturn hash340(\"TapTweak\", pubkey, data);\n}\n","import { Buff } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/micro-lib\";\nimport { hash340, sha256 } from \"@vbyte/micro-lib/hash\";\nimport * as CONST from \"@/const.js\";\nimport { encode_tapscript } from \"@/lib/taproot/encode.js\";\nimport {\n\tencode_script_data,\n\tencode_tx_locktime,\n\tencode_tx_version,\n\tencode_txin_sequence,\n\tencode_txin_txid,\n\tencode_txin_vout,\n\tencode_vout_value,\n} from \"@/lib/tx/encode.js\";\nimport { parse_tx } from \"@/lib/tx/parse.js\";\nimport type {\n\tSigHashOptions,\n\tTxData,\n\tTxInput,\n\tTxOutput,\n} from \"@/types/index.js\";\nimport { get_annex_data, get_prevout, parse_txinput } from \"./util.js\";\n\nexport function hash_taproot_tx(\n\ttemplate: TxData | string,\n\tconfig: SigHashOptions = {},\n): Buff {\n\tconst preimage = get_taproot_tx_preimage(template, config);\n\treturn hash340(\"TapSighash\", preimage);\n}\n\nexport function get_taproot_tx_preimage(\n\ttemplate: TxData | string,\n\tconfig: SigHashOptions = {},\n): Buff {\n\t// Unpack configuration.\n\tconst {\n\t\tscript,\n\t\ttxindex,\n\t\tsigflag = 0x00,\n\t\textflag = 0x00,\n\t\tkey_version = 0x00,\n\t\tseparator_pos = 0xffffffff,\n\t} = config;\n\n\t// Normalize the txdata object.\n\tconst tx = parse_tx(template);\n\t// Unpack the txdata object.\n\tconst { version, vin: input, vout: output, locktime } = tx;\n\t// Parse the input we are signing from the config.\n\tconst txinput = parse_txinput(tx, config);\n\t// Unpack the txinput object.\n\tconst { txid, vout, sequence, witness = [] } = txinput;\n\t// Check if we are using a valid hash type.\n\tif (!CONST.SIGHASH_TAPROOT.includes(sigflag)) {\n\t\t// If the sigflag is an invalid type, throw error.\n\t\tthrow new Error(`Invalid hash type: ${String(sigflag)}`);\n\t}\n\tif (extflag < 0 || extflag > 127) {\n\t\t// If the extflag is out of range, throw error.\n\t\tthrow new Error(`Extention flag out of range: ${String(extflag)}`);\n\t}\n\n\tlet { extension } = config;\n\n\tif (script !== undefined) {\n\t\textension = encode_tapscript(script).hex;\n\t}\n\n\t// Define the parameters of the transaction.\n\tconst is_anypay = (sigflag & 0x80) === 0x80;\n\tconst annex = get_annex_data(witness);\n\tconst annexBit = annex !== undefined ? 1 : 0;\n\tconst extendBit = extension !== undefined ? 1 : 0;\n\tconst spendType = (extflag + extendBit) * 2 + annexBit;\n\n\t// Begin building our preimage.\n\tconst preimage: (string | Uint8Array)[] = [\n\t\tBuff.num(0x00, 1), // Add zero-byte.\n\t\tBuff.num(sigflag, 1), // Commit to signature flag.\n\t\tencode_tx_version(version), // Commit to tx version.\n\t\tencode_tx_locktime(locktime), // Commit to tx locktime.\n\t];\n\n\tif (!is_anypay) {\n\t\t// If flag ANYONE_CAN_PAY is not set,\n\t\t// then commit to all inputs.\n\t\tconst prevouts = input.map((e) => get_prevout(e));\n\t\tpreimage.push(\n\t\t\tbip341_hash_outpoints(input), // Commit to txid/vout for each input.\n\t\t\tbip341_hash_amounts(prevouts), // Commit to prevout amount for each input.\n\t\t\tbip341_hash_scripts(prevouts), // Commit to prevout script for each input.\n\t\t\tbip341_hash_sequence(input), // Commit to sequence value for each input.\n\t\t);\n\t}\n\n\tif ((sigflag & 0x03) < 2 || (sigflag & 0x03) > 3) {\n\t\t// If neither SINGLE or NONE flags are set,\n\t\t// include a commitment to all outputs.\n\t\tpreimage.push(bip341_hash_outputs(output));\n\t}\n\n\t// At this step, we include the spend type.\n\tpreimage.push(Buff.num(spendType, 1));\n\n\tif (is_anypay) {\n\t\t// If ANYONE_CAN_PAY flag is set, then we will\n\t\t// provide a commitment to the input being signed.\n\t\tconst { value, script_pk } = get_prevout(txinput);\n\t\tpreimage.push(\n\t\t\tencode_txin_txid(txid), // Commit to the input txid.\n\t\t\tencode_txin_vout(vout), // Commit to the input vout index.\n\t\t\tencode_vout_value(value), // Commit to the input's prevout value.\n\t\t\tencode_script_data(script_pk), // Commit to the input's prevout script.\n\t\t\tencode_txin_sequence(sequence), // Commit to the input's sequence value.\n\t\t);\n\t} else {\n\t\t// Otherwise, we must have already included a commitment\n\t\t// to all inputs in the tx, so simply add a commitment to\n\t\t// the index of the input we are signing for.\n\t\tAssert.ok(typeof txindex === \"number\");\n\t\tpreimage.push(Buff.num(txindex, 4).reverse());\n\t}\n\n\tif (annex !== undefined) {\n\t\t// If an annex has been set, include it here.\n\t\tpreimage.push(annex);\n\t}\n\n\tif ((sigflag & 0x03) === 0x03) {\n\t\t// If the SINGLE flag is set, then include a\n\t\t// commitment to the output which is adjacent\n\t\t// to the input that we are signing for.\n\t\tAssert.ok(\n\t\t\ttypeof txindex === \"number\",\n\t\t\t\"txindex required for SIGHASH_SINGLE\",\n\t\t);\n\t\tAssert.ok(\n\t\t\ttxindex >= 0 && txindex < output.length,\n\t\t\t`txindex ${txindex} out of bounds for ${output.length} outputs`,\n\t\t);\n\t\tpreimage.push(bip341_hash_output(output[txindex]));\n\t}\n\n\tif (extension !== undefined) {\n\t\t// If we are extending this signature to include\n\t\t// other commitments (such as a tapleaf), then we\n\t\t// will add it to the preimage here.\n\t\tpreimage.push(\n\t\t\tBuff.bytes(extension), // Extention data (in bytes).\n\t\t\tBuff.num(key_version), // Key version (reserved for future upgrades).\n\t\t\tBuff.num(separator_pos, 4, \"le\"), // If OP_CODESEPARATOR is used, this must be set.\n\t\t);\n\t}\n\n\treturn Buff.join(preimage);\n}\n\nexport function bip341_hash_outpoints(vin: TxInput[]): Buff {\n\tconst stack = [];\n\tfor (const { txid, vout } of vin) {\n\t\tstack.push(encode_txin_txid(txid));\n\t\tstack.push(encode_txin_vout(vout));\n\t}\n\treturn sha256(Buff.join(stack));\n}\n\nexport function bip341_hash_sequence(vin: TxInput[]): Buff {\n\treturn sha256(...vin.map((vin) => encode_txin_sequence(vin.sequence)));\n}\n\nexport function bip341_hash_amounts(prevouts: TxOutput[]): Buff {\n\treturn sha256(...prevouts.map((prevout) => encode_vout_value(prevout.value)));\n}\n\nexport function bip341_hash_scripts(prevouts: TxOutput[]): Buff {\n\treturn sha256(\n\t\t...prevouts.map((prevout) => encode_script_data(prevout.script_pk)),\n\t);\n}\n\nexport function bip341_hash_outputs(vout: TxOutput[]): Buff {\n\tconst stack = [];\n\tfor (const { value, script_pk } of vout) {\n\t\tstack.push(encode_vout_value(value));\n\t\tstack.push(encode_script_data(script_pk));\n\t}\n\treturn sha256(...stack);\n}\n\nexport function bip341_hash_output(vout: TxOutput): Buff {\n\treturn sha256(\n\t\tencode_vout_value(vout.value),\n\t\tencode_script_data(vout.script_pk),\n\t);\n}\n","import { Buff } from \"@vbyte/buff\";\nimport { ECC } from \"@vbyte/micro-lib\";\nimport { SIGHASH_DEFAULT, SIGHASH_SEGWIT, SIGHASH_TAPROOT } from \"@/const.js\";\nimport { hash_segwit_tx } from \"@/lib/sighash/segwit.js\";\nimport { hash_taproot_tx } from \"@/lib/sighash/taproot.js\";\nimport { parse_tx } from \"@/lib/tx/parse.js\";\n\nimport type { SigHashOptions, TxData } from \"@/types/index.js\";\n\n/**\n * Regex pattern for valid 32-byte hex string (64 hex characters).\n * Used for secret key validation.\n */\nconst SECKEY_REGEX = /^[0-9a-fA-F]{64}$/;\n\n/**\n * Validate a secret key format.\n * @param seckey - The secret key to validate\n * @throws Error if the secret key is invalid\n */\nfunction validate_seckey(seckey: string): void {\n\tif (typeof seckey !== \"string\") {\n\t\tthrow new Error(\"Secret key must be a string\");\n\t}\n\tif (!SECKEY_REGEX.test(seckey)) {\n\t\tthrow new Error(\n\t\t\t\"Invalid secret key format: expected 32-byte hex string (64 characters)\",\n\t\t);\n\t}\n}\n\n/**\n * Validate sighash options.\n * @param options - The sighash options to validate\n * @param validFlags - Array of valid sighash flags\n * @throws Error if options are invalid\n */\nfunction validate_sighash_options(\n\toptions: SigHashOptions,\n\tvalidFlags: number[],\n): void {\n\tconst { sigflag, txindex } = options;\n\n\tif (sigflag !== undefined) {\n\t\tif (typeof sigflag !== \"number\" || !Number.isInteger(sigflag)) {\n\t\t\tthrow new Error(\"sigflag must be an integer\");\n\t\t}\n\t\t// Normalize sigflag for validation (remove ANYONECANPAY bit)\n\t\tconst normalizedFlag = sigflag & 0x7f;\n\t\tconst isAnypay = (sigflag & 0x80) === 0x80;\n\t\tconst baseFlag = isAnypay ? normalizedFlag | 0x80 : normalizedFlag;\n\n\t\tif (\n\t\t\t!validFlags.includes(baseFlag) &&\n\t\t\t!validFlags.includes(normalizedFlag)\n\t\t) {\n\t\t\tthrow new Error(`Invalid sigflag: ${sigflag}`);\n\t\t}\n\t}\n\n\tif (txindex !== undefined) {\n\t\tif (\n\t\t\ttypeof txindex !== \"number\" ||\n\t\t\t!Number.isInteger(txindex) ||\n\t\t\ttxindex < 0\n\t\t) {\n\t\t\tthrow new Error(\"txindex must be a non-negative integer\");\n\t\t}\n\t}\n}\n\n/**\n * Sign a transaction input using segwit (BIP143) signature hashing.\n * @param seckey - 32-byte secret key as hex string (64 characters)\n * @param txdata - Transaction data\n * @param options - Sighash options including txindex, sigflag, pubkey/script\n * @returns ECDSA signature with sighash flag appended\n * @throws Error if secret key format is invalid\n */\nexport function sign_segwit_tx(\n\tseckey: string,\n\ttxdata: TxData,\n\toptions: SigHashOptions,\n) {\n\tvalidate_seckey(seckey);\n\tvalidate_sighash_options(options, SIGHASH_SEGWIT);\n\n\tconst tx = parse_tx(txdata);\n\tconst msg = hash_segwit_tx(tx, options);\n\tconst sig = ECC.sign_ecdsa(seckey, msg).hex;\n\tconst flag = format_sigflag(options.sigflag ?? SIGHASH_DEFAULT);\n\treturn sig + flag;\n}\n\n/**\n * Sign a transaction input using taproot (BIP341) signature hashing.\n * @param seckey - 32-byte secret key as hex string (64 characters)\n * @param txdata - Transaction data\n * @param options - Sighash options including txindex, sigflag, extension\n * @returns Schnorr signature with optional sighash flag appended\n * @throws Error if secret key format is invalid\n */\nexport function sign_taproot_tx(\n\tseckey: string,\n\ttxdata: TxData,\n\toptions: SigHashOptions,\n) {\n\tvalidate_seckey(seckey);\n\tvalidate_sighash_options(options, SIGHASH_TAPROOT);\n\n\tconst tx = parse_tx(txdata);\n\tconst msg = hash_taproot_tx(tx, options);\n\tconst sig = ECC.sign_bip340(seckey, msg).hex;\n\tconst flag = format_sigflag(options.sigflag ?? 0);\n\treturn sig + flag;\n}\n\nfunction format_sigflag(flag: number) {\n\treturn flag !== 0 ? Buff.num(flag, 1).hex : \"\";\n}\n","import { Buff, type Bytes } from \"@vbyte/buff\";\nimport { TAPLEAF_VERSIONS } from \"@/const.js\";\nimport { is_valid_script } from \"@/lib/script/decode.js\";\n\nimport type {\n\tSpendScriptType,\n\tWitnessData,\n\tWitnessVersion,\n} from \"@/types/index.js\";\n\nexport function parse_witness(witness: Bytes[]): WitnessData {\n\t// Parse the witness data.\n\tconst elems = witness.map((e) => Buff.bytes(e));\n\tconst stack = witness.map((e) => Buff.bytes(e).hex);\n\tconst annex = parse_annex_data(elems);\n\tif (annex !== null) elems.pop();\n\tconst cblock = parse_cblock_data(elems);\n\tif (cblock !== null) elems.pop();\n\tconst type = parse_witness_type(elems, cblock);\n\tconst version = parse_witness_version(type);\n\tconst script = parse_witness_script(elems, type);\n\tif (script !== null) elems.pop();\n\tconst params = elems.map((e) => e.hex);\n\treturn { annex, cblock, params, script, stack, type, version };\n}\n\nfunction parse_annex_data(data: Uint8Array[]): string | null {\n\t// Get the last element of the array.\n\tconst elem = data.at(-1);\n\t// Check if the element fits the annex format.\n\tif (data.length > 1 && elem instanceof Uint8Array && elem[0] === 0x50) {\n\t\t// Return the element.\n\t\treturn new Buff(elem).hex;\n\t} else {\n\t\t// Return null.\n\t\treturn null;\n\t}\n}\n\nfunction parse_cblock_data(data: Uint8Array[]): string | null {\n\tconst elem = data.at(-1);\n\tif (\n\t\tdata.length > 1 &&\n\t\telem instanceof Uint8Array &&\n\t\telem.length > 32 &&\n\t\tTAPLEAF_VERSIONS.includes(elem[0] & 0xfe)\n\t) {\n\t\t// Return the element.\n\t\treturn new Buff(elem).hex;\n\t} else {\n\t\t// Return null.\n\t\treturn null;\n\t}\n}\n\nfunction parse_witness_script(\n\telems: Uint8Array[],\n\ttype: SpendScriptType | null,\n) {\n\tlet script: Uint8Array | undefined;\n\tswitch (type) {\n\t\tcase \"p2ts\":\n\t\t\tscript = elems.at(-1);\n\t\t\tbreak;\n\t\tcase \"p2wsh\":\n\t\t\tscript = elems.at(-1);\n\t\t\tbreak;\n\t}\n\treturn script !== undefined ? new Buff(script).hex : null;\n}\n\nfunction parse_witness_type(\n\telems: Uint8Array[],\n\tcblock: string | null,\n): SpendScriptType | null {\n\t// Get the important elements of the witness.\n\tconst param_0 = elems.at(0),\n\t\tparam_1 = elems.at(1),\n\t\tparam_x = elems.at(-1);\n\t// If the cblock is present and the last element exists:\n\tif (cblock !== null && param_x !== undefined) {\n\t\treturn \"p2ts\";\n\t\t// If the witness elements match the profile of a p2w-pkh:\n\t\t// ECDSA signatures are 71-73 bytes (DER-encoded), Schnorr are 64-65 bytes\n\t} else if (\n\t\telems.length === 2 &&\n\t\tparam_0 !== undefined &&\n\t\tparam_1 !== undefined &&\n\t\tparam_0.length >= 71 &&\n\t\tparam_0.length <= 73 &&\n\t\tparam_1.length === 33\n\t) {\n\t\treturn \"p2wpkh\";\n\t\t// If the witness elements match the profile of a p2tr-pk (Schnorr 64 or 65 bytes):\n\t} else if (\n\t\telems.length === 1 &&\n\t\tparam_0 !== undefined &&\n\t\t(param_0.length === 64 || param_0.length === 65)\n\t) {\n\t\treturn \"p2tr\";\n\t\t// If there is at least two witness elements:\n\t} else if (\n\t\telems.length > 1 &&\n\t\tparam_x !== undefined &&\n\t\tis_valid_script(param_x)\n\t) {\n\t\treturn \"p2wsh\";\n\t\t// If the witness elements don't match any known profile:\n\t} else {\n\t\treturn null;\n\t}\n}\n\nfunction parse_witness_version(\n\ttype: SpendScriptType | null,\n): WitnessVersion | null {\n\tif (type === null) return null;\n\tif (type.startsWith(\"p2w\")) return 0;\n\tif (type.startsWith(\"p2t\")) return 1;\n\treturn null;\n}\n","import { Buff, Stream } from \"@vbyte/buff\";\nimport { Assert, ECC } from \"@vbyte/micro-lib\";\nimport { parse_witness } from \"@/lib/witness/parse.js\";\nimport type { ControlBlock } from \"@/types/index.js\";\nimport {\n\tencode_tapbranch,\n\tencode_tapscript,\n\tencode_taptweak,\n} from \"./encode.js\";\n\n/**\n * Parse a taproot script-path witness and extract spending data.\n * Computes the tapkey from the control block and verifies the merkle proof.\n *\n * @param witness - Array of witness stack elements (hex strings)\n * @returns Parsed taproot spending data including cblock, params, script, tapkey, and tweak\n * @throws Error if control block or script is missing\n *\n * @example\n * ```typescript\n * const witness = [signature, tapscript, controlBlock]\n * const { tapkey, script, params } = parse_taproot_witness(witness)\n * ```\n */\nexport function parse_taproot_witness(witness: string[]) {\n\tconst { cblock, params, script } = parse_witness(witness);\n\n\tAssert.exists(cblock, \"cblock is null\");\n\tAssert.exists(script, \"script is null\");\n\n\tconst cblk = parse_cblock(cblock);\n\tconst target = encode_tapscript(script, cblk.version);\n\n\tlet branch = target.hex;\n\n\tfor (const leaf of cblk.path) {\n\t\tbranch = encode_tapbranch(branch, leaf).hex;\n\t}\n\n\tconst tweak = encode_taptweak(cblk.int_key, branch);\n\tconst tapkey = ECC.tweak_pubkey(cblk.int_key, tweak, \"bip340\");\n\n\tparams.map((e) => Buff.bytes(e).hex);\n\n\treturn { cblock: cblk, params, script, tapkey: tapkey.hex, tweak: tweak.hex };\n}\n\n/**\n * Parse a taproot control block into its components.\n * Extracts version, parity, internal pubkey, and merkle path.\n *\n * @param cblock - Control block data (hex string or bytes)\n * @returns Parsed control block with int_key, path, parity, and version\n * @throws Error if control block has invalid format or non-empty remainder\n *\n * @example\n * ```typescript\n * const cblock = 'c0' + internalPubkey + merkleProof\n * const { int_key, path, version, parity } = parse_cblock(cblock)\n * ```\n */\nexport function parse_cblock(cblock: string | Uint8Array): ControlBlock {\n\tconst buffer = new Stream(cblock);\n\tconst cbyte = buffer.read(1).num;\n\tconst int_key = buffer.read(32).hex;\n\tconst [version, parity] = parse_cblock_parity(cbyte);\n\tconst path = [];\n\twhile (buffer.size >= 32) {\n\t\tpath.push(buffer.read(32).hex);\n\t}\n\tif (buffer.size !== 0) {\n\t\tthrow new Error(`Non-empty buffer on control block: ${String(buffer)}`);\n\t}\n\treturn { int_key, path, parity, version };\n}\n\n/**\n * Parse the control block version byte to extract version and parity.\n * Even bytes indicate even parity (0x02), odd bytes indicate odd parity (0x03).\n *\n * @param cbits - Control block version byte\n * @returns Tuple of [version, parity] where version has parity bit cleared\n *\n * @example\n * ```typescript\n * parse_cblock_parity(0xc0) // [0xc0, 0x02] - even\n * parse_cblock_parity(0xc1) // [0xc0, 0x03] - odd\n * ```\n */\nexport function parse_cblock_parity(cbits: number) {\n\treturn cbits % 2 === 0 ? [cbits - 0, 0x02] : [cbits - 1, 0x03];\n}\n\n/**\n * Parse a compressed public key to extract its parity bit.\n * Returns 0 for even y-coordinate (0x02 prefix), 1 for odd (0x03 prefix).\n *\n * @param pubkey - 33-byte compressed public key (hex string or bytes)\n * @returns Parity bit: 0 for even, 1 for odd\n * @throws Error if pubkey is not 33 bytes or has invalid prefix\n *\n * @example\n * ```typescript\n * parse_pubkey_parity('02' + x_coordinate) // 0 (even)\n * parse_pubkey_parity('03' + x_coordinate) // 1 (odd)\n * ```\n */\nexport function parse_pubkey_parity(pubkey: string | Uint8Array): number {\n\tAssert.size(pubkey, 33, \"invalid pubkey size\");\n\tconst [parity] = Buff.bytes(pubkey);\n\tif (parity === 0x02) return 0;\n\tif (parity === 0x03) return 1;\n\tthrow new Error(`Invalid parity bit: ${String(parity)}`);\n}\n","import { Buff } from \"@vbyte/buff\";\nimport type { MerkleProof, TapTree } from \"@/types/index.js\";\nimport { encode_tapbranch } from \"./encode.js\";\n\n/** Maximum taproot tree depth (BIP-341 limit) */\nconst MAX_TAPROOT_DEPTH = 128;\n\n/**\n * Get the root of a taproot tree.\n * @param leaves - The leaves of the tree.\n * @returns The root of the tree.\n */\nexport function get_merkle_root(leaves: TapTree) {\n\t// Process the merkle tree, and return the root.\n\treturn merkleize(leaves)[0];\n}\n\n/**\n * Process a taproot tree into a merkle proof.\n * @param taptree - The leaves of the tree.\n * @param target - The target leaf of the tree.\n * @param path - The recursive path of the tree.\n * @param depth - Current recursion depth (for limit checking).\n * @returns The root of the tree.\n * @throws Error if tree depth exceeds MAX_TAPROOT_DEPTH (128).\n */\nexport function merkleize(\n\ttaptree: TapTree,\n\ttarget?: string,\n\tpath: string[] = [],\n\tdepth: number = 0,\n): MerkleProof {\n\t// Check depth limit to prevent stack overflow attacks\n\tif (depth > MAX_TAPROOT_DEPTH) {\n\t\tthrow new Error(\n\t\t\t`Taproot tree depth ${depth} exceeds maximum ${MAX_TAPROOT_DEPTH}`,\n\t\t);\n\t}\n\n\t// Initialize the leaves and tree arrays.\n\tconst leaves: string[] = [];\n\tconst tree: string[] = [];\n\t// If there are no leaves, throw an error.\n\tif (taptree.length < 1) {\n\t\tthrow new Error(\"Tree is empty!\");\n\t}\n\t// Crawl through the tree, and find each leaf.\n\tfor (let i = 0; i < taptree.length; i++) {\n\t\t// Get the current leaf as bytes.\n\t\tconst bytes = taptree[i];\n\t\t// If the leaf is an array,\n\t\tif (Array.isArray(bytes)) {\n\t\t\t// Recursively process the nested tree (with incremented depth).\n\t\t\tconst [tapleaf, new_target, branches] = merkleize(\n\t\t\t\tbytes,\n\t\t\t\ttarget,\n\t\t\t\t[],\n\t\t\t\tdepth + 1,\n\t\t\t);\n\t\t\t// Update the target leaf.\n\t\t\ttarget = new_target;\n\t\t\t// Add the nested tapleaf to the leaves array.\n\t\t\tleaves.push(tapleaf);\n\t\t\t// For each branch node,\n\t\t\tfor (const branch of branches) {\n\t\t\t\t// Add the branch to the path.\n\t\t\t\tpath.push(branch);\n\t\t\t}\n\t\t} else {\n\t\t\t// Convert the leaf to a hex string.\n\t\t\tconst leaf = Buff.bytes(bytes).hex;\n\t\t\t// Add the leaf to the leaves array.\n\t\t\tleaves.push(leaf);\n\t\t}\n\t}\n\n\t// If there is only one leaf,\n\tif (leaves.length === 1) {\n\t\t// Return the leaf as the root.\n\t\treturn [leaves[0], target, path];\n\t}\n\t// Ensure the tree is sorted at this point.\n\tleaves.sort();\n\t// Ensure the tree is balanced evenly.\n\tif (leaves.length % 2 !== 0) {\n\t\t// If uneven, duplicate the last leaf.\n\t\tleaves.push(leaves[leaves.length - 1]);\n\t}\n\t// Sort through the leaves (two at a time).\n\tfor (let i = 0; i < leaves.length - 1; i += 2) {\n\t\t// Compute two leaves into a branch.\n\t\tconst branch = encode_tapbranch(leaves[i], leaves[i + 1]).hex;\n\t\t// Push our branch to the tree.\n\t\ttree.push(branch);\n\t\t// Check if a proof target is specified.\n\t\tif (typeof target === \"string\") {\n\t\t\t// Check if this branch is part of our proofs.\n\t\t\tif (target === leaves[i]) {\n\t\t\t\t// If so, include right-side of branch.\n\t\t\t\tpath.push(leaves[i + 1]);\n\t\t\t\ttarget = branch;\n\t\t\t} else if (target === leaves[i + 1]) {\n\t\t\t\t// If so, include left-side of branch.\n\t\t\t\tpath.push(leaves[i]);\n\t\t\t\ttarget = branch;\n\t\t\t}\n\t\t}\n\t}\n\t// Recursively process the tree (with incremented depth).\n\treturn merkleize(tree, target, path, depth + 1);\n}\n","import { Buff, type Bytes } from \"@vbyte/buff\";\nimport { Assert, ECC } from \"@vbyte/micro-lib\";\nimport { TAPLEAF_DEFAULT_VERSION } from \"@/const.js\";\nimport * as Schema from \"@/schema/index.js\";\nimport type { TaprootConfig, TaprootContext } from \"@/types/index.js\";\n\nimport { encode_tapbranch, encode_taptweak } from \"./encode.js\";\n\nimport { parse_cblock, parse_pubkey_parity } from \"./parse.js\";\nimport { merkleize } from \"./tree.js\";\n\nconst DEFAULT_VERSION = TAPLEAF_DEFAULT_VERSION;\n\nexport function create_taproot(config: TaprootConfig): TaprootContext {\n\tSchema.taproot.config.parse(config);\n\n\tconst { pubkey, version = DEFAULT_VERSION } = config;\n\n\tconst leaves = config.leaves ?? [];\n\n\tconst target =\n\t\tconfig.target !== undefined ? Buff.bytes(config.target).hex : undefined;\n\n\tlet path: string[] = [],\n\t\ttaproot: string | undefined;\n\n\tif (leaves.length > 0) {\n\t\t// Merkelize the leaves into a root hash (with proof).\n\t\tconst [root, _, proofs] = merkleize(leaves, target);\n\t\t// Get the control path from the merkelized output.\n\t\tpath = proofs;\n\t\t// Get the tapped key from the internal key.\n\t\ttaproot = root;\n\t} else {\n\t\t// Get the tapped key from the single tapleaf.\n\t\ttaproot = target;\n\t}\n\n\tconst taptweak = encode_taptweak(pubkey, taproot);\n\tconst twk_key = ECC.tweak_pubkey(pubkey, taptweak, \"ecdsa\");\n\tconst parity = parse_pubkey_parity(twk_key);\n\tconst tapkey = ECC.serialize_pubkey(twk_key, \"bip340\");\n\t// Get the block version / parity bit.\n\tconst cbit = Buff.num(version + parity);\n\t// Stack the initial control block data.\n\tconst block: Bytes[] = [cbit, Buff.bytes(pubkey)];\n\t// If there is more than one path, add to block.\n\tif (path.length > 0) {\n\t\tblock.push(...path);\n\t}\n\t// Merge the data together into one array.\n\tconst cblock = Buff.join(block);\n\n\treturn {\n\t\tint_key: Buff.bytes(pubkey).hex,\n\t\tpath,\n\t\tparity,\n\t\ttaproot: taproot ?? null,\n\t\tcblock: cblock.hex,\n\t\ttapkey: tapkey.hex,\n\t\ttaptweak: taptweak.hex,\n\t};\n}\n\nexport function verify_taproot(\n\ttapkey: string,\n\ttarget: string,\n\tcblock: string,\n): boolean {\n\tAssert.size(tapkey, 32);\n\tconst { parity, path, int_key } = parse_cblock(cblock);\n\n\tconst ext_key = Buff.join([parity, tapkey]);\n\n\tlet branch = Buff.bytes(target).hex;\n\n\tfor (const leaf of path) {\n\t\tbranch = encode_tapbranch(branch, leaf).hex;\n\t}\n\n\tconst tap_tweak = encode_taptweak(int_key, branch);\n\tconst tweaked_key = ECC.tweak_pubkey(int_key, tap_tweak, \"ecdsa\");\n\n\treturn ext_key.hex === tweaked_key.hex;\n}\n","import { Buff, type Bytes } from \"@vbyte/buff\";\nimport { ECC } from \"@vbyte/micro-lib\";\nimport { hash160 } from \"@vbyte/micro-lib/hash\";\nimport { get_lock_script_type } from \"@/lib/script/lock.js\";\nimport { hash_segwit_tx } from \"@/lib/sighash/segwit.js\";\nimport { hash_taproot_tx } from \"@/lib/sighash/taproot.js\";\nimport { verify_taproot } from \"@/lib/taproot/cblock.js\";\nimport { encode_tapscript } from \"@/lib/taproot/encode.js\";\nimport { parse_tx } from \"@/lib/tx/index.js\";\nimport { parse_witness } from \"@/lib/witness/parse.js\";\n\nimport type {\n\tSigHashOptions,\n\tTxData,\n\tTxInput,\n\tWitnessData,\n} from \"@/types/index.js\";\n\nexport interface VerifyOptions extends SigHashOptions {\n\t/** Throw an error on verification failure (default: false) */\n\tthrows?: boolean;\n}\n\nexport interface VerifyResult {\n\t/** Whether all signatures are valid */\n\tvalid: boolean;\n\t/** Per-input verification results */\n\tinputs: InputVerifyResult[];\n\t/** Error message if verification failed */\n\terror?: string;\n}\n\nexport interface InputVerifyResult {\n\t/** Input index */\n\tindex: number;\n\t/** Whether the signature is valid */\n\tvalid: boolean;\n\t/** Spend type detected */\n\ttype?: string | null;\n\t/** Error message if verification failed */\n\terror?: string;\n}\n\n/**\n * Verify all signatures in a transaction.\n * @param txdata - Transaction data (hex, bytes, or TxData object)\n * @param options - Verification options\n * @returns Verification result with per-input details\n */\nexport function verify_tx(\n\ttxdata: TxData | Bytes,\n\toptions: VerifyOptions = {},\n): VerifyResult {\n\tconst { throws = false } = options;\n\n\tconst tx = parse_tx(txdata);\n\tconst inputs: InputVerifyResult[] = [];\n\tlet allValid = true;\n\n\tfor (let i = 0; i < tx.vin.length; i++) {\n\t\tconst vin = tx.vin[i];\n\n\t\t// Skip coinbase inputs\n\t\tif (vin.coinbase !== null) {\n\t\t\tinputs.push({ index: i, valid: true, type: \"coinbase\" });\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst result = verify_input(tx, vin, i, options);\n\t\tinputs.push(result);\n\n\t\tif (!result.valid) {\n\t\t\tallValid = false;\n\t\t\tif (throws) {\n\t\t\t\tthrow new Error(`Input ${i} verification failed: ${result.error}`);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tvalid: allValid,\n\t\tinputs,\n\t\terror: allValid ? undefined : \"One or more inputs failed verification\",\n\t};\n}\n\n/**\n * Verify a single input signature.\n */\nfunction verify_input(\n\ttx: TxData,\n\tvin: TxInput,\n\tindex: number,\n\toptions: VerifyOptions,\n): InputVerifyResult {\n\ttry {\n\t\tconst { witness = [] } = vin;\n\n\t\t// No witness means no signature to verify\n\t\tif (witness.length === 0) {\n\t\t\treturn { index, valid: true, type: null };\n\t\t}\n\n\t\t// Parse the witness data\n\t\tconst witnessData = parse_witness(witness.map((e) => Buff.hex(e)));\n\t\tconst { type, version } = witnessData;\n\n\t\t// No recognizable type means we can't verify\n\t\tif (type === null || version === null) {\n\t\t\treturn { index, valid: false, type, error: \"Unknown witness type\" };\n\t\t}\n\n\t\t// Get the prevout script\n\t\tconst prevout = vin.prevout;\n\t\tif (prevout === null || prevout === undefined) {\n\t\t\treturn { index, valid: false, type, error: \"Missing prevout data\" };\n\t\t}\n\n\t\tconst scriptType = get_lock_script_type(prevout.script_pk);\n\n\t\t// Dispatch to the appropriate verification method\n\t\tif (version === 0) {\n\t\t\treturn verify_segwit_input(tx, vin, index, witnessData, options);\n\t\t} else if (version === 1) {\n\t\t\treturn verify_taproot_input(\n\t\t\t\ttx,\n\t\t\t\tvin,\n\t\t\t\tindex,\n\t\t\t\twitnessData,\n\t\t\t\tscriptType,\n\t\t\t\toptions,\n\t\t\t);\n\t\t}\n\n\t\treturn {\n\t\t\tindex,\n\t\t\tvalid: false,\n\t\t\ttype,\n\t\t\terror: `Unsupported witness version: ${version}`,\n\t\t};\n\t} catch (err) {\n\t\tconst error = err instanceof Error ? err.message : String(err);\n\t\treturn { index, valid: false, error };\n\t}\n}\n\n/**\n * Verify a segwit (v0) input signature using ECDSA.\n */\nfunction verify_segwit_input(\n\ttx: TxData,\n\tvin: TxInput,\n\tindex: number,\n\twitnessData: WitnessData,\n\toptions: VerifyOptions,\n): InputVerifyResult {\n\tconst { type, params, script } = witnessData;\n\n\tif (params.length < 1) {\n\t\treturn { index, valid: false, type, error: \"Missing signature in witness\" };\n\t}\n\n\t// Extract signature and sighash flag\n\tconst sigHex = params[0];\n\tconst { signature, sigflag } = parse_ecdsa_signature(sigHex);\n\n\t// Get pubkey and script for hash calculation\n\tlet pubkey: string;\n\tlet hashScript: string;\n\n\tif (type === \"p2wpkh\") {\n\t\t// P2WPKH: pubkey is second witness element\n\t\tif (params.length < 2) {\n\t\t\treturn {\n\t\t\t\tindex,\n\t\t\t\tvalid: false,\n\t\t\t\ttype,\n\t\t\t\terror: \"Missing pubkey in P2WPKH witness\",\n\t\t\t};\n\t\t}\n\t\tpubkey = params[1];\n\n\t\t// P2WPKH script is derived from pubkey hash\n\t\tconst pkh = hash160(pubkey).hex;\n\t\thashScript = `76a914${pkh}88ac`;\n\t} else if (type === \"p2wsh\") {\n\t\t// P2WSH: script is witness script, need to find pubkey in params\n\t\tif (script === null) {\n\t\t\treturn {\n\t\t\t\tindex,\n\t\t\t\tvalid: false,\n\t\t\t\ttype,\n\t\t\t\terror: \"Missing script in P2WSH witness\",\n\t\t\t};\n\t\t}\n\t\thashScript = script;\n\n\t\t// For P2WSH, we need to extract the pubkey from the script or params\n\t\t// This is a simplified approach - in practice the pubkey needs to be specified\n\t\tif (params.length >= 2) {\n\t\t\tpubkey = params[1];\n\t\t} else {\n\t\t\treturn {\n\t\t\t\tindex,\n\t\t\t\tvalid: false,\n\t\t\t\ttype,\n\t\t\t\terror: \"Missing pubkey in P2WSH witness\",\n\t\t\t};\n\t\t}\n\t} else {\n\t\treturn {\n\t\t\tindex,\n\t\t\tvalid: false,\n\t\t\ttype,\n\t\t\terror: `Unexpected segwit type: ${type}`,\n\t\t};\n\t}\n\n\t// Calculate the sighash\n\tconst sighashOptions: SigHashOptions = {\n\t\t...options,\n\t\ttxindex: index,\n\t\ttxinput: vin,\n\t\tpubkey: type === \"p2wpkh\" ? pubkey : undefined,\n\t\tscript: type === \"p2wsh\" ? hashScript : undefined,\n\t\tsigflag,\n\t};\n\n\tconst hash = hash_segwit_tx(tx, sighashOptions);\n\n\t// Verify the ECDSA signature\n\tconst isValid = ECC.verify_ecdsa(signature, hash, pubkey);\n\n\treturn {\n\t\tindex,\n\t\tvalid: isValid,\n\t\ttype,\n\t\terror: isValid ? undefined : \"Invalid ECDSA signature\",\n\t};\n}\n\n/**\n * Verify a taproot (v1) input signature using Schnorr.\n */\nfunction verify_taproot_input(\n\ttx: TxData,\n\tvin: TxInput,\n\tindex: number,\n\twitnessData: WitnessData,\n\t_scriptType: string | null,\n\toptions: VerifyOptions,\n): InputVerifyResult {\n\tconst { type, params, script, cblock } = witnessData;\n\n\tif (vin.prevout == null) {\n\t\treturn {\n\t\t\tindex,\n\t\t\tvalid: false,\n\t\t\ttype,\n\t\t\terror: \"Missing prevout for taproot verification\",\n\t\t};\n\t}\n\tconst prevout = vin.prevout;\n\n\tif (params.length < 1) {\n\t\treturn { index, valid: false, type, error: \"Missing signature in witness\" };\n\t}\n\n\t// Extract signature and sighash flag\n\tconst sigHex = params[0];\n\tconst { signature, sigflag } = parse_schnorr_signature(sigHex);\n\n\t// Get the tapkey from the prevout script (remove 5120 prefix)\n\tconst tapkey = prevout.script_pk.slice(4);\n\n\tlet pubkey: string;\n\tlet extension: string | undefined;\n\n\tif (type === \"p2tr\") {\n\t\t// Key-path spend: pubkey is the tapkey\n\t\tpubkey = tapkey;\n\t} else if (type === \"p2ts\") {\n\t\t// Script-path spend: verify control block and get internal key\n\t\tif (cblock === null || script === null) {\n\t\t\treturn {\n\t\t\t\tindex,\n\t\t\t\tvalid: false,\n\t\t\t\ttype,\n\t\t\t\terror: \"Missing cblock or script in script-path spend\",\n\t\t\t};\n\t\t}\n\n\t\t// Verify the control block path\n\t\tconst target = encode_tapscript(script).hex;\n\t\tconst pathValid = verify_taproot(tapkey, target, cblock);\n\n\t\tif (!pathValid) {\n\t\t\treturn {\n\t\t\t\tindex,\n\t\t\t\tvalid: false,\n\t\t\t\ttype,\n\t\t\t\terror: \"Control block verification failed\",\n\t\t\t};\n\t\t}\n\n\t\t// For script-path, we need a pubkey from the script or additional witness elements\n\t\t// The pubkey for signing is usually in the additional params\n\t\tif (params.length >= 2 && params[1].length === 64) {\n\t\t\tpubkey = params[1];\n\t\t} else {\n\t\t\t// Fallback to tapkey for verification\n\t\t\tpubkey = tapkey;\n\t\t}\n\n\t\t// Set the extension (tapleaf hash)\n\t\textension = target;\n\t} else {\n\t\treturn {\n\t\t\tindex,\n\t\t\tvalid: false,\n\t\t\ttype,\n\t\t\terror: `Unexpected taproot type: ${type}`,\n\t\t};\n\t}\n\n\t// Calculate the sighash\n\tconst sighashOptions: SigHashOptions = {\n\t\t...options,\n\t\ttxindex: index,\n\t\ttxinput: vin,\n\t\tsigflag,\n\t\textension: extension,\n\t\tscript: type === \"p2ts\" ? (script ?? undefined) : undefined,\n\t};\n\n\tconst hash = hash_taproot_tx(tx, sighashOptions);\n\n\t// Verify the Schnorr signature\n\tconst isValid = ECC.verify_bip340(signature, hash, pubkey);\n\n\treturn {\n\t\tindex,\n\t\tvalid: isValid,\n\t\ttype,\n\t\terror: isValid ? undefined : \"Invalid Schnorr signature\",\n\t};\n}\n\n/**\n * Parse an ECDSA DER-encoded signature and extract sighash flag.\n */\nfunction parse_ecdsa_signature(sigHex: string): {\n\tsignature: string;\n\tsigflag: number;\n} {\n\t// ECDSA sigs are DER-encoded, last byte is sighash flag\n\tconst sigBytes = Buff.hex(sigHex);\n\tconst sigflag = sigBytes.at(-1) ?? 0x01;\n\tconst signature = sigBytes.slice(0, -1).hex;\n\treturn { signature, sigflag };\n}\n\n/**\n * Parse a Schnorr signature and extract sighash flag.\n */\nfunction parse_schnorr_signature(sigHex: string): {\n\tsignature: string;\n\tsigflag: number;\n} {\n\t// Schnorr sigs are 64 bytes, optional sighash byte appended\n\tconst sigBytes = Buff.hex(sigHex);\n\n\tif (sigBytes.length === 64) {\n\t\t// No sighash appended, default to SIGHASH_DEFAULT (0x00)\n\t\treturn { signature: sigHex, sigflag: 0x00 };\n\t} else if (sigBytes.length === 65) {\n\t\t// Sighash byte appended\n\t\tconst sigflag = sigBytes.at(-1) ?? 0x00;\n\t\tif (sigflag === 0x00) {\n\t\t\tthrow new Error(\"0x00 is not a valid appended sigflag\");\n\t\t}\n\t\tconst signature = sigBytes.slice(0, 64).hex;\n\t\treturn { signature, sigflag };\n\t}\n\n\tthrow new Error(`Invalid Schnorr signature length: ${sigBytes.length}`);\n}\n","import { Buff, type Bytes } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/micro-lib\";\n\nimport type { WitnessSize } from \"@/types/index.js\";\n\nconst WIT_LENGTH_BYTE = 1;\n\nexport function get_witness_size(witness: Bytes[]): WitnessSize {\n\tconst stack = witness.map((e) => Buff.bytes(e));\n\tconst size = stack.reduce((prev, next) => prev + next.length, 0);\n\tconst vsize = Math.ceil(WIT_LENGTH_BYTE + size / 4);\n\treturn { total: size, vsize };\n}\n\nexport function assert_witness(witness: unknown): asserts witness is Bytes[] {\n\tAssert.ok(Array.isArray(witness), \"witness must be an array\");\n\tAssert.ok(\n\t\twitness.every((e) => Buff.is_bytes(e)),\n\t\t\"witness must be an array of strings or bytes\",\n\t);\n}\n"],"names":["COINBASE","TXID","repeat","VOUT","DEFAULT","LOCKTIME","SEQUENCE","VERSION","TAPLEAF_VERSIONS","LOCK_SCRIPT_TYPE","P2PKH","P2SH","P2WPKH","P2WSH","P2TR","OPRETURN","LOCK_SCRIPT_REGEX","SIGHASH_SEGWIT","SIGHASH_TAPROOT","MAX_SCRIPT_SIZE","MAX_VARINT_SIZE","Check","Assert","P2TS","GLOBAL_BASE","GLOBAL_WIT","TXIN_BASE","TXOUT_BASE","is_hex","input","match","length","is_bytes","Uint8Array","Array","isArray","every","e","within_size","data","size","TypeError","hex","Error","bytes","String","is_json","str","JSON","parse","is_safe_int","num","Number","MAX_SAFE_INTEGER","_0n","BigInt","_255n","_256n","big_to_bytes","big","endian","undefined","get_big_size","use_le","buffer","ArrayBuffer","dataView","DataView","offset","byte","setUint8","bigint_replacer","_","v","bigint_reviver","test","slice","num_to_bytes","get_num_size","hex_to_bytes","hexstr","len","get_hex_size","use_be","i","char","substring","parseInt","fill","set","create_bytes","ec","TextEncoder","dc","TextDecoder","str_to_bytes","encode","bytes_to_str","decode","Buff","this","number","bigint","bin","uint","binary","bins","split","map","ct","j","Lib.bin_to_bytes","u8a","Lib.str_to_bytes","json","replacer","Lib.bigint_replacer","stringify","chunk","payload","chunk_size","total_size","chunks","data_blob","count","idx","subarray","Lib.split_bytes","Lib.buffer","is_equal","a","b","random","isInteger","crypto","getRandomValues","pcrypto","randomBytes","Lib.get_random_bytes","now","stamp","Math","floor","Date","constructor","super","arr","to_arr","to_big","to_bin","to_hex","to_num","to_str","to_u8a","Lib.bytes_to_big","reverse","chars","toString","padStart","Lib.bytes_to_hex","to_json","reviver","Lib.bigint_reviver","Lib.bytes_to_str","Lib.bytes_to_num","join","Lib.bytes_to_bin","append","equals","prepend","prefix_varint","varint","create_varint","array","start","end","begin","toJSON","from","of","args","joined","reduce","buff","Lib.join_bytes","sort","Stream","peek","read","read_varint","get_lock_script_type","script","type","regex","Object","entries","get_lock_script_version","at","is_p2pkh_script","p2pkh","is_p2sh_script","p2sh","is_p2wpkh_script","p2wpkh","is_p2wsh_script","p2wsh","is_p2tr_script","p2tr","sort_obj","obj","Map","keys","filter","value","sorted","key","Test","is_object","is_string","is_number","isNaN","exists","is_deep_equal","has_items","is_bigint","is_uchar","is_ushort","is_uint","is_u8a","is_base58","is_base64","is_b64url","is_bech32","is_hash","ok","message","msg","is_empty","is_instance","name","err_msg","globalThis","isBytes","isView","anumber","n","isSafeInteger","abytes","lengths","includes","ahash","h","create","outputLen","blockLen","aexists","instance","checkFinished","destroyed","finished","clean","arrays","createView","byteOffset","byteLength","rotr","word","shift","rotl","hasHexBuiltin","toHex","fromHex","hexes","bytesToHex","asciis","asciiToBase16","ch","hexToBytes","hl","al","ai","hi","n1","charCodeAt","n2","utf8ToBytes","toBytes","concatBytes","sum","res","pad","Hash","createHasher","hashCons","hashC","update","digest","tmp","bytesLength","Chi","c","Maj","HashMD","padOffset","isLE","pos","view","take","min","process","roundClean","digestInto","out","aoutput","setBigUint64","_32n","_u32_max","wh","wl","l","setUint32","oview","outLen","state","get","destroy","_cloneInto","to","clone","SHA256_IV","Uint32Array","SHA256_K","SHA256_W","SHA256","A","B","C","D","E","F","G","H","getUint32","W15","W2","s0","s1","T1","T2","sha256","HMAC","hash","_key","iHash","oHash","buf","getPrototypeOf","hmac","_1n","_abool2","title","_abytes2","isBytes_","needsLen","numberToHexUnpadded","hexToNumber","bytesToNumberBE","bytesToHex_","bytesToNumberLE","abytes_","numberToBytesBE","hexToBytes_","numberToBytesLE","ensureBytes","expectedLength","isPosBig","inRange","max","bitLen","bitMask","_validateObject","object","fields","optFields","checkField","fieldName","expectedType","isOpt","val","current","forEach","k","memoized","fn","WeakMap","arg","computed","_2n","_3n","_4n","_5n","_7n","_8n","_9n","_16n","mod","result","pow2","x","power","modulo","invert","u","r","m","assertIsSquare","Fp","root","eql","sqr","sqrt3mod4","p1div4","ORDER","pow","sqrt5mod8","p5div8","mul","nv","sub","ONE","tonelliShanks","P","Q","S","Z","_Fp","Field","FpLegendre","cc","Q1div2","is0","M","t","R","ZERO","t_tmp","exponent","FpSqrt","Fp_","tn","c1","neg","c2","c3","c4","tv1","tv2","tv3","tv4","e1","e2","cmov","e3","sqrt9mod16","FIELD_FIELDS","FpInvertBatch","nums","passZero","inverted","multipliedAcc","acc","invertedAcc","inv","reduceRight","p1mod2","powered","yes","zero","no","nLength","nBitLength","_nBitLength","nByteLength","ceil","bitLenOrOpts","opts","_nbitLength","_sqrt","allowedLengths","modFromBytes","sqrt","_opts","BITS","BYTES","sqrtP","f","freeze","MASK","isValid","isValidNot0","isOdd","lhs","rhs","add","p","d","FpPow","div","sqrN","addN","subN","mulN","fromBytes","skipValidation","padded","scalar","invertBatch","lst","getFieldBytesLength","fieldOrder","bitLength","getMinHashLength","mapHashToField","fieldLen","minLen","reduced","negateCt","condition","item","negate","normalizeZ","points","invertedZs","fromAffine","toAffine","validateW","W","bits","calcWOpts","scalarBits","maxNumber","windows","windowSize","mask","shiftBy","calcOffsets","window","wOpts","wbits","nextN","offsetStart","abs","isZero","isNeg","isNegF","offsetF","pointPrecomputes","pointWindowSizes","getW","assert0","wNAF","Point","BASE","Fn","_unsafeLadder","elm","double","precomputeWindow","point","base","push","precomputes","wo","wNAFUnsafe","getPrecomputes","transform","comp","cached","unsafe","prev","createCache","delete","hasCache","pippenger","fieldN","scalars","validateMSMPoints","field","s","validateMSMScalars","plength","slength","buckets","resI","sumI","createField","order","validateField","divNearest","den","validateSigFormat","format","validateSigOpts","def","optsn","optName","abool","lowS","prehash","DERErr","DER","Err","_tlv","tag","dataLen","lenLen","first","lengthBytes","_int","toSig","int","tlv","seqBytes","seqLeftBytes","rBytes","rLeftBytes","sBytes","sLeftBytes","hexFromSig","sig","seq","_normFnElement","expected","error","weierstrassN","params","extraOpts","validated","CURVE","curveOpts","FpFnLE","assign","_createCurveFields","cofactor","CURVE_ORDER","allowInfinityPoint","clearCofactor","isTorsionFree","endo","wrapPrivateKey","beta","basises","getWLengths","assertCompressionIsSupported","encodePoint","_c","isCompressed","y","bx","pprefix","decodePoint","publicKey","publicKeyUncompressed","uncomp","head","tail","L","isValidXY","y2","weierstrassEquation","sqrtError","err","x2","x3","left","right","Gx","Gy","_4a3","_27b2","acoord","banZero","aprjpoint","other","splitEndoScalarN","basis","a1","b1","a2","b2","k1","k2","k1neg","k2neg","MAX_NUM","_splitEndoScalar","toAffineMemo","iz","X","Y","zz","assertValidMemo","finishEndo","endoBeta","k1p","k2p","assertValidity","precompute","isLazy","wnaf","multiply","hasEvenY","X1","Y1","Z1","X2","Y2","Z2","U1","U2","b3","X3","Y3","Z3","t0","t1","t2","t3","t4","t5","subtract","fake","k1f","k2f","multiplyUnsafe","sc","p1","p2","mulEndoUnsafe","multiplyAndAddUnsafe","invertedZ","isSmallOrder","px","py","pz","toRawBytes","_setWindowSize","msm","fromPrivateKey","privateKey","secretKey","publicKeyHasPrefix","signature","ecdsa","ecdsaOpts","bits2int","bits2int_modN","randomBytesWeb","msgs","nobleHmac","fnBits","keygen","getPublicKey","getSharedSecret","utils","ecdhOpts","randomBytes_","seed","isValidSecretKey","randomSecretKey","isProbPub","isValidPublicKey","isValidPrivateKey","randomPrivateKey","normPrivateKeyToScalar","secretKeyA","publicKeyB","ecdh","defaultSigOpts","extraEntropy","defaultSigOpts_format","isBiggerThanHalfOrder","validateRS","Signature","recovery","recid","validateSigLength","addRecoveryBit","recoverPublicKey","messageHash","FIELD_ORDER","rec","radj","ir","u1","u2","hasHighS","fromCompact","fromDER","normalizeS","toDERRawBytes","toDERHex","toCompactRawBytes","toCompactHex","delta","ORDER_MASK","int2octets","aInRange","validateMsgAndHash","sign","k2sig","some","h1int","seedArgs","kBytes","ik","q","normS","prepSig","hashLen","qByteLen","hmacFn","u8n","u8of","reset","reseed","gen","sl","concatBytes_","pred","createHmacDrbg","drbg","verify","sg","isHex","isObj","derError","tryParsingSig","is","_ecdsa_legacy_opts_to_new","allowedPrivateKeyLengths","Set","_weierstrass_legacy_opts_to_new","weierstrass","_ecdsa","ProjectivePoint","_ecdsa_new_output_to_legacy","secp256k1_CURVE","secp256k1_ENDO","Fpk1","_6n","_11n","_22n","_23n","_44n","_88n","b6","b9","b11","b22","b44","b88","b176","b220","b223","secp256k1","curveDef","defHash","createCurve","TAGGED_HASH_PREFIXES","taggedHash","messages","tagP","tagH","pointToBytes","Pointk1","hasEven","schnorrGetExtPubKey","priv","d_","lift_x","xx","challenge","schnorrGetPublicKey","schnorrSign","auxRand","rand","rx","schnorrVerify","pub","schnorr","GP","tweak_pubkey","pubkey","tweak","even_y","twk_big","serialize_bytes","pub_pt","pk","serialize_pubkey","lift_point","tweak_pt","tweaked_pt","prefix","Rho160","Id160","Pi160","idxLR","idxL","idxR","shifts160","shiftsL160","shiftsR160","Kl160","Kr160","ripemd_f","group","z","BUF_160","RIPEMD160","h0","h1","h2","h3","h4","ar","bl","br","cl","cr","dl","dr","el","er","rGroup","hbl","hbr","rl","rr","sr","tl","tr","ripemd160","hash160","noble_r160","noble_s256","hash256","hash340","htag","hashtag","isArrayOf","isString","afn","astr","label","aArr","astrArr","anumArr","chain","id","wrap","alphabet","letters","lettersA","indexes","digits","letter","separator","convertRadix","dlen","carry","done","digit","fromCarry","digitBase","rounded","gcd","radix2carry","powers","convertRadix2","padding","radix2","revPadding","unsafeWrapper","apply","base64","toBase64","fromBase64","lastChunkHandling","decodeBase64Builtin","chr","base64urlnopad","base58","abc","radix","createBase58check","oldChecksum","newChecksum","BECH_ALPHABET","POLYMOD_GENERATORS","bech32Polymod","pre","chk","bechChecksum","words","encodingConst","genBech32","encoding","ENCODING_CONST","_words","fromWords","toWords","fromWordsUnsafe","limit","plen","actualLength","lowered","toLowerCase","slen","toUpperCase","sepIndex","lastIndexOf","endsWith","encodeFromBytes","decodeToBytes","decodeUnsafe","bech32","bech32m","B58chk","Base64","B64url","Bech32","Bech32m","assert_prefix","assert_words","to_words","to_bytes","ENCODING_REGEX","decode_address","address","get_address_format","encoded","version","base58_decode","rest","bech32_decode","bech32m_decode","encode_address","config","base58_encode","bech32_encode","bech32m_encode","get_address_script","script_key","script_type","asm","get_p2pkh_script","get_p2sh_script","get_p2w_pkh_script","get_p2w_sh_script","get_p2tr_script","CONFIG_TABLE","get_address_config","address_network","address_type","network","get_address_info","dec","startsWith","ADDRESS_TYPE","create_p2pkh_address","encode_p2pkh_address","create_p2pkh_script","encode_p2pkh_script","pk_hash","decode_p2pkh_script","decode_p2pkh_address","parsed","create_address","create_script","encode_script","decode_script","create_p2sh_address","encode_p2sh_address","encode_p2sh_script","create_p2sh_script","script_hash","script_pk","decode_p2sh_script","decode_p2sh_address","create_p2tr_address","encode_p2tr_address","create_p2tr_script","encode_p2tr_script","decode_p2tr_script","decode_p2tr_address","create_p2wpkh_address","encode_p2wpkh_address","create_p2wpkh_script","encode_p2wpkh_script","decode_p2wpkh_script","decode_p2wpkh_address","create_p2wsh_address","encode_p2wsh_address","create_p2wsh_script","encode_p2wsh_script","decode_p2wsh_script","decode_p2wsh_address","LOCKTIME_THRESHOLD","LocktimeField","RefPointer","encode_locktime","locktime","height","decode_locktime","encode_inscription_id","txid","decode_inscription_id","inscription_id","assert_inscription_id","verify_inscription_id","encode_rune_id","block_height","block_index","decode_rune_id","rune_id","assert_rune_id","verify_rune_id","encode_outpoint","vout","decode_outpoint","outpoint","assert_outpoint","verify_outpoint","assert","record_id","OPCODE_MAP","OP_0","OP_PUSHDATA1","OP_PUSHDATA2","OP_PUSHDATA4","OP_1NEGATE","OP_SUCCESS80","OP_1","OP_2","OP_3","OP_4","OP_5","OP_6","OP_7","OP_8","OP_9","OP_10","OP_11","OP_12","OP_13","OP_14","OP_15","OP_16","OP_NOP","OP_SUCCESS98","OP_IF","OP_NOTIF","OP_ELSE","OP_ENDIF","OP_VERIFY","OP_RETURN","OP_TOALTSTACK","OP_FROMALTSTACK","OP_2DROP","OP_2DUP","OP_3DUP","OP_2OVER","OP_2ROT","OP_2SWAP","OP_IFDUP","OP_DEPTH","OP_DROP","OP_DUP","OP_NIP","OP_OVER","OP_PICK","OP_ROLL","OP_ROT","OP_SWAP","OP_TUCK","OP_SUCCESS126","OP_SUCCESS127","OP_SUCCESS128","OP_SUCCESS129","OP_SIZE","OP_SUCCESS131","OP_SUCCESS132","OP_SUCCESS133","OP_SUCCESS134","OP_EQUAL","OP_EQUALVERIFY","OP_SUCCESS137","OP_SUCCESS138","OP_1ADD","OP_1SUB","OP_SUCCESS141","OP_SUCCESS142","OP_NEGATE","OP_ABS","OP_NOT","OP_0NOTEQUAL","OP_ADD","OP_SUB","OP_SUCCESS149","OP_SUCCESS150","OP_SUCCESS151","OP_SUCCESS152","OP_SUCCESS153","OP_BOOLAND","OP_BOOLOR","OP_NUMEQUAL","OP_NUMEQUALVERIFY","OP_NUMNOTEQUAL","OP_LESSTHAN","OP_GREATERTHAN","OP_LESSTHANOREQUAL","OP_GREATERTHANOREQUAL","OP_MIN","OP_MAX","OP_WITHIN","OP_RIPEMD160","OP_SHA1","OP_SHA256","OP_HASH160","OP_HASH256","OP_CODESEPARATOR","OP_CHECKSIG","OP_CHECKSIGVERIFY","OP_CHECKMULTISIG","OP_CHECKMULTISIGVERIFY","OP_NOP1","OP_CHECKLOCKTIMEVERIFY","OP_CHECKSEQUENCEVERIFY","OP_NOP4","OP_NOP5","OP_NOP6","OP_NOP7","OP_NOP8","OP_NOP9","OP_NOP10","OP_CHECKSIGADD","get_op_code","get_asm_code","string","get_op_type","is_valid_op","stream","stack","stack_size","word_type","word_size","is_valid_script","MAX_WORD_SIZE","encode_script_word","asm_code","split_script_word","prefix_word_size","get_size_varint","_26n","InscriptionUtil","decode_inscription","envelopes","start_idx","indexOf","stop_idx","env","parse_envelopes","parse_record","encode_inscription","create_envelope","delegate","encode_id","ref","parent","opcode","code","encode_pointer","pointer","ptr","rune","encode_rune_label","mimetype","encode_label","content","encode_content","envelope","record","decode_label","decode_pointer","decode_id","decode_rune_label","decode_bytes","decode_content","identifier","parts","charCode","fromCharCode","TIMELOCK_TYPE","TIMELOCK_VALUE_MASK","TIMELOCK_VALUE_MAX","SequenceField","encode_sequence","mode","parse_height","ts","parse_stamp","decode_sequence","sequence","parse_sequence","prefix_script_size","opreturn","matchAll","MAX_TX_SIZE","MAX_TX_ELEMENTS","decode_tx","txdata","use_segwit","txSize","read_version","has_witness","marker","flag","check_witness_flag","vin","inputs","vinCount","txinput","read_vin","read_inputs","outputs","vcount","read_vout","_error","read_outputs","txin","witness","read_witness","read_locktime","script_sig","read_payload","coinbase","prevout","element","$constructor","initializer","init","inst","_zod","defineProperty","constr","traits","enumerable","has","proto","prototype","bind","Parent","Definition","_a","deferred","Symbol","hasInstance","$ZodAsyncError","$ZodEncodeError","globalConfig","newConfig","getEnumValues","numericValues","values","jsonStringifyReplacer","getter","nullish","cleanRegex","source","EVALUATING","defineLazy","configurable","assignProp","target","prop","writable","mergeDefs","defs","mergedDescriptors","descriptors","getOwnPropertyDescriptors","defineProperties","esc","captureStackTrace","_args","isObject","allowsEval","navigator","userAgent","Function","isPlainObject","o","ctor","prot","hasOwnProperty","call","shallowClone","propertyKeyTypes","escapeRegex","replace","normalizeParams","_params","NUMBER_FORMAT_RANGES","safeint","MIN_SAFE_INTEGER","int32","uint32","float32","float64","MAX_VALUE","aborted","startIndex","issues","continue","prefixIssues","path","iss","unshift","unwrapMessage","finalizeIssue","ctx","full","customError","localeError","reportInput","getLengthableOrigin","issue","util.jsonStringifyReplacer","$ZodError","$ZodRealError","_parse","_Err","schema","_ctx","async","run","Promise","core.$ZodAsyncError","util.finalizeIssue","core.config","util.captureStackTrace","callee","_parseAsync","_safeParse","success","errors.$ZodError","safeParse","errors.$ZodRealError","_safeParseAsync","safeParseAsync","_encode","direction","_decode","_encodeAsync","_decodeAsync","_safeEncode","_safeDecode","_safeEncodeAsync","_safeDecodeAsync","cuid","cuid2","ulid","xid","ksuid","nanoid","duration","guid","uuid","RegExp","email","ipv4","ipv6","cidrv4","cidrv6","base64url","e164","dateSource","date","timeSource","hhmm","precision","integer","boolean","_null","lowercase","uppercase","$ZodCheck","core.$constructor","onattach","numericOriginMap","$ZodCheckLessThan","origin","bag","curr","inclusive","maximum","exclusiveMaximum","POSITIVE_INFINITY","check","getTime","abort","$ZodCheckGreaterThan","minimum","exclusiveMinimum","NEGATIVE_INFINITY","$ZodCheckMultipleOf","multipleOf","step","valDecCount","stepString","stepDecCount","decCount","toFixed","util.floatSafeRemainder","divisor","$ZodCheckNumberFormat","isInt","util.NUMBER_FORMAT_RANGES","pattern","regexes.integer","note","$ZodCheckMaxLength","when","util.nullish","util.getLengthableOrigin","$ZodCheckMinLength","$ZodCheckLengthEquals","tooBig","exact","$ZodCheckStringFormat","_b","patterns","lastIndex","$ZodCheckRegex","$ZodCheckLowerCase","regexes.lowercase","$ZodCheckUpperCase","regexes.uppercase","$ZodCheckIncludes","escapedRegex","util.escapeRegex","position","$ZodCheckStartsWith","$ZodCheckEndsWith","suffix","$ZodCheckOverwrite","tx","Doc","indent","indented","write","execution","lines","minIndent","trimStart","dedented","line","compile","major","minor","patch","$ZodType","checks","runChecks","asyncResult","isAborted","util.aborted","currLen","resolve","then","handleCanaryResult","canary","checkResult","skipChecks","util.defineLazy","validate","vendor","$ZodString","pop","coerce","$ZodStringFormat","checks.$ZodCheckStringFormat","$ZodGUID","regexes.guid","$ZodUUID","v1","v2","v3","v4","v5","v6","v7","v8","regexes.uuid","$ZodEmail","regexes.email","$ZodURL","trimmed","trim","url","URL","hostname","protocol","normalize","href","$ZodEmoji","$ZodNanoID","regexes.nanoid","$ZodCUID","regexes.cuid","$ZodCUID2","regexes.cuid2","$ZodULID","regexes.ulid","$ZodXID","regexes.xid","$ZodKSUID","regexes.ksuid","$ZodISODateTime","time","local","timeRegex","regexes.datetime","$ZodISODate","regexes.date","$ZodISOTime","$ZodISODuration","regexes.duration","$ZodIPv4","regexes.ipv4","$ZodIPv6","regexes.ipv6","$ZodCIDRv4","regexes.cidrv4","$ZodCIDRv6","regexes.cidrv6","prefixNum","isValidBase64","atob","$ZodBase64","regexes.base64","contentEncoding","$ZodBase64URL","regexes.base64url","padEnd","isValidBase64URL","$ZodE164","regexes.e164","$ZodJWT","token","algorithm","tokensParts","header","parsedHeader","typ","alg","isValidJWT","$ZodNumber","regexes.number","isFinite","received","$ZodNumberFormat","checks.$ZodCheckNumberFormat","$ZodBoolean","regexes.boolean","Boolean","$ZodBigInt","regexes.bigint","$ZodNull","regexes.null","$ZodUnknown","$ZodNever","handleArrayResult","final","index","util.prefixIssues","$ZodArray","proms","all","handlePropertyResult","isOptionalOut","normalizeDef","shape","okeys","optin","optout","keySet","numKeys","optionalKeys","handleCatchall","unrecognized","_catchall","catchall","$ZodObject","desc","getOwnPropertyDescriptor","sh","newSh","_normalized","util.cached","propValues","util.isObject","$ZodObjectJIT","superParse","fastpass","jit","core.globalConfig","jitless","fastEnabled","util.allowsEval","doc","normalized","parseStr","util.esc","ids","counter","generateFastpass","handleUnionResults","results","nonaborted","errors","$ZodUnion","options","flatMap","option","util.cleanRegex","single","$ZodIntersection","handleIntersectionResults","mergeValues","valid","util.isPlainObject","bKeys","sharedKeys","newObj","sharedValue","mergeErrorPath","newArray","unrecKeys","unrecIssue","bothKeys","merged","$ZodRecord","keyType","recordKeys","valueType","Reflect","ownKeys","keyResult","retryResult","$ZodEnum","util.getEnumValues","valuesSet","util.propertyKeyTypes","$ZodTransform","core.$ZodEncodeError","_out","output","handleOptionalResult","$ZodOptional","innerType","$ZodExactOptional","$ZodNullable","$ZodDefault","defaultValue","handleDefaultResult","$ZodPrefault","$ZodNonOptional","handleNonOptionalResult","$ZodCatch","catchValue","$ZodPipe","in","handlePipeResult","next","$ZodReadonly","handleReadonlyResult","$ZodLazy","$ZodCustom","checks.$ZodCheck","handleRefineResult","_iss","util.issue","$ZodRegistry","_map","_idmap","_meta","meta","clear","remove","pm","__zod_globalRegistry","globalRegistry","_guid","Class","util.normalizeParams","_lt","checks.$ZodCheckLessThan","_lte","_gt","checks.$ZodCheckGreaterThan","_gte","_multipleOf","checks.$ZodCheckMultipleOf","_maxLength","checks.$ZodCheckMaxLength","_minLength","checks.$ZodCheckMinLength","_length","checks.$ZodCheckLengthEquals","_overwrite","checks.$ZodCheckOverwrite","_superRefine","_check","addIssue","_issue","fatal","initializeContext","processors","metadataRegistry","metadata","unrepresentable","override","io","seen","cycles","reused","external","schemaPath","cycle","overrideSchema","toJSONSchema","processJSONSchema","_json","processor","isParent","isTransforming","examples","default","_prefault","extractDefs","idToSchema","entry","existing","extractToDef","$ref","defId","defsSegment","externalId","registry","uriGenerator","uri","defUriPrefix","makeURI","ext","finalize","flattenRef","zodSchema","_cached","refSeen","refSchema","allOf","parentSeen","jsonSchema","$schema","$id","$defs","definitions","finalized","createStandardJSONSchemaMethod","_err","_schema","items","libraryOptions","formatMap","datetime","json_string","optionalProcessor","ZodISODateTime","core.$ZodISODateTime","schemas.ZodStringFormat","core._isoDateTime","ZodISODate","core.$ZodISODate","core._isoDate","ZodISOTime","core.$ZodISOTime","core._isoTime","ZodISODuration","core.$ZodISODuration","core._isoDuration","ZodRealError","mapper","fieldErrors","_errors","processError","core.formatError","flatten","formErrors","core.flattenError","addIssues","isEmpty","core._parse","parseAsync","core._parseAsync","core._safeParse","core._safeParseAsync","core._encode","core._decode","encodeAsync","core._encodeAsync","decodeAsync","core._decodeAsync","safeEncode","core._safeEncode","safeDecode","core._safeDecode","safeEncodeAsync","core._safeEncodeAsync","safeDecodeAsync","core._safeDecodeAsync","ZodType","core.$ZodType","createToJSONSchemaMethod","util.mergeDefs","with","core.clone","brand","register","reg","parse.parse","parse.safeParse","parse.parseAsync","parse.safeParseAsync","spa","parse.encode","parse.decode","parse.encodeAsync","parse.decodeAsync","parse.safeEncode","parse.safeDecode","parse.safeEncodeAsync","parse.safeDecodeAsync","refine","core._refine","ZodCustom","superRefine","refinement","core._superRefine","overwrite","checks.overwrite","optional","exactOptional","ZodExactOptional","nullable","nonoptional","ZodNonOptional","or","union","and","ZodIntersection","pipe","ZodTransform","_default","ZodDefault","util.shallowClone","prefault","ZodPrefault","catch","_catch","ZodCatch","readonly","ZodReadonly","describe","description","core.globalRegistry","isOptional","isNullable","_ZodString","core.$ZodString","minLength","maxLength","regexes","processors.stringProcessor","checks.$ZodCheckRegex","checks.regex","checks.$ZodCheckIncludes","checks.includes","checks.$ZodCheckStartsWith","checks.startsWith","checks.$ZodCheckEndsWith","checks.endsWith","checks.minLength","checks.maxLength","checks.length","nonempty","checks.$ZodCheckLowerCase","checks.lowercase","checks.$ZodCheckUpperCase","checks.uppercase","form","checks.normalize","slugify","util.slugify","ZodString","core._email","ZodEmail","core._url","ZodURL","jwt","core._jwt","ZodJWT","emoji","core._emoji","ZodEmoji","core._guid","ZodGUID","core._uuid","ZodUUID","uuidv4","core._uuidv4","uuidv6","core._uuidv6","uuidv7","core._uuidv7","core._nanoid","ZodNanoID","core._cuid","ZodCUID","core._cuid2","ZodCUID2","core._ulid","ZodULID","core._base64","ZodBase64","core._base64url","ZodBase64URL","core._xid","ZodXID","core._ksuid","ZodKSUID","core._ipv4","ZodIPv4","core._ipv6","ZodIPv6","core._cidrv4","ZodCIDRv4","core._cidrv6","ZodCIDRv6","core._e164","ZodE164","iso.datetime","iso.date","iso.time","iso.duration","core._string","ZodStringFormat","core.$ZodStringFormat","core.$ZodEmail","core.$ZodGUID","core.$ZodUUID","core.$ZodURL","core.$ZodEmoji","core.$ZodNanoID","core.$ZodCUID","core.$ZodCUID2","core.$ZodULID","core.$ZodXID","core.$ZodKSUID","core.$ZodIPv4","core.$ZodIPv6","core.$ZodCIDRv4","core.$ZodCIDRv6","core.$ZodBase64","core.$ZodBase64URL","core.$ZodE164","core.$ZodJWT","ZodNumber","core.$ZodNumber","processors.numberProcessor","gt","checks.gt","gte","checks.gte","lt","checks.lt","lte","checks.lte","safe","positive","nonnegative","negative","nonpositive","checks.multipleOf","finite","minValue","maxValue","core._number","ZodNumberFormat","core.$ZodNumberFormat","core._int","ZodBoolean","core.$ZodBoolean","processors.booleanProcessor","ZodBigInt","core.$ZodBigInt","processors.bigintProcessor","ZodNull","core.$ZodNull","enum","processors.nullProcessor","ZodUnknown","core.$ZodUnknown","unknown","ZodNever","core.$ZodNever","not","processors.neverProcessor","never","core._never","ZodArray","core.$ZodArray","minItems","maxItems","processors.arrayProcessor","unwrap","core._array","ZodObject","core.$ZodObjectJIT","properties","allKeys","requiredKeys","required","additionalProperties","processors.objectProcessor","keyof","fromEntries","ZodEnum","_enum","passthrough","loose","strict","strip","extend","incoming","existingShape","_shape","util.extend","safeExtend","util.safeExtend","merge","util.merge","pick","currDef","newShape","util.pick","omit","util.omit","partial","oldShape","util.partial","ZodOptional","util.required","ZodUnion","core.$ZodUnion","isExclusive","oneOf","anyOf","processors.unionProcessor","core.$ZodIntersection","isSimpleIntersection","processors.intersectionProcessor","ZodRecord","core.$ZodRecord","keyBag","valueSchema","patternProperties","propertyNames","keyValues","validKeyValues","processors.recordProcessor","core.$ZodEnum","processors.enumProcessor","extract","newEntries","exclude","core.$ZodTransform","processors.transformProcessor","core.$ZodOptional","processors.optionalProcessor","core.$ZodExactOptional","ZodNullable","core.$ZodNullable","inner","processors.nullableProcessor","core.$ZodDefault","processors.defaultProcessor","removeDefault","core.$ZodPrefault","processors.prefaultProcessor","core.$ZodNonOptional","processors.nonoptionalProcessor","core.$ZodCatch","processors.catchProcessor","removeCatch","ZodPipe","core.$ZodPipe","processors.pipeProcessor","in_","core.$ZodReadonly","readOnly","processors.readonlyProcessor","ZodLazy","core.$ZodLazy","processors.lazyProcessor","core.$ZodCustom","processors.customProcessor","z\n .number","cls","z.instanceof","z.string","z.number","z\n .string","literal","z.union","core._boolean","core._null","z.null","z.array","z.record","u8a32","u8a33","u8a64","hex32","hex33","hex64","byte32","taptree","z.object","leaves","sats","core._bigint","z.bigint","tx_output","tx_input","tx_data","vout_template","vin_template","tx_template","assert_tx_template","Schema.tx.tx_template","assert_has_prevouts","assert_tx_data","Schema.tx.tx_data","assert_vin_template","Schema.tx.vin_template","assert_vout_template","Schema.tx.vout_template","encode_tx","encode_tx_version","encode_tx_inputs","encode_tx_outputs","encode_vin_witness","encode_tx_locktime","encode_txin_txid","encode_txin_vout","encode_txin_sequence","raw","encode_vin","encode_script_data","encode_vout_value","encode_tx_vout","txout","param","parse_tx","prevouts","create_tx","create_tx_output","transcode_tx","normalize_sequence","normalize_value","normalize_prevout","create_coinbase_input","create_virtual_input","create_spend_input","create_tx_input","Schema.tx.tx_input","Schema.tx.tx_output","txinputs","fees","txoutput","total","weight","remain","vsize","get_prevout","parse_txinput","txindex","get_annex_data","annex","hash_segwit_tx","sigflag","is_anypay","CONST.SIGHASH_SEGWIT","prevIdx","pkhash","sighash","bip143_hash_prevouts","bip143_hash_sequence","bip143_hash_outputs","isAnypay","isAnyPay","encode_tapscript","encode_tapleaf","encode_leaf_version","encode_tapbranch","leaf_a","leaf_b","encode_taptweak","hash_taproot_tx","template","get_taproot_tx_preimage","extflag","key_version","separator_pos","CONST.SIGHASH_TAPROOT","extension","spendType","preimage","bip341_hash_outpoints","bip341_hash_amounts","bip341_hash_scripts","bip341_hash_sequence","bip341_hash_outputs","bip341_hash_output","SECKEY_REGEX","validate_seckey","seckey","validate_sighash_options","validFlags","normalizedFlag","baseFlag","format_sigflag","parse_witness","elems","elem","parse_annex_data","cblock","parse_cblock_data","param_0","param_1","param_x","parse_witness_type","parse_witness_version","parse_witness_script","parse_cblock","cbyte","int_key","parity","parse_cblock_parity","cbits","parse_pubkey_parity","merkleize","depth","tree","tapleaf","new_target","branches","branch","leaf","DEFAULT_VERSION","verify_taproot","tapkey","ext_key","tweaked_key","ECC.tweak_pubkey","verify_input","witnessData","sigHex","sigBytes","parse_ecdsa_signature","hashScript","sighashOptions","ECC.verify_ecdsa","verify_segwit_input","_scriptType","parse_schnorr_signature","ECC.verify_bip340","verify_taproot_input","scriptType","ECC.sign_ecdsa","ECC.sign_bip340","throws","allValid","Schema.taproot.config","taproot","proofs","taptweak","twk_key","ECC.serialize_pubkey","block","cblk"],"mappings":"qCAAO,MAAMA,EAAW,CACvBC,KAAM,KAAKC,OAAO,IAClBC,KAAM,YAGMC,EAAU,CACtBC,SAAU,EACVC,SAAU,WACVC,QAAS,GAGGC,EAAmB,CAC/B,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IACxE,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IACxE,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IACxE,IAAM,KAKMC,EAAmB,CAC/BC,MAAO,QACPC,KAAM,OACNC,OAAQ,SACRC,MAAO,QACPC,KAAM,OACNC,SAAU,YAYEC,EAA4C,CACxD,CAACP,EAAiBC,OAAQ,4BAC1B,CAACD,EAAiBE,MAAO,wBACzB,CAACF,EAAiBG,QAAS,sBAC3B,CAACH,EAAiBI,OAAQ,sBAC1B,CAACJ,EAAiBK,MAAO,sBACzB,CAACL,EAAiBM,UAAW,qBAajBE,EAAiB,CAAC,EAAM,EAAM,EAAM,IAAM,IAAM,KAChDC,EAAkB,CAAC,KAASD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B,MAAM8qE,EAAO9C,GAAaR,GAG1B,IAAIqB,EAFWxD,GAAiBrlE,EAAQ8qE,EAAK11C,SAEzBz+B,IAEpB,IAAK,MAAMmyE,KAAQgC,EAAK19B,KACvBy7B,EAASrD,GAAiBqD,EAAQC,GAAMnyE,IAGzC,MAAMo1B,EAAQ45C,GAAgBmF,EAAK5C,QAASW,GACtCI,EAASG,GAAiB0B,EAAK5C,QAASn8C,EAAO,UAIrD,OAFAnQ,EAAO/gB,IAAKvE,GAAM8D,EAAKvD,MAAMP,GAAGK,KAEzB,CAAE6wE,OAAQsD,EAAMlvD,SAAQ5b,SAAQipE,OAAQA,EAAOtyE,IAAKo1B,MAAOA,EAAMp1B,IACzE,0EI/BM,SAAyBoxC,GAC9BxyC,EAAOoN,GAAGxM,MAAMC,QAAQ2xC,GAAU,4BAClCxyC,EAAOoN,GACNolC,EAAQ1xC,MAAOC,GAAM8D,EAAKnE,SAASK,IACnC,+CAEF,mBAbM,SAA2ByxC,GAChC,MACMtxC,EADQsxC,EAAQltC,IAAKvE,GAAM8D,EAAKvD,MAAMP,IACzBiJ,OAAO,CAAC6Y,EAAMurC,IAASvrC,EAAOurC,EAAK3tD,OAAQ,GAE9D,MAAO,CAAEguE,MAAOvtE,EAAM0tE,MADRrnE,KAAKsV,KALI,EAKmB3b,EAAO,GAElD","x_google_ignoreList":[1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66]}
1
+ {"version":3,"file":"script.js","sources":["../src/const.ts","../node_modules/@vbyte/buff/dist/util/validate.js","../node_modules/@vbyte/buff/dist/util/error.js","../node_modules/@vbyte/buff/dist/util/assert.js","../node_modules/@vbyte/buff/dist/lib/big.js","../node_modules/@vbyte/buff/dist/lib/num.js","../node_modules/@vbyte/buff/dist/lib/hex.js","../node_modules/@vbyte/buff/dist/lib/bytes.js","../node_modules/@vbyte/buff/dist/lib/str.js","../node_modules/@vbyte/buff/dist/lib/rand.js","../node_modules/@vbyte/buff/dist/class/buff.js","../node_modules/@vbyte/buff/dist/lib/bin.js","../node_modules/@vbyte/buff/dist/class/stream.js","../src/error.ts","../src/lib/script/lock.ts","../node_modules/@vbyte/util/dist/lib/obj.js","../node_modules/@vbyte/util/dist/lib/test.js","../node_modules/@vbyte/util/dist/lib/assert.js","../node_modules/@noble/hashes/utils.js","../node_modules/@noble/hashes/hmac.js","../node_modules/@noble/hashes/_md.js","../node_modules/@noble/hashes/legacy.js","../node_modules/@noble/hashes/sha2.js","../node_modules/@vbyte/crypto/dist/lib/hash.js","../node_modules/@vbyte/crypto/dist/lib/assert.js","../node_modules/@noble/curves/utils.js","../node_modules/@noble/curves/abstract/modular.js","../node_modules/@noble/curves/abstract/curve.js","../node_modules/@noble/curves/abstract/weierstrass.js","../node_modules/@noble/curves/secp256k1.js","../node_modules/@vbyte/crypto/dist/lib/ecc.js","../node_modules/@vbyte/crypto/node_modules/@scure/base/index.js","../node_modules/@vbyte/crypto/dist/lib/encode.js","../src/lib/address/encode.ts","../src/lib/address/script.ts","../src/lib/address/util.ts","../src/lib/address/p2pkh.ts","../src/lib/address/p2sh.ts","../src/lib/address/p2tr.ts","../src/lib/address/p2wpkh.ts","../src/lib/address/p2wsh.ts","../src/lib/address/api.ts","../src/lib/meta/locktime.ts","../src/lib/meta/ref.ts","../src/lib/script/words.ts","../src/lib/script/decode.ts","../src/lib/script/encode.ts","../src/lib/meta/scribe.ts","../src/lib/meta/sequence.ts","../src/lib/script/util.ts","../src/lib/tx/decode.ts","../node_modules/zod/v4/core/core.js","../node_modules/zod/v4/core/util.js","../node_modules/zod/v4/core/errors.js","../node_modules/zod/v4/core/parse.js","../node_modules/zod/v4/core/regexes.js","../node_modules/zod/v4/core/checks.js","../node_modules/zod/v4/core/doc.js","../node_modules/zod/v4/core/versions.js","../node_modules/zod/v4/core/schemas.js","../node_modules/zod/v4/core/registries.js","../node_modules/zod/v4/core/api.js","../node_modules/zod/v4/core/to-json-schema.js","../node_modules/zod/v4/core/json-schema-processors.js","../node_modules/zod/v4/classic/iso.js","../node_modules/zod/v4/classic/errors.js","../node_modules/zod/v4/classic/parse.js","../node_modules/zod/v4/classic/schemas.js","../src/schema/base.ts","../src/schema/taproot.ts","../src/schema/tx.ts","../src/lib/tx/validate.ts","../src/lib/tx/encode.ts","../src/lib/tx/parse.ts","../src/lib/tx/util.ts","../src/lib/tx/create.ts","../src/lib/tx/size.ts","../src/lib/sighash/util.ts","../src/lib/sighash/segwit.ts","../src/lib/taproot/encode.ts","../src/lib/sighash/taproot.ts","../src/lib/signer/sign.ts","../src/lib/witness/parse.ts","../src/lib/taproot/parse.ts","../src/lib/taproot/tree.ts","../src/lib/taproot/cblock.ts","../src/lib/signer/verify.ts","../src/lib/witness/util.ts"],"sourcesContent":["export const COINBASE = {\n\tTXID: \"00\".repeat(32),\n\tVOUT: 0xffffffff,\n};\n\nexport const DEFAULT = {\n\tLOCKTIME: 0,\n\tSEQUENCE: 0xffffffff,\n\tVERSION: 2,\n};\n\nexport const TAPLEAF_VERSIONS = [\n\t0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0xcc, 0xce, 0xd0, 0xd2, 0xd4, 0xd6, 0xd8,\n\t0xda, 0xdc, 0xde, 0xe0, 0xe2, 0xe4, 0xe6, 0xe8, 0xea, 0xec, 0xee, 0xf0, 0xf2,\n\t0xf4, 0xf6, 0xf8, 0xfa, 0xfc, 0xfe, 0x66, 0x7e, 0x80, 0x84, 0x96, 0x98, 0xba,\n\t0xbc, 0xbe,\n];\n\nexport const TAPLEAF_DEFAULT_VERSION = 0xc0;\n\nexport const LOCK_SCRIPT_TYPE = {\n\tP2PKH: \"p2pkh\",\n\tP2SH: \"p2sh\",\n\tP2WPKH: \"p2wpkh\",\n\tP2WSH: \"p2wsh\",\n\tP2TR: \"p2tr\",\n\tOPRETURN: \"opreturn\",\n} as const;\n\nexport const SPEND_SCRIPT_TYPE = {\n\tP2PKH: \"p2pkh\",\n\tP2SH: \"p2sh\",\n\tP2WPKH: \"p2wpkh\",\n\tP2WSH: \"p2wsh\",\n\tP2TR: \"p2tr\",\n\tP2TS: \"p2ts\",\n} as const;\n\nexport const LOCK_SCRIPT_REGEX: Record<string, RegExp> = {\n\t[LOCK_SCRIPT_TYPE.P2PKH]: /^76a914[0-9a-f]{40}88ac$/i,\n\t[LOCK_SCRIPT_TYPE.P2SH]: /^a914[0-9a-f]{40}87$/i,\n\t[LOCK_SCRIPT_TYPE.P2WPKH]: /^0014[0-9a-f]{40}$/i,\n\t[LOCK_SCRIPT_TYPE.P2WSH]: /^0020[0-9a-f]{64}$/i,\n\t[LOCK_SCRIPT_TYPE.P2TR]: /^5120[0-9a-f]{64}$/i,\n\t[LOCK_SCRIPT_TYPE.OPRETURN]: /^6a[0-9a-f]{2,}$/i,\n} as const;\n\nexport const SCRIPT_INT_KEY = \"\";\n\nexport const TX_SIZE = {\n\tGLOBAL_BASE: 8,\n\tGLOBAL_WIT: 10,\n\tTXIN_BASE: 32 + 4 + 4,\n\tTXOUT_BASE: 8,\n};\n\nexport const SIGHASH_DEFAULT = 0x01;\nexport const SIGHASH_SEGWIT = [0x01, 0x02, 0x03, 0x81, 0x82, 0x83];\nexport const SIGHASH_TAPROOT = [0x00, ...SIGHASH_SEGWIT];\n\n/** Bitcoin consensus script size limit (10,000 bytes) */\nexport const MAX_SCRIPT_SIZE = 10_000;\n\n/** Maximum varint payload size (~520KB, prevents memory exhaustion attacks) */\nexport const MAX_VARINT_SIZE = 520_000;\n\n/** Offset to convert 1-16 to OP_1 through OP_16 */\nexport const OP_1_OFFSET = 0x50;\n","export var Check;\n(function (Check) {\n function is_hex(input) {\n return (input.match(/[^a-fA-F0-9]/) === null &&\n input.length % 2 === 0);\n }\n Check.is_hex = is_hex;\n function is_bytes(input) {\n if (typeof input === 'string' && is_hex(input)) {\n return true;\n }\n else if (input instanceof Uint8Array) {\n return true;\n }\n else if (Array.isArray(input) &&\n input.every(e => typeof e === 'number' &&\n Number.isInteger(e) &&\n e >= 0 &&\n e <= 255)) {\n return true;\n }\n else {\n return false;\n }\n }\n Check.is_bytes = is_bytes;\n})(Check || (Check = {}));\n","export class ValidationError extends Error {\n constructor(message) {\n super(message);\n this.name = 'ValidationError';\n }\n}\nexport class HexValidationError extends ValidationError {\n constructor(message) {\n super(message);\n this.name = 'HexValidationError';\n }\n}\nexport class ByteRangeError extends ValidationError {\n constructor(message) {\n super(message);\n this.name = 'ByteRangeError';\n }\n}\nexport class IntegerBoundsError extends ValidationError {\n constructor(message) {\n super(message);\n this.name = 'IntegerBoundsError';\n }\n}\nexport class SizeError extends ValidationError {\n constructor(message) {\n super(message);\n this.name = 'SizeError';\n }\n}\n","import { Check } from '../util/validate.js';\nimport { ByteRangeError, HexValidationError, IntegerBoundsError, SizeError, ValidationError } from '../util/error.js';\nexport var Assert;\n(function (Assert) {\n function within_size(data, size) {\n if (data.length > size) {\n throw new SizeError(`Data is larger than array size: ${data.length} > ${size}`);\n }\n }\n Assert.within_size = within_size;\n function is_hex(hex) {\n if (hex.match(/[^a-fA-F0-9]/) !== null) {\n throw new HexValidationError(`Invalid characters in hex string: ${hex}`);\n }\n if (hex.length % 2 !== 0) {\n throw new HexValidationError(`Length of hex string is invalid: ${hex.length}`);\n }\n }\n Assert.is_hex = is_hex;\n function is_bytes(bytes) {\n if (!Check.is_bytes(bytes)) {\n throw new ByteRangeError(`Bytes contains invalid elements: ${String(bytes)}`);\n }\n }\n Assert.is_bytes = is_bytes;\n function is_json(str) {\n try {\n JSON.parse(str);\n }\n catch {\n throw new ValidationError('JSON string is invalid!');\n }\n }\n Assert.is_json = is_json;\n function is_safe_int(num) {\n if (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) {\n throw new IntegerBoundsError('Number exceeds safe bounds!');\n }\n }\n Assert.is_safe_int = is_safe_int;\n})(Assert || (Assert = {}));\n","const _0n = BigInt(0);\nconst _255n = BigInt(255);\nconst _256n = BigInt(256);\nexport function get_big_size(big) {\n if (big <= 0xffn)\n return 1;\n if (big <= 0xffffn)\n return 2;\n if (big <= 0xffffffffn)\n return 4;\n if (big <= 0xffffffffffffffffn)\n return 8;\n if (big <= 0xffffffffffffffffffffffffffffffffn)\n return 16;\n if (big <= 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn) {\n return 32;\n }\n throw new TypeError('Must specify a fixed buffer size for bigints greater than 32 bytes.');\n}\nexport function big_to_bytes(big, size, endian = 'be') {\n if (size === undefined)\n size = get_big_size(big);\n const use_le = (endian === 'le');\n const buffer = new ArrayBuffer(size);\n const dataView = new DataView(buffer);\n let offset = (use_le) ? 0 : size - 1;\n while (big > _0n) {\n const byte = big & _255n;\n const num = Number(byte);\n if (use_le) {\n dataView.setUint8(offset++, num);\n }\n else {\n dataView.setUint8(offset--, num);\n }\n big = (big - byte) / _256n;\n }\n return new Uint8Array(buffer);\n}\nexport function bytes_to_big(bytes) {\n let num = BigInt(0);\n for (let i = bytes.length - 1; i >= 0; i--) {\n num = (num * _256n) + BigInt(bytes[i]);\n }\n return BigInt(num);\n}\nexport function bigint_replacer(_, v) {\n return typeof v === 'bigint'\n ? `${v}n`\n : v;\n}\nexport function bigint_reviver(_, v) {\n return typeof v === 'string' && /^[0-9]+n$/.test(v)\n ? BigInt(v.slice(0, -1))\n : v;\n}\n","import { Assert } from '../util/assert.js';\nexport function get_num_size(num) {\n if (num < 0) {\n throw new TypeError('Number must be non-negative');\n }\n if (num <= 0xFF)\n return 1;\n if (num <= 0xFFFF)\n return 2;\n if (num <= 0xFFFFFFFF)\n return 4;\n throw new TypeError('Numbers larger than 4 bytes must specify a fixed size!');\n}\nexport function num_to_bytes(num, size, endian = 'be') {\n if (size === undefined)\n size = get_num_size(num);\n const use_le = (endian === 'le');\n const buffer = new ArrayBuffer(size);\n const dataView = new DataView(buffer);\n let offset = (use_le) ? 0 : size - 1;\n while (num > 0) {\n const byte = num & 255;\n if (use_le) {\n dataView.setUint8(offset++, byte);\n }\n else {\n dataView.setUint8(offset--, byte);\n }\n num = (num - byte) / 256;\n }\n return new Uint8Array(buffer);\n}\nexport function bytes_to_num(bytes) {\n let num = 0;\n for (let i = bytes.length - 1; i >= 0; i--) {\n num = (num * 256) + bytes[i];\n Assert.is_safe_int(num);\n }\n return num;\n}\n","import { Assert } from '../util/assert.js';\nexport function hex_to_bytes(hexstr, size, endian = 'be') {\n size = get_hex_size(hexstr, size);\n const use_be = (endian === 'be');\n const buffer = new ArrayBuffer(size);\n const dataView = new DataView(buffer);\n let offset = (use_be) ? 0 : size - 1;\n for (let i = 0; i < hexstr.length; i += 2) {\n const char = hexstr.substring(i, i + 2);\n const num = parseInt(char, 16);\n if (use_be) {\n dataView.setUint8(offset++, num);\n }\n else {\n dataView.setUint8(offset--, num);\n }\n }\n return new Uint8Array(buffer);\n}\nexport function bytes_to_hex(bytes) {\n let chars = '';\n for (let i = 0; i < bytes.length; i++) {\n chars += bytes[i].toString(16).padStart(2, '0');\n }\n return chars;\n}\nfunction get_hex_size(hexstr, size) {\n Assert.is_hex(hexstr);\n const len = hexstr.length / 2;\n if (size === undefined)\n size = len;\n if (len > size) {\n throw new TypeError(`Hex string is larger than array size: ${len} > ${size}`);\n }\n return size;\n}\n","import { Assert } from '../util/assert.js';\nimport { big_to_bytes } from './big.js';\nimport { num_to_bytes } from './num.js';\nimport { hex_to_bytes } from './hex.js';\nexport function buffer(bytes, size, endian) {\n if (bytes instanceof ArrayBuffer) {\n return new Uint8Array(bytes);\n }\n else if (bytes instanceof Uint8Array) {\n return create_bytes(bytes, size, endian);\n }\n else if (typeof bytes === 'string') {\n Assert.is_hex(bytes);\n return hex_to_bytes(bytes, size, endian);\n }\n else if (typeof bytes === 'bigint') {\n return big_to_bytes(bytes, size, endian);\n }\n else if (typeof bytes === 'number') {\n return num_to_bytes(bytes, size, endian);\n }\n throw new TypeError(`Input type not supported: ${typeof bytes}`);\n}\nexport function create_bytes(data, size, endian = 'le') {\n if (size === undefined)\n size = data.length;\n Assert.within_size(data, size);\n const buffer = new Uint8Array(size).fill(0);\n const offset = (endian === 'be') ? 0 : size - data.length;\n buffer.set(data, offset);\n return buffer;\n}\nexport function join_bytes(arr) {\n let i, offset = 0;\n const size = arr.reduce((len, arr) => len + arr.length, 0);\n const buff = new Uint8Array(size);\n for (i = 0; i < arr.length; i++) {\n const a = arr[i];\n buff.set(a, offset);\n offset += a.length;\n }\n return buff;\n}\nexport function split_bytes(data_blob, chunk_size, total_size) {\n const len = data_blob.length, count = total_size / chunk_size;\n if (total_size % chunk_size !== 0) {\n throw new TypeError(`Invalid parameters: ${total_size} % ${chunk_size} !== 0`);\n }\n if (len !== total_size) {\n throw new TypeError(`Invalid data stream: ${len} !== ${total_size}`);\n }\n if (len % chunk_size !== 0) {\n throw new TypeError(`Invalid data stream: ${len} % ${chunk_size} !== 0`);\n }\n const chunks = new Array(count);\n for (let i = 0; i < count; i++) {\n const idx = i * chunk_size;\n chunks[i] = data_blob.subarray(idx, idx + chunk_size);\n }\n return chunks;\n}\n","const ec = new TextEncoder();\nconst dc = new TextDecoder();\nexport function str_to_bytes(str) {\n return ec.encode(str);\n}\nexport function bytes_to_str(bytes) {\n return dc.decode(bytes);\n}\n","const MAX_RANDOM_LENGTH = 1024 * 1024;\nexport function get_random_bytes(length = 32) {\n if (!Number.isInteger(length) || length < 0) {\n throw new TypeError('Length must be a non-negative integer');\n }\n if (length > MAX_RANDOM_LENGTH) {\n throw new RangeError(`Length exceeds maximum allowed: ${length} > ${MAX_RANDOM_LENGTH}`);\n }\n if (crypto &&\n typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(length));\n }\n const pcrypto = crypto;\n if (pcrypto &&\n pcrypto.randomBytes !== undefined &&\n typeof pcrypto.randomBytes === 'function') {\n return pcrypto.randomBytes(length);\n }\n throw new Error('getRandomValues from crypto library is undefined');\n}\n","import * as Lib from '../lib/index.js';\nimport { Assert, Check } from '../util/index.js';\nexport class Buff extends Uint8Array {\n static { this.num = (number, size, endian) => {\n return new Buff(number, size, endian);\n }; }\n static { this.big = (bigint, size, endian) => {\n return new Buff(bigint, size, endian);\n }; }\n static { this.bin = (data, size, endian) => {\n const uint = Lib.bin_to_bytes(data);\n return new Buff(uint, size, endian);\n }; }\n static { this.u8a = (data, size, endian) => {\n return new Buff(data, size, endian);\n }; }\n static { this.str = (data, size, endian) => {\n const uint = Lib.str_to_bytes(data);\n return new Buff(uint, size, endian);\n }; }\n static { this.hex = (data, size, endian) => {\n Assert.is_hex(data);\n return new Buff(data, size, endian);\n }; }\n static { this.bytes = (bytes, size, endian) => {\n Assert.is_bytes(bytes);\n return new Buff(bytes, size, endian);\n }; }\n static { this.json = (data, replacer) => {\n replacer = replacer ?? Lib.bigint_replacer;\n const str = JSON.stringify(data, replacer);\n const uint = Lib.str_to_bytes(str);\n return new Buff(uint);\n }; }\n static { this.chunk = (payload, chunk_size, total_size) => {\n const bytes = Lib.buffer(payload);\n const chunks = Lib.split_bytes(bytes, chunk_size, total_size);\n return chunks.map(e => new Buff(e));\n }; }\n static { this.is_equal = (a, b) => {\n const buf_a = new Buff(a);\n const buf_b = new Buff(b);\n if (buf_a.length !== buf_b.length)\n return false;\n for (let i = 0; i < buf_a.length; i++) {\n if (buf_a[i] !== buf_b[i])\n return false;\n }\n return true;\n }; }\n static { this.is_bytes = Check.is_bytes; }\n static { this.is_hex = Check.is_hex; }\n static random(size = 32) {\n const uint = Lib.get_random_bytes(size);\n return new Buff(uint, size);\n }\n static now() {\n const stamp = Math.floor(Date.now() / 1000);\n return new Buff(stamp, 4);\n }\n constructor(data, size, endian) {\n super(Lib.buffer(data, size, endian));\n }\n get arr() {\n return this.to_arr();\n }\n get big() {\n return this.to_big();\n }\n get bin() {\n return this.to_bin();\n }\n get hex() {\n return this.to_hex();\n }\n get num() {\n return this.to_num();\n }\n get str() {\n return this.to_str();\n }\n get u8a() {\n return this.to_u8a();\n }\n to_big(endian = 'be') {\n const bytes = (endian === 'be')\n ? this.u8a.reverse()\n : this.u8a;\n return Lib.bytes_to_big(bytes);\n }\n to_hex(endian = 'be') {\n const bytes = (endian === 'be')\n ? this.u8a\n : this.u8a.reverse();\n return Lib.bytes_to_hex(bytes);\n }\n to_json(reviver) {\n if (reviver === undefined) {\n reviver = Lib.bigint_reviver;\n }\n const str = Lib.bytes_to_str(this);\n return JSON.parse(str, reviver);\n }\n to_num(endian = 'be') {\n const bytes = (endian === 'be')\n ? this.u8a.reverse()\n : this.u8a;\n return Lib.bytes_to_num(bytes);\n }\n to_arr() { return [...this]; }\n to_bin() { return Lib.bytes_to_bin(this); }\n to_str() { return Lib.bytes_to_str(this); }\n to_u8a() { return new Uint8Array(this); }\n append(data) {\n return Buff.join([this, new Buff(data)]);\n }\n equals(data) {\n const other = new Buff(data);\n if (this.length !== other.length)\n return false;\n for (let i = 0; i < this.length; i++) {\n if (this[i] !== other[i])\n return false;\n }\n return true;\n }\n prepend(data) {\n return Buff.join([new Buff(data), this]);\n }\n prefix_varint(endian) {\n if (this.length === 0)\n throw new Error('buffer is empty');\n const varint = Buff.create_varint(this.length, endian);\n return this.prepend(varint);\n }\n reverse() {\n super.reverse();\n return this;\n }\n set(array, offset) {\n super.set(array, offset);\n }\n slice(start, end) {\n const arr = new Uint8Array(this).slice(start, end);\n return new Buff(arr);\n }\n subarray(begin, end) {\n const arr = new Uint8Array(this).subarray(begin, end);\n return new Buff(arr);\n }\n toJSON() {\n return this.hex;\n }\n toString() {\n return this.hex;\n }\n static from(data) {\n return new Buff(Uint8Array.from(data));\n }\n static of(...args) {\n return new Buff(Uint8Array.of(...args));\n }\n static join(arr) {\n const bytes = arr.map(e => new Buff(e));\n const joined = Lib.join_bytes(bytes);\n return new Buff(joined);\n }\n static sort(arr, size) {\n const hex = arr.map(e => new Buff(e, size).hex);\n hex.sort();\n return hex.map(e => Buff.hex(e, size));\n }\n static create_varint(num, endian) {\n if (num < 0) {\n throw new Error(`Varint cannot be negative: ${num}`);\n }\n if (num < 0xFD) {\n return Buff.num(num, 1);\n }\n else if (num < 0x10000) {\n return Buff.of(0xFD, ...Buff.num(num, 2, endian));\n }\n else if (num < 0x100000000) {\n return Buff.of(0xFE, ...Buff.num(num, 4, endian));\n }\n else if (BigInt(num) < 0x10000000000000000n) {\n return Buff.of(0xFF, ...Buff.num(num, 8, endian));\n }\n else {\n throw new Error(`Value is too large: ${num}`);\n }\n }\n}\n","export function bin_to_bytes(binary) {\n if (!/^[01]*$/.test(binary)) {\n throw new TypeError('Binary string must contain only 0 and 1 characters');\n }\n const bins = binary.split('').map(Number);\n if (bins.length % 8 !== 0) {\n throw new Error(`Binary array is invalid length: ${binary.length}`);\n }\n const bytes = new Uint8Array(bins.length / 8);\n for (let i = 0, ct = 0; i < bins.length; i += 8, ct++) {\n let byte = 0;\n for (let j = 0; j < 8; j++) {\n byte |= (bins[i + j] << (7 - j));\n }\n bytes[ct] = byte;\n }\n return bytes;\n}\nexport function bytes_to_bin(bytes) {\n const bin = new Array(bytes.length * 8);\n let count = 0;\n for (const num of bytes) {\n if (num > 255) {\n throw new Error(`Invalid byte value: ${num}. Byte values must be between 0 and 255.`);\n }\n for (let i = 7; i >= 0; i--, count++) {\n bin[count] = (num >> i) & 1;\n }\n }\n return bin.join('');\n}\n","import { Buff } from '../class/buff.js';\nexport class Stream {\n constructor(data) {\n this.data = new Buff(data);\n this.size = this.data.length;\n }\n peek(size) {\n if (size > this.size) {\n throw new Error(`Size greater than stream: ${size} > ${this.size}`);\n }\n return new Buff(this.data.slice(0, size));\n }\n read(size) {\n const chunk = this.peek(size);\n this.data = this.data.slice(size);\n this.size = this.data.length;\n return chunk;\n }\n read_varint(endian) {\n const num = this.read(1).num;\n switch (true) {\n case (num >= 0 && num < 0xFD):\n return num;\n case (num === 0xFD):\n return this.read(2).to_num(endian);\n case (num === 0xFE):\n return this.read(4).to_num(endian);\n case (num === 0xFF):\n return this.read(8).to_num(endian);\n default:\n throw new Error(`Varint is out of range: ${num}`);\n }\n }\n}\n","/**\n * Custom error classes for @vbyte/btc-dev\n *\n * These errors provide more specific error types for better error handling:\n * - ValidationError: Invalid input format, out of range values, etc.\n * - DecodingError: Malformed data during decode/parse operations\n * - ConfigError: Invalid configuration (unknown network, missing config, etc.)\n *\n * @example\n * ```typescript\n * import { ValidationError, DecodingError } from '@vbyte/btc-dev/error'\n *\n * try {\n * const tx = TX.decode(malformedData)\n * } catch (err) {\n * if (err instanceof DecodingError) {\n * console.log('Malformed data at position:', err.position)\n * }\n * }\n * ```\n */\n\n/**\n * Thrown when input validation fails.\n *\n * Common scenarios:\n * - Invalid format (wrong length, bad encoding)\n * - Out of range values\n * - Missing required fields\n * - Type mismatches\n *\n * @example\n * ```typescript\n * throw new ValidationError('Public key must be 33 bytes', 'pubkey')\n * ```\n */\nexport class ValidationError extends Error {\n\t/** The field or parameter that failed validation */\n\tfield?: string;\n\n\tconstructor(message: string, field?: string) {\n\t\tsuper(message);\n\t\tthis.name = \"ValidationError\";\n\t\tthis.field = field;\n\t}\n}\n\n/**\n * Thrown when decoding or parsing malformed data fails.\n *\n * Common scenarios:\n * - Truncated data (unexpected end of stream)\n * - Invalid opcodes in scripts\n * - Malformed transaction structure\n * - Invalid witness data\n *\n * @example\n * ```typescript\n * throw new DecodingError('Unexpected end of stream', 42)\n * ```\n */\nexport class DecodingError extends Error {\n\t/** Byte position where the error occurred */\n\tposition?: number;\n\n\tconstructor(message: string, position?: number) {\n\t\tsuper(message);\n\t\tthis.name = \"DecodingError\";\n\t\tthis.position = position;\n\t}\n}\n\n/**\n * Thrown when configuration is invalid.\n *\n * Common scenarios:\n * - Unknown network type\n * - Invalid sighash type\n * - Missing required configuration options\n * - Incompatible option combinations\n *\n * @example\n * ```typescript\n * throw new ConfigError('Unknown network: foonet')\n * ```\n */\nexport class ConfigError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"ConfigError\";\n\t}\n}\n","/**\n * Locking script type detection utilities.\n *\n * Functions for identifying Bitcoin locking script types (P2PKH, P2SH, P2WPKH, P2WSH, P2TR).\n * These are used to determine how to sign and verify transactions.\n *\n * @module\n */\n\nimport { Buff, type Bytes } from \"@vbyte/buff\";\nimport { LOCK_SCRIPT_REGEX } from \"@/const.js\";\n\nimport type {\n\tLockScriptInfo,\n\tLockScriptType,\n\tWitnessVersion,\n} from \"@/types/index.js\";\n\n/**\n * Check if a script is an OP_RETURN script.\n *\n * OP_RETURN scripts start with opcode 0x6a and are used for data embedding.\n * These outputs are provably unspendable.\n *\n * @param script - The script to check (hex string or bytes)\n * @returns True if the script is an OP_RETURN script\n *\n * @example\n * ```typescript\n * is_return_script('6a0b68656c6c6f20776f726c64') // true (OP_RETURN + \"hello world\")\n * is_return_script('76a914...88ac') // false (P2PKH)\n * ```\n */\nexport function is_return_script(script: Bytes): boolean {\n\tconst bytes = Buff.bytes(script);\n\treturn bytes.at(0) === 0x6a;\n}\n\n/**\n * Get complete information about a locking script.\n *\n * Returns both the script type and witness version (if applicable).\n *\n * @param script - The locking script (hex string or bytes)\n * @returns Object with type and version properties\n *\n * @example\n * ```typescript\n * get_lock_script_info('0014' + pubkeyHash)\n * // { type: 'p2wpkh', version: 0 }\n *\n * get_lock_script_info('5120' + tapkey)\n * // { type: 'p2tr', version: 1 }\n * ```\n */\nexport function get_lock_script_info(script: Bytes): LockScriptInfo {\n\treturn {\n\t\ttype: get_lock_script_type(script),\n\t\tversion: get_lock_script_version(script),\n\t};\n}\n\n/**\n * Identify the type of a locking script.\n *\n * Checks the script against known patterns for P2PKH, P2SH, P2WPKH, P2WSH,\n * P2TR, and OP_RETURN scripts.\n *\n * @param script - The locking script (hex string or bytes)\n * @returns The script type ('p2pkh', 'p2sh', 'p2wpkh', 'p2wsh', 'p2tr', 'opreturn') or null if unknown\n *\n * @example\n * ```typescript\n * get_lock_script_type('76a914' + hash160 + '88ac') // 'p2pkh'\n * get_lock_script_type('0014' + pubkeyHash) // 'p2wpkh'\n * get_lock_script_type('5120' + taprootKey) // 'p2tr'\n * get_lock_script_type('deadbeef') // null (unknown)\n * ```\n */\nexport function get_lock_script_type(script: Bytes): LockScriptType | null {\n\t// Get the hex string of the script.\n\tconst hex = Buff.bytes(script).hex;\n\t// Iterate over the lock script regexes.\n\tfor (const [type, regex] of Object.entries(LOCK_SCRIPT_REGEX)) {\n\t\t// If the script matches the regex, return the type.\n\t\tif (regex.test(hex)) return type as LockScriptType;\n\t}\n\t// If the script does not match any regex, return null.\n\treturn null;\n}\n\n/**\n * Get the witness version of a locking script.\n *\n * SegWit scripts use version bytes: 0x00 for v0 (P2WPKH/P2WSH), 0x51 for v1 (P2TR).\n * Non-SegWit scripts return null.\n *\n * @param script - The locking script (hex string or bytes)\n * @returns The witness version (0 or 1) or null for non-SegWit scripts\n *\n * @example\n * ```typescript\n * get_lock_script_version('0014' + hash) // 0 (SegWit v0)\n * get_lock_script_version('5120' + key) // 1 (SegWit v1/Taproot)\n * get_lock_script_version('76a914...') // null (Legacy P2PKH)\n * ```\n */\nexport function get_lock_script_version(script: Bytes): WitnessVersion | null {\n\t// Get the version of the script.\n\tconst version = Buff.bytes(script);\n\t// Return the version of the script.\n\tswitch (version.at(0)) {\n\t\tcase 0x00:\n\t\t\treturn 0;\n\t\tcase 0x51:\n\t\t\treturn 1;\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/**\n * Check if a script is a P2PKH (Pay-to-Public-Key-Hash) script.\n *\n * P2PKH is the original Bitcoin address format. Script pattern:\n * OP_DUP OP_HASH160 <20 bytes> OP_EQUALVERIFY OP_CHECKSIG\n *\n * @param script - The script to check (hex string or bytes)\n * @returns True if the script is P2PKH\n *\n * @example\n * ```typescript\n * is_p2pkh_script('76a914' + hash160 + '88ac') // true\n * ```\n */\nexport function is_p2pkh_script(script: Bytes): boolean {\n\tconst hex = Buff.bytes(script).hex;\n\treturn LOCK_SCRIPT_REGEX.p2pkh.test(hex);\n}\n\n/**\n * Check if a script is a P2SH (Pay-to-Script-Hash) script.\n *\n * P2SH allows spending based on script hash. Script pattern:\n * OP_HASH160 <20 bytes> OP_EQUAL\n *\n * @param script - The script to check (hex string or bytes)\n * @returns True if the script is P2SH\n *\n * @example\n * ```typescript\n * is_p2sh_script('a914' + scriptHash + '87') // true\n * ```\n */\nexport function is_p2sh_script(script: Bytes): boolean {\n\tconst hex = Buff.bytes(script).hex;\n\treturn LOCK_SCRIPT_REGEX.p2sh.test(hex);\n}\n\n/**\n * Check if a script is a P2WPKH (Pay-to-Witness-Public-Key-Hash) script.\n *\n * P2WPKH is native SegWit v0 for single-key addresses. Script pattern:\n * OP_0 <20 bytes>\n *\n * @param script - The script to check (hex string or bytes)\n * @returns True if the script is P2WPKH\n *\n * @example\n * ```typescript\n * is_p2wpkh_script('0014' + pubkeyHash) // true\n * ```\n */\nexport function is_p2wpkh_script(script: Bytes): boolean {\n\tconst hex = Buff.bytes(script).hex;\n\treturn LOCK_SCRIPT_REGEX.p2wpkh.test(hex);\n}\n\n/**\n * Check if a script is a P2WSH (Pay-to-Witness-Script-Hash) script.\n *\n * P2WSH is native SegWit v0 for script-based addresses. Script pattern:\n * OP_0 <32 bytes>\n *\n * @param script - The script to check (hex string or bytes)\n * @returns True if the script is P2WSH\n *\n * @example\n * ```typescript\n * is_p2wsh_script('0020' + sha256Hash) // true\n * ```\n */\nexport function is_p2wsh_script(script: Bytes): boolean {\n\tconst hex = Buff.bytes(script).hex;\n\treturn LOCK_SCRIPT_REGEX.p2wsh.test(hex);\n}\n\n/**\n * Check if a script is a P2TR (Pay-to-Taproot) script.\n *\n * P2TR is SegWit v1 (Taproot). Script pattern:\n * OP_1 <32 bytes>\n *\n * @param script - The script to check (hex string or bytes)\n * @returns True if the script is P2TR\n *\n * @example\n * ```typescript\n * is_p2tr_script('5120' + xOnlyPubkey) // true\n * ```\n */\nexport function is_p2tr_script(script: Bytes): boolean {\n\tconst hex = Buff.bytes(script).hex;\n\treturn LOCK_SCRIPT_REGEX.p2tr.test(hex);\n}\n\n/**\n * Check if a script is an OP_RETURN script using regex matching.\n *\n * Alternative to is_return_script() that uses the standard regex pattern.\n *\n * @param script - The script to check (hex string or bytes)\n * @returns True if the script is OP_RETURN\n *\n * @example\n * ```typescript\n * is_opreturn_script('6a' + data) // true\n * ```\n */\nexport function is_opreturn_script(script: Bytes): boolean {\n\tconst hex = Buff.bytes(script).hex;\n\treturn LOCK_SCRIPT_REGEX.opreturn.test(hex);\n}\n","export function pick(obj, keys) {\n const result = {};\n for (const key of keys) {\n if (key in obj)\n result[key] = obj[key];\n }\n return result;\n}\nexport function omit(obj, keys) {\n const result = { ...obj };\n for (const key of keys) {\n delete result[key];\n }\n return result;\n}\nexport function is_empty(obj) {\n return Object.keys(obj).length === 0;\n}\nexport function sort(obj) {\n if (obj === null ||\n obj === undefined ||\n obj instanceof Map ||\n obj instanceof Set ||\n obj instanceof Date ||\n Array.isArray(obj) ||\n typeof obj !== 'object') {\n return obj;\n }\n else {\n return Object.keys(obj)\n .sort()\n .filter(key => obj[key] !== undefined)\n .reduce((sorted, key) => {\n sorted[key] = obj[key];\n return sorted;\n }, {});\n }\n}\n","import { sort } from './obj.js';\nexport var Test;\n(function (Test) {\n function exists(value) {\n if (typeof value === 'undefined' || value === null) {\n return false;\n }\n return true;\n }\n Test.exists = exists;\n function is_equal(a, b) {\n return a === b;\n }\n Test.is_equal = is_equal;\n function is_object(value) {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n }\n Test.is_object = is_object;\n function is_deep_equal(a, b) {\n if (is_object(a))\n a = sort(a);\n if (is_object(b))\n b = sort(b);\n return JSON.stringify(a) === JSON.stringify(b);\n }\n Test.is_deep_equal = is_deep_equal;\n function has_items(array) {\n return Array.isArray(array) && array.length > 0;\n }\n Test.has_items = has_items;\n function is_string(value) {\n return typeof value === 'string';\n }\n Test.is_string = is_string;\n function is_number(value) {\n return typeof value === 'number' && Number.isFinite(value);\n }\n Test.is_number = is_number;\n function is_integer(value) {\n return Number.isInteger(value);\n }\n Test.is_integer = is_integer;\n function is_bigint(value) {\n return typeof value === 'bigint';\n }\n Test.is_bigint = is_bigint;\n function is_uchar(value) {\n return is_integer(value) && value >= 0 && value <= 0xFF;\n }\n Test.is_uchar = is_uchar;\n function is_ushort(value) {\n return is_integer(value) && value >= 0 && value <= 0xFFFF;\n }\n Test.is_ushort = is_ushort;\n function is_uint(value) {\n return is_integer(value) && value >= 0 && value <= 0xFFFFFFFF;\n }\n Test.is_uint = is_uint;\n function is_u8a(value) {\n return value instanceof Uint8Array;\n }\n Test.is_u8a = is_u8a;\n function is_base58(value) {\n if (typeof value !== 'string')\n return false;\n return /^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]+$/.test(value);\n }\n Test.is_base58 = is_base58;\n function is_base64(value) {\n if (typeof value !== 'string')\n return false;\n return /^[a-zA-Z0-9+/]+={0,2}$/.test(value);\n }\n Test.is_base64 = is_base64;\n function is_b64url(value) {\n if (typeof value !== 'string')\n return false;\n return /^[a-zA-Z0-9\\-_]+={0,2}$/.test(value);\n }\n Test.is_b64url = is_b64url;\n function is_bech32(value) {\n if (typeof value !== 'string')\n return false;\n return /^[a-z]+1[023456789acdefghjklmnpqrstuvwxyz]+$/.test(value);\n }\n Test.is_bech32 = is_bech32;\n function is_hex(value) {\n if (!is_string(value))\n return false;\n return (value.match(/[^a-fA-F0-9]/) === null && value.length % 2 === 0);\n }\n Test.is_hex = is_hex;\n function is_hash(value) {\n return (is_string(value) && is_hex(value) && value.length === 64);\n }\n Test.is_hash = is_hash;\n function is_null(value) {\n return value === null;\n }\n Test.is_null = is_null;\n function is_undefined(value) {\n return value === undefined;\n }\n Test.is_undefined = is_undefined;\n function is_array(value) {\n return Array.isArray(value);\n }\n Test.is_array = is_array;\n function is_function(value) {\n return typeof value === 'function';\n }\n Test.is_function = is_function;\n function is_error(value) {\n return value instanceof Error;\n }\n Test.is_error = is_error;\n function is_promise(value) {\n return value instanceof Promise || (is_object(value) && is_function(value.then) && is_function(value.catch));\n }\n Test.is_promise = is_promise;\n})(Test || (Test = {}));\n","import { Test } from './test.js';\nexport var Assert;\n(function (Assert) {\n function ok(value, message) {\n if (value === false) {\n throw new Error(message ?? 'Assertion failed!');\n }\n }\n Assert.ok = ok;\n function exists(value, msg) {\n if (!Test.exists(value)) {\n throw new Error(msg ?? 'Value is null or undefined!');\n }\n }\n Assert.exists = exists;\n function is_empty(value, msg) {\n if (value !== null && value !== undefined) {\n throw new Error(msg ?? 'value is not null or undefined!');\n }\n }\n Assert.is_empty = is_empty;\n function is_instance(value, type, msg) {\n if (!(value instanceof type)) {\n throw new Error(msg ?? `value is not an instance of ${type.name}`);\n }\n }\n Assert.is_instance = is_instance;\n function is_equal(a, b, msg) {\n if (!Test.is_equal(a, b)) {\n throw new Error(msg ?? `values are not equal: ${String(a)} !== ${String(b)}`);\n }\n }\n Assert.is_equal = is_equal;\n function is_object(value, msg) {\n if (!Test.is_object(value)) {\n throw new Error(msg ?? `value is not an object: ${String(value)}`);\n }\n }\n Assert.is_object = is_object;\n function is_deep_equal(a, b, msg) {\n if (!Test.is_deep_equal(a, b)) {\n throw new Error(msg ?? `values are not deep equal: ${String(a)} !== ${String(b)}`);\n }\n }\n Assert.is_deep_equal = is_deep_equal;\n function is_number(value) {\n if (!Test.is_number(value)) {\n throw new TypeError(`invalid number: ${String(value)}`);\n }\n }\n Assert.is_number = is_number;\n function is_integer(value) {\n if (!Test.is_integer(value)) {\n throw new TypeError(`invalid integer: ${String(value)}`);\n }\n }\n Assert.is_integer = is_integer;\n function is_bigint(value) {\n if (!Test.is_bigint(value)) {\n throw new TypeError(`invalid bigint: ${String(value)}`);\n }\n }\n Assert.is_bigint = is_bigint;\n function is_hex(value) {\n if (!Test.is_hex(value)) {\n throw new TypeError(`invalid hex: ${String(value)}`);\n }\n }\n Assert.is_hex = is_hex;\n function is_uchar(value) {\n if (!Test.is_uchar(value)) {\n throw new TypeError(`invalid unsignedchar: ${String(value)}`);\n }\n }\n Assert.is_uchar = is_uchar;\n function is_ushort(value) {\n if (!Test.is_ushort(value)) {\n throw new TypeError(`invalid unsigned short: ${String(value)}`);\n }\n }\n Assert.is_ushort = is_ushort;\n function is_uint(value) {\n if (!Test.is_uint(value)) {\n throw new TypeError(`invalid unsigned int: ${String(value)}`);\n }\n }\n Assert.is_uint = is_uint;\n function is_u8a(value) {\n if (!Test.is_u8a(value)) {\n throw new TypeError(`invalid Uint8Array: ${String(value)}`);\n }\n }\n Assert.is_u8a = is_u8a;\n function is_hash(value, msg) {\n if (!Test.is_hash(value)) {\n throw new TypeError(msg ?? `invalid hash: ${String(value)}`);\n }\n }\n Assert.is_hash = is_hash;\n function has_items(array, err_msg) {\n if (!Test.has_items(array)) {\n throw new Error(err_msg ?? 'array does not contain any items');\n }\n }\n Assert.has_items = has_items;\n function is_base58(value) {\n if (!Test.is_base58(value)) {\n throw new Error('invalid base58 string');\n }\n }\n Assert.is_base58 = is_base58;\n function is_base64(value) {\n if (!Test.is_base64(value)) {\n throw new Error('invalid base64 string');\n }\n }\n Assert.is_base64 = is_base64;\n function is_b64url(value) {\n if (!Test.is_b64url(value)) {\n throw new Error('invalid base64url string');\n }\n }\n Assert.is_b64url = is_b64url;\n function is_bech32(value) {\n if (!Test.is_bech32(value)) {\n throw new Error('invalid bech32 string');\n }\n }\n Assert.is_bech32 = is_bech32;\n})(Assert || (Assert = {}));\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n, title = '') {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(value, length, title = '') {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/** Merges default options and passed options. */\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** Creates function with outputLen, blockLen, create properties from a class constructor. */\nexport function createHasher(hashCons, info = {}) {\n const hashC = (msg, opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */\nexport const oidNist = (suffix) => ({\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n//# sourceMappingURL=utils.js.map","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean } from \"./utils.js\";\n/** Internal class for HMAC. */\nexport class _HMAC {\n oHash;\n iHash;\n blockLen;\n outputLen;\n finished = false;\n destroyed = false;\n constructor(hash, key) {\n ahash(hash);\n abytes(key, undefined, 'key');\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n abytes(out, this.outputLen, 'output');\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new _HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView } from \"./utils.js\";\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD {\n blockLen;\n outputLen;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to ||= new this.constructor();\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from \"./_md.js\";\nimport { clean, createHasher, rotl } from \"./utils.js\";\n/** Initial SHA1 state */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n// Reusable temporary buffer\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA1 legacy hash class. */\nexport class _SHA1 extends HashMD {\n A = SHA1_IV[0] | 0;\n B = SHA1_IV[1] | 0;\n C = SHA1_IV[2] | 0;\n D = SHA1_IV[3] | 0;\n E = SHA1_IV[4] | 0;\n constructor() {\n super(64, 20, 8, false);\n }\n get() {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n set(A, B, C, D, E) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n }\n else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n }\n else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n }\n else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n this.set(A, B, C, D, E);\n }\n roundClean() {\n clean(SHA1_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */\nexport const sha1 = /* @__PURE__ */ createHasher(() => new _SHA1());\n/** Per-round constants */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));\n/** md5 initial state: same as sha1, but 4 u32 instead of 5. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n// Reusable temporary buffer\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n/** Internal MD5 legacy hash class. */\nexport class _MD5 extends HashMD {\n A = MD5_IV[0] | 0;\n B = MD5_IV[1] | 0;\n C = MD5_IV[2] | 0;\n D = MD5_IV[3] | 0;\n constructor() {\n super(64, 16, 8, true);\n }\n get() {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n set(A, B, C, D) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g, s;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n s = [7, 12, 17, 22];\n }\n else if (i < 32) {\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n s = [5, 9, 14, 20];\n }\n else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n s = [4, 11, 16, 23];\n }\n else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n s = [6, 10, 15, 21];\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, s[i % 4]);\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n this.set(A, B, C, D);\n }\n roundClean() {\n clean(MD5_W);\n }\n destroy() {\n this.set(0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n */\nexport const md5 = /* @__PURE__ */ createHasher(() => new _MD5());\n// RIPEMD-160\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++)\n for (let j of res)\n j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction ripemd_f(group, x, y, z) {\n if (group === 0)\n return x ^ y ^ z;\n if (group === 1)\n return (x & y) | (~x & z);\n if (group === 2)\n return (x | ~y) ^ z;\n if (group === 3)\n return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable temporary buffer\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\nexport class _RIPEMD160 extends HashMD {\n h0 = 0x67452301 | 0;\n h1 = 0xefcdab89 | 0;\n h2 = 0x98badcfe | 0;\n h3 = 0x10325476 | 0;\n h4 = 0xc3d2e1f0 | 0;\n constructor() {\n super(64, 20, 8, true);\n }\n get() {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n set(h0, h1, h2, h3, h4) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);\n }\n roundClean() {\n clean(BUF_160);\n }\n destroy() {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\n */\nexport const ripemd160 = /* @__PURE__ */ createHasher(() => new _RIPEMD160());\n//# sourceMappingURL=legacy.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://www.rfc-editor.org/rfc/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal 32-byte base SHA2 hash class. */\nclass SHA2_32B extends HashMD {\n constructor(outputLen) {\n super(64, outputLen, 8, false);\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA2-256 hash class. */\nexport class _SHA256 extends SHA2_32B {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n/** Internal SHA2-224 hash class. */\nexport class _SHA224 extends SHA2_32B {\n A = SHA224_IV[0] | 0;\n B = SHA224_IV[1] | 0;\n C = SHA224_IV[2] | 0;\n D = SHA224_IV[3] | 0;\n E = SHA224_IV[4] | 0;\n F = SHA224_IV[5] | 0;\n G = SHA224_IV[6] | 0;\n H = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal 64-byte base SHA2 hash class. */\nclass SHA2_64B extends HashMD {\n constructor(outputLen) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/** Internal SHA2-512 hash class. */\nexport class _SHA512 extends SHA2_64B {\n Ah = SHA512_IV[0] | 0;\n Al = SHA512_IV[1] | 0;\n Bh = SHA512_IV[2] | 0;\n Bl = SHA512_IV[3] | 0;\n Ch = SHA512_IV[4] | 0;\n Cl = SHA512_IV[5] | 0;\n Dh = SHA512_IV[6] | 0;\n Dl = SHA512_IV[7] | 0;\n Eh = SHA512_IV[8] | 0;\n El = SHA512_IV[9] | 0;\n Fh = SHA512_IV[10] | 0;\n Fl = SHA512_IV[11] | 0;\n Gh = SHA512_IV[12] | 0;\n Gl = SHA512_IV[13] | 0;\n Hh = SHA512_IV[14] | 0;\n Hl = SHA512_IV[15] | 0;\n constructor() {\n super(64);\n }\n}\n/** Internal SHA2-384 hash class. */\nexport class _SHA384 extends SHA2_64B {\n Ah = SHA384_IV[0] | 0;\n Al = SHA384_IV[1] | 0;\n Bh = SHA384_IV[2] | 0;\n Bl = SHA384_IV[3] | 0;\n Ch = SHA384_IV[4] | 0;\n Cl = SHA384_IV[5] | 0;\n Dh = SHA384_IV[6] | 0;\n Dl = SHA384_IV[7] | 0;\n Eh = SHA384_IV[8] | 0;\n El = SHA384_IV[9] | 0;\n Fh = SHA384_IV[10] | 0;\n Fl = SHA384_IV[11] | 0;\n Gh = SHA384_IV[12] | 0;\n Gl = SHA384_IV[13] | 0;\n Hh = SHA384_IV[14] | 0;\n Hl = SHA384_IV[15] | 0;\n constructor() {\n super(48);\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA2-512/224 hash class. */\nexport class _SHA512_224 extends SHA2_64B {\n Ah = T224_IV[0] | 0;\n Al = T224_IV[1] | 0;\n Bh = T224_IV[2] | 0;\n Bl = T224_IV[3] | 0;\n Ch = T224_IV[4] | 0;\n Cl = T224_IV[5] | 0;\n Dh = T224_IV[6] | 0;\n Dl = T224_IV[7] | 0;\n Eh = T224_IV[8] | 0;\n El = T224_IV[9] | 0;\n Fh = T224_IV[10] | 0;\n Fl = T224_IV[11] | 0;\n Gh = T224_IV[12] | 0;\n Gl = T224_IV[13] | 0;\n Hh = T224_IV[14] | 0;\n Hl = T224_IV[15] | 0;\n constructor() {\n super(28);\n }\n}\n/** Internal SHA2-512/256 hash class. */\nexport class _SHA512_256 extends SHA2_64B {\n Ah = T256_IV[0] | 0;\n Al = T256_IV[1] | 0;\n Bh = T256_IV[2] | 0;\n Bl = T256_IV[3] | 0;\n Ch = T256_IV[4] | 0;\n Cl = T256_IV[5] | 0;\n Dh = T256_IV[6] | 0;\n Dl = T256_IV[7] | 0;\n Eh = T256_IV[8] | 0;\n El = T256_IV[9] | 0;\n Fh = T256_IV[10] | 0;\n Fl = T256_IV[11] | 0;\n Gh = T256_IV[12] | 0;\n Gl = T256_IV[13] | 0;\n Hh = T256_IV[14] | 0;\n Hl = T256_IV[15] | 0;\n constructor() {\n super(32);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n//# sourceMappingURL=sha2.js.map","import { Buff } from '@vbyte/buff';\nimport { hmac as noble_hmac } from '@noble/hashes/hmac.js';\nimport { pbkdf2 as noble_pbkdf2 } from '@noble/hashes/pbkdf2.js';\nimport { ripemd160 as noble_r160 } from '@noble/hashes/legacy.js';\nimport { sha256 as noble_s256, sha512 as noble_s512 } from '@noble/hashes/sha2.js';\nexport function hash160(...input) {\n const buffer = Buff.join(input);\n const digest = noble_r160(noble_s256(buffer));\n return new Buff(digest);\n}\nexport function sha256(...input) {\n const buffer = Buff.join(input);\n const digest = noble_s256(buffer);\n return new Buff(digest);\n}\nexport function hash256(...input) {\n const buffer = Buff.join(input);\n const digest = noble_s256(noble_s256(buffer));\n return new Buff(digest);\n}\nexport function hashtag(tag) {\n const hash = sha256(Buff.str(tag));\n return Buff.join([hash, hash]);\n}\nexport function hash340(tag, ...input) {\n const htag = hashtag(tag);\n const pimg = Buff.join([htag, ...input]);\n return sha256(pimg);\n}\nexport function hmac256(key, ...input) {\n const mask = new Buff(key);\n const buffer = Buff.join(input);\n const digest = noble_hmac(noble_s256, mask, buffer);\n return new Buff(digest);\n}\nexport function hmac512(key, ...input) {\n const mask = new Buff(key);\n const buffer = Buff.join(input);\n const digest = noble_hmac(noble_s512, mask, buffer);\n return new Buff(digest);\n}\nexport function pkdf256(secret, salt, options) {\n const { c = 100000, dk_len = 32 } = options ?? {};\n const sec_u8 = new Buff(secret);\n const salt_u8 = new Buff(salt);\n const digest = noble_pbkdf2(noble_s256, sec_u8, salt_u8, { c, dkLen: dk_len });\n return new Buff(digest);\n}\nexport function pkdf512(secret, salt, options) {\n const { c = 100000, dk_len = 32 } = options ?? {};\n const sec_u8 = new Buff(secret);\n const salt_u8 = new Buff(salt);\n const digest = noble_pbkdf2(noble_s512, sec_u8, salt_u8, { c, dkLen: dk_len });\n return new Buff(digest);\n}\n","import { Buff } from '@vbyte/buff';\nexport var Assert;\n(function (Assert) {\n function ok(value, message) {\n if (!value) {\n throw new Error(message ?? 'Assertion failed!');\n }\n }\n Assert.ok = ok;\n function size(input, size, msg) {\n const bytes = Buff.bytes(input);\n if (bytes.length !== size) {\n throw new Error(msg ?? `invalid input size: ${bytes.length} !== ${size}`);\n }\n }\n Assert.size = size;\n function is_u8a(value) {\n if (!(value instanceof Uint8Array)) {\n throw new TypeError(`invalid Uint8Array: ${String(value)}`);\n }\n }\n Assert.is_u8a = is_u8a;\n function is_base58(value) {\n if (typeof value !== 'string' || !/^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]+$/.test(value)) {\n throw new Error('invalid base58 string');\n }\n }\n Assert.is_base58 = is_base58;\n function is_base64(value) {\n if (typeof value !== 'string' || value.length === 0 || !/^[a-zA-Z0-9+/]+={0,2}$/.test(value)) {\n throw new Error('invalid base64 string');\n }\n }\n Assert.is_base64 = is_base64;\n function is_b64url(value) {\n if (typeof value !== 'string' || value.length === 0 || !/^[a-zA-Z0-9\\-_]+={0,2}$/.test(value)) {\n throw new Error('invalid base64url string');\n }\n }\n Assert.is_b64url = is_b64url;\n function is_bech32(value) {\n if (typeof value !== 'string' || !/^[a-z]+1[023456789acdefghjklmnpqrstuvwxyz]+$/.test(value)) {\n throw new Error('invalid bech32 string');\n }\n }\n Assert.is_bech32 = is_bech32;\n})(Assert || (Assert = {}));\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes as abytes_, anumber, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, } from '@noble/hashes/utils.js';\nexport { abytes, anumber, bytesToHex, concatBytes, hexToBytes, isBytes, randomBytes, } from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n// Used in weierstrass, der\nfunction abignumber(n) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n))\n throw new Error('positive bigint expected, got ' + n);\n }\n else\n anumber(n);\n return n;\n}\nexport function asafenumber(value, title = '') {\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected safe integer, got type=' + typeof value);\n }\n}\nexport function numberToHexUnpadded(num) {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n anumber(len);\n n = abignumber(n);\n const res = hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n if (res.length !== len)\n throw new Error('number too large');\n return res;\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes_(numberToHexUnpadded(abignumber(n)));\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes) {\n return Uint8Array.from(bytes);\n}\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n */\nexport function asciiToBytes(ascii) {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_1n << BigInt(n)) - _1n;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n anumber(hashLen, 'hashLen');\n anumber(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n const u8n = (len) => new Uint8Array(len); // creates Uint8Array\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...msgs) => hmacFn(k, concatBytes_(v, ...msgs)); // hmac(k)(v, ...values)\n const reseed = (seed = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= _maxDrbgIters)\n throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\nexport function validateObject(object, fields = {}, optFields = {}) {\n if (!object || typeof object !== 'object')\n throw new Error('expected valid options object');\n function checkField(fieldName, expectedType, isOpt) {\n const val = object[fieldName];\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn) {\n const map = new WeakMap();\n return (arg, ...args) => {\n const val = map.get(arg);\n if (val !== undefined)\n return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n//# sourceMappingURL=utils.js.map","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes, anumber, bytesToNumberBE, bytesToNumberLE, numberToBytesBE, numberToBytesLE, validateObject, } from \"../utils.js\";\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _16n = /* @__PURE__ */ BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num, power, modulo) {\n return FpPow(Field(modulo), num, power);\n}\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n if (modulo <= _0n)\n throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\nfunction assertIsSquare(Fp, root, n) {\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n}\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp, n) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\nfunction sqrt5mod8(Fp, n) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n assertIsSquare(Fp, root, n);\n return root;\n}\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P) {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return (Fp, n) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n)\n throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000)\n throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1)\n return sqrt3mod4;\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n if (Fp.is0(n))\n return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1)\n throw new Error('Cannot find square root');\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t))\n return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M)\n throw new Error('Cannot find square root');\n }\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P) {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n)\n return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n)\n return sqrt5mod8;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n)\n return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(Fp, num, power) {\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return Fp.ONE;\n if (power === _1n)\n return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp, nums, passZero = false) {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num))\n return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num))\n return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n// TODO: remove\nexport function FpDiv(Fp, lhs, rhs) {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n */\nexport function FpLegendre(Fp, n) {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no)\n throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp, n) {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined)\n anumber(nBitLength);\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\nclass _Field {\n ORDER;\n BITS;\n BYTES;\n isLE;\n ZERO = _0n;\n ONE = _1n;\n _lengths;\n _sqrt; // cached sqrt\n _mod;\n constructor(ORDER, opts = {}) {\n if (ORDER <= _0n)\n throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n if (typeof opts.BITS === 'number')\n _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function')\n this.sqrt = opts.sqrt;\n if (typeof opts.isLE === 'boolean')\n this.isLE = opts.isLE;\n if (opts.allowedLengths)\n this._lengths = opts.allowedLengths?.slice();\n if (typeof opts.modFromBytes === 'boolean')\n this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048)\n throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n this._sqrt = undefined;\n Object.preventExtensions(this);\n }\n create(num) {\n return mod(num, this.ORDER);\n }\n isValid(num) {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num) {\n return (num & _1n) === _1n;\n }\n neg(num) {\n return mod(-num, this.ORDER);\n }\n eql(lhs, rhs) {\n return lhs === rhs;\n }\n sqr(num) {\n return mod(num * num, this.ORDER);\n }\n add(lhs, rhs) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs, rhs) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs, rhs) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num, power) {\n return FpPow(this, num, power);\n }\n div(lhs, rhs) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n // Same as above, but doesn't normalize\n sqrN(num) {\n return num * num;\n }\n addN(lhs, rhs) {\n return lhs + rhs;\n }\n subN(lhs, rhs) {\n return lhs - rhs;\n }\n mulN(lhs, rhs) {\n return lhs * rhs;\n }\n inv(num) {\n return invert(num, this.ORDER);\n }\n sqrt(num) {\n // Caching _sqrt speeds up sqrt9mod16 by 5x and tonneli-shanks by 10%\n if (!this._sqrt)\n this._sqrt = FpSqrt(this.ORDER);\n return this._sqrt(this, num);\n }\n toBytes(num) {\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes)\n scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst) {\n return FpInvertBatch(this, lst);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a, b, condition) {\n return condition ? b : a;\n }\n}\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, opts = {}) {\n return new _Field(ORDER, opts);\n}\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.Point.Fn.ORDER)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n abytes(key);\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask } from \"../utils.js\";\nimport { Field, FpInvertBatch, validateField } from \"./modular.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport function negateCt(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\n}\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\nexport function normalizeZ(c, points) {\n const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\nfunction validateW(W, bits) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\nfunction calcWOpts(W, scalarBits) {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\nfunction calcOffsets(n, window, wOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\nfunction validateMSMPoints(points, c) {\n if (!Array.isArray(points))\n throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars, field) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error('invalid scalar at index ' + i);\n });\n}\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\nfunction getW(P) {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\nfunction assert0(n) {\n if (n !== _0n)\n throw new Error('invalid wNAF');\n}\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF {\n BASE;\n ZERO;\n Fn;\n bits;\n // Parametrized with a given Point class (not individual point)\n constructor(Point, bits) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n // non-const time multiplication ladder\n _unsafeLadder(elm, n, p = this.ZERO) {\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(point, W) {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points = [];\n let p = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n))\n throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n }\n else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n }\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n)\n break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n }\n else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n getPrecomputes(W, point, transform) {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W);\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function')\n comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n cached(point, scalar, transform) {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n unsafe(point, scalar, transform, prev) {\n const W = getW(point);\n if (W === 1)\n return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P, W) {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n hasCache(elm) {\n return getW(elm) !== 1;\n }\n}\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe(Point, point, k1, k2) {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n p1 = p1.add(acc);\n if (k2 & _1n)\n p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka secret keys / bigints)\n */\nexport function pippenger(c, points, scalars) {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength)\n throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12)\n windowSize = wbits - 3;\n else if (wbits > 4)\n windowSize = wbits - 2;\n else if (wbits > 0)\n windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe(c, points, windowSize) {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n const fieldN = c.Fn;\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero)\n for (let j = 0; j < windowSize; j++)\n res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr)\n continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\nfunction createField(order, field, isLE) {\n if (field) {\n if (field.ORDER !== order)\n throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n }\n else {\n return Field(order, { isLE });\n }\n}\n/** Validates CURVE opts and creates fields */\nexport function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {\n if (FpFnLE === undefined)\n FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object')\n throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h']) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b];\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\nexport function createKeygen(randomSecretKey, getPublicKey) {\n return function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n };\n}\n//# sourceMappingURL=curve.js.map","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils.js';\nimport { abool, abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, hexToBytes, isBytes, memoized, numberToHexUnpadded, validateObject, randomBytes as wcRandomBytes, } from \"../utils.js\";\nimport { createCurveFields, createKeygen, mulEndoUnsafe, negateCt, normalizeZ, wNAF, } from \"./curve.js\";\nimport { FpInvertBatch, getMinHashLength, mapHashToField, validateField, } from \"./modular.js\";\n// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)\nconst divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;\n/**\n * Splits scalar for GLV endomorphism.\n */\nexport function _splitEndoScalar(k, basis, n) {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg)\n k1 = -k1;\n if (k2neg)\n k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n}\nfunction validateSigFormat(format) {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format;\n}\nfunction validateSigOpts(opts, def) {\n const optsn = {};\n for (let optName of Object.keys(def)) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS, 'lowS');\n abool(optsn.prehash, 'prehash');\n if (optsn.format !== undefined)\n validateSigFormat(optsn.format);\n return optsn;\n}\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 0b1000_0000); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num) {\n const { Err: E } = DER;\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data) {\n const { Err: E } = DER;\n if (data[0] & 0b1000_0000)\n throw new E('invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(bytes) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = abytes(bytes, undefined, 'signature');\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * See {@link WeierstrassOpts}.\n *\n * @example\n```js\nconst opts = {\n p: 0xfffffffffffffffffffffffffffffffeffffac73n,\n n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,\n h: 1n,\n a: 0n,\n b: 7n,\n Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,\n Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,\n};\nconst secp160k1_Point = weierstrass(opts);\n```\n */\nexport function weierstrass(params, extraOpts = {}) {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(extraOpts, {}, {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n });\n const { endo } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n const lengths = getWLengths(Fp, Fn);\n function assertCompressionIsSupported() {\n if (!Fp.isOdd)\n throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n // Implements IEEE P1363 point encoding\n function pointToBytes(_c, point, isCompressed) {\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd(y);\n return concatBytes(pprefix(hasEvenY), bx);\n }\n else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x))\n throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const evenY = Fp.isOdd(y);\n const evenH = (head & 1) === 1; // ECDSA-specific\n if (evenH !== evenY)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y))\n throw new Error('bad point: is not on curve');\n return { x, y };\n }\n else {\n throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);\n }\n }\n const encodePoint = extraOpts.toBytes || pointToBytes;\n const decodePoint = extraOpts.fromBytes || pointFromBytes;\n function weierstrassEquation(x) {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b\n }\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y² == x³ + ax + b */\n function isValidXY(x, y) {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2)))\n throw new Error('bad curve params: a or b');\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title, n, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n)))\n throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n function aprjpoint(other) {\n if (!(other instanceof Point))\n throw new Error('Weierstrass Point expected');\n }\n function splitEndoScalarN(k) {\n if (!endo || !endo.basises)\n throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)\n const toAffineMemo = memoized((p, iz) => {\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE))\n return { x: X, y: Y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x, y };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is invalid representation of ZERO.\n if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\n }\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).\n * Default Point works in 2d / affine coordinates: (x, y).\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n // base / generator point\n static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n static Fp = Fp;\n // scalar field\n static Fn = Fn;\n X;\n Y;\n Z;\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X, Y, Z) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n static fromBytes(bytes) {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n static fromHex(hex) {\n return Point.fromBytes(hexToBytes(hex));\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n *\n * @param windowSize\n * @param isLazy true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy)\n this.multiply(_3n); // random number\n return this;\n }\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity() {\n assertValidMemo(this);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n /** Compare one point to another. */\n equals(other) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate() {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n const { endo } = extraOpts;\n if (!Fn.isValidNot0(scalar))\n throw new Error('invalid scalar: out of range'); // 0 is invalid\n let point, fake; // Fake point is used to const-time mult\n const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n }\n else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc) {\n const { endo } = extraOpts;\n const p = this;\n if (!Fn.isValid(sc))\n throw new Error('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0())\n return Point.ZERO; // 0\n if (sc === _1n)\n return p; // 1\n if (wnaf.hasCache(this))\n return this.multiply(sc); // precomputes\n // We don't have method for double scalar multiplication (aP + bQ):\n // Even with using Strauss-Shamir trick, it's 35% slower than naïve mul+add.\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n }\n else {\n return wnaf.unsafe(p, sc);\n }\n }\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ) {\n return toAffineMemo(this, invertedZ);\n }\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree() {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n)\n return true;\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n clearCofactor() {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(cofactor);\n }\n isSmallOrder() {\n // can we use this.clearCofactor()?\n return this.multiplyUnsafe(cofactor).is0();\n }\n toBytes(isCompressed = true) {\n abool(isCompressed, 'isCompressed');\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n return bytesToHex(this.toBytes(isCompressed));\n }\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY) {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n validateField(Fp);\n const { A, B, Z } = opts;\n if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, Z);\n if (!Fp.isOdd)\n throw new Error('Field does not have .isOdd()');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\nfunction getWLengths(Fp, Fn) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n signature: 2 * Fn.BYTES,\n };\n}\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n */\nexport function ecdh(Point, ecdhOpts = {}) {\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes || wcRandomBytes;\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });\n function isValidSecretKey(secretKey) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n }\n catch (error) {\n return false;\n }\n }\n function isValidPublicKey(publicKey, isCompressed) {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp)\n return false;\n if (isCompressed === false && l !== publicKeyUncompressed)\n return false;\n return !!Point.fromBytes(publicKey);\n }\n catch (error) {\n return false;\n }\n }\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed = randomBytes_(lengths.seed)) {\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n }\n /**\n * Computes public key for a secret key. Checks for validity of the secret key.\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(secretKey, isCompressed = true) {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n if (!isBytes(item))\n return undefined;\n if (('_lengths' in Fn && Fn._lengths) || secretKey === publicKey)\n return undefined;\n const l = abytes(item, undefined, 'key').length;\n return l === publicKey || l === publicKeyUncompressed;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {\n if (isProbPub(secretKeyA) === true)\n throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false)\n throw new Error('second arg must be public key');\n const s = Fn.fromBytes(secretKeyA);\n const b = Point.fromBytes(publicKeyB); // checks for being on-curve\n return b.multiply(s).toBytes(isCompressed);\n }\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n };\n const keygen = createKeygen(randomSecretKey, getPublicKey);\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n *\n * @param Point created using {@link weierstrass} function\n * @param hash used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)\n * @param ecdsaOpts rarely needed, see {@link ECDSAOpts}\n *\n * @example\n * ```js\n * const p256_Point = weierstrass(...);\n * const p256_sha256 = ecdsa(p256_Point, sha256);\n * const p256_sha224 = ecdsa(p256_Point, sha224);\n * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });\n * ```\n */\nexport function ecdsa(Point, hash, ecdsaOpts = {}) {\n ahash(hash);\n validateObject(ecdsaOpts, {}, {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n });\n ecdsaOpts = Object.assign({}, ecdsaOpts);\n const randomBytes = ecdsaOpts.randomBytes || wcRandomBytes;\n const hmac = ecdsaOpts.hmac || ((key, msg) => nobleHmac(hash, key, msg));\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts = {\n prehash: true,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : true,\n format: 'compact',\n extraEntropy: false,\n };\n const hasLargeCofactor = CURVE_ORDER * _2n < Fp.ORDER; // Won't CURVE().h > 2n be more effective?\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title, num) {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function assertSmallCofactor() {\n // ECDSA recovery is hard for cofactor > 1 curves.\n // In sign, `r = q.x mod n`, and here we recover q.x from r.\n // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.\n // However, for cofactor>1, r+n may not get q.x:\n // r+n*i would need to be done instead where i is unknown.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit non-prime-order signatures (recid > 1).\n if (hasLargeCofactor)\n throw new Error('\"recovered\" sig type is not supported for cofactor >2 curves');\n }\n function validateSigLength(bytes, format) {\n validateSigFormat(format);\n const size = lengths.signature;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer);\n }\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature {\n r;\n s;\n recovery;\n constructor(r, s, recovery) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null) {\n assertSmallCofactor();\n if (![0, 1, 2, 3].includes(recovery))\n throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n static fromBytes(bytes, format = defaultSigOpts.format) {\n validateSigLength(bytes, format);\n let recid;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = lengths.signature / 2;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n static fromHex(hex, format) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n assertRecovery() {\n const { recovery } = this;\n if (recovery == null)\n throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(messageHash) {\n const { r, s } = this;\n const recovery = this.assertRecovery();\n const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj))\n throw new Error('invalid recovery id: sig.r+curve.n != R.x');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0())\n throw new Error('invalid recovery: point at infinify');\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n toBytes(format = defaultSigOpts.format) {\n validateSigFormat(format);\n if (format === 'der')\n return hexToBytes(DER.hexFromSig(this));\n const { r, s } = this;\n const rb = Fn.toBytes(r);\n const sb = Fn.toBytes(s);\n if (format === 'recovered') {\n assertSmallCofactor();\n return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);\n }\n return concatBytes(rb, sb);\n }\n toHex(format) {\n return bytesToHex(this.toBytes(format));\n }\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = ecdsaOpts.bits2int ||\n function bits2int_def(bytes) {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192)\n throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = ecdsaOpts.bits2int_modN ||\n function bits2int_modN_def(bytes) {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // Pads output with zero as per spec\n const ORDER_MASK = bitMask(fnBits);\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num) {\n // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n function validateMsgAndHash(message, prehash) {\n abytes(message, undefined, 'message');\n return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;\n }\n /**\n * Steps A, D of RFC6979 3.2.\n * Creates RFC6979 seed; converts msg/privKey to numbers.\n * Used only in sign, not in verify.\n *\n * Warning: we cannot assume here that message has same amount of bytes as curve order,\n * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.\n */\n function prepSig(message, secretKey, opts) {\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(message);\n const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint\n if (!Fn.isValidNot0(d))\n throw new Error('invalid private key');\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n // To transform k => Signature:\n // q = k⋅G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!Fn.isValidNot0(k))\n return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3 when q.x>n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N\n recovery ^= 1;\n }\n return new Signature(r, normS, hasLargeCofactor ? undefined : recovery);\n }\n return { seed, k2sig };\n }\n /**\n * Signs message hash with a secret key.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message, secretKey, opts = {}) {\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig.toBytes(opts.format);\n }\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * u1 = hs^-1 mod n\n * u2 = rs^-1 mod n\n * R = u1⋅G + u2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, message, publicKey, opts = {}) {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature)) {\n const end = signature instanceof Signature ? ', use sig.toBytes()' : '';\n throw new Error('verify expects Uint8Array signature' + end);\n }\n validateSigLength(signature, format); // execute this twice because we want loud error\n try {\n const sig = Signature.fromBytes(signature, format);\n const P = Point.fromBytes(publicKey);\n if (lowS && sig.hasHighS())\n return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P\n if (R.is0())\n return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n }\n catch (e) {\n return false;\n }\n }\n function recoverPublicKey(signature, message, opts = {}) {\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash,\n });\n}\n//# sourceMappingURL=weierstrass.js.map","/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createKeygen } from \"./abstract/curve.js\";\nimport { createHasher, isogenyMap } from \"./abstract/hash-to-curve.js\";\nimport { Field, mapHashToField, pow2 } from \"./abstract/modular.js\";\nimport { ecdsa, mapToCurveSimpleSWU, weierstrass, } from \"./abstract/weierstrass.js\";\nimport { abytes, asciiToBytes, bytesToNumberBE, concatBytes } from \"./utils.js\";\n// Seems like generator was produced from some seed:\n// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\nconst secp256k1_ENDO = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _2n = /* @__PURE__ */ BigInt(2);\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1_CURVE.p;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });\nconst Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {\n Fp: Fpk1,\n endo: secp256k1_ENDO,\n});\n/**\n * secp256k1 curve: ECDSA and ECDH methods.\n *\n * Uses sha256 to hash messages. To use a different hash,\n * pass `{ prehash: false }` to sign / verify.\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * // const publicKey = secp256k1.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey);\n * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(asciiToBytes(tag));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toBytes(true).slice(1);\nconst hasEven = (y) => y % _2n === _0n;\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n const { Fn, BASE } = Pointk1;\n const d_ = Fn.fromBytes(priv);\n const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n return { scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n const Fp = Fpk1;\n if (!Fp.isValidNot0(x))\n throw new Error('invalid x: Fail if x ≥ p');\n const xx = Fp.create(x * x);\n const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y))\n y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(secretKey) {\n return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, secretKey, auxRand = randomBytes(32)) {\n const { Fn } = Pointk1;\n const m = abytes(message, undefined, 'message');\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array\n const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const { Fp, Fn, BASE } = Pointk1;\n const sig = abytes(signature, 64, 'signature');\n const m = abytes(message, undefined, 'message');\n const pub = abytes(publicKey, 32, 'publicKey');\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!Fp.isValidNot0(r))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!Fn.isValidNot0(s))\n return false;\n const e = challenge(Fn.toBytes(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n // R = s⋅G - e⋅P, where -eP == (n-e)P\n const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n if (R.is0() || !hasEven(y) || x !== r)\n return false;\n return true;\n }\n catch (error) {\n return false;\n }\n}\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed = randomBytes(seedLength)) => {\n return mapHashToField(seed, secp256k1_CURVE.n);\n };\n return {\n keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: {\n randomSecretKey,\n taggedHash,\n lift_x,\n pointToBytes,\n },\n lengths: {\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n },\n };\n})();\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n}))();\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(Pointk1, (scalars) => {\n const { x, y } = mapSWU(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\n//# sourceMappingURL=secp256k1.js.map","import { Buff } from '@vbyte/buff';\nimport { Assert } from './assert.js';\nimport { secp256k1, schnorr } from '@noble/curves/secp256k1.js';\nimport { Field } from '@noble/curves/abstract/modular.js';\nconst _0n = BigInt(0);\nconst _2n = BigInt(2);\nconst _N = secp256k1.Point.Fn.ORDER;\nconst FD = Field(_N, { isLE: true });\nconst GP = secp256k1.Point.BASE;\nexport function get_seckey(secret, even_y = false) {\n const sk = serialize_bytes(secret).big % _N;\n if (even_y) {\n const pt = GP.multiply(sk);\n return (pt.y % _2n === _0n)\n ? Buff.big(sk, 32)\n : Buff.big(_N - sk, 32);\n }\n else {\n return Buff.big(sk, 32);\n }\n}\nexport function get_pubkey(seckey, format) {\n const sk = serialize_bytes(seckey).big;\n const pt = GP.multiply(sk);\n const pk = pt.toHex(true);\n return serialize_pubkey(pk, format);\n}\nexport function tweak_seckey(seckey, tweak, even_y = false) {\n const sk = get_seckey(seckey, even_y).big;\n const twk = serialize_bytes(tweak).big;\n const tweaked_sk = FD.add(sk, twk);\n const new_secret = Buff.big(tweaked_sk, 32);\n return get_seckey(new_secret, false);\n}\nexport function tweak_pubkey(pubkey, tweak, format, even_y = false) {\n const twk_big = serialize_bytes(tweak).big;\n const pub_pt = lift_point(pubkey);\n const tweak_pt = GP.multiply(twk_big);\n let tweaked_pt = pub_pt.add(tweak_pt);\n if (even_y && tweaked_pt.y % _2n !== _0n) {\n tweaked_pt = tweaked_pt.negate();\n }\n const pk = tweaked_pt.toHex(true);\n return serialize_pubkey(pk, format);\n}\nexport function verify_seckey(seckey) {\n const sk = serialize_bytes(seckey);\n Assert.size(sk, 32, 'ecdsa secret keys must be 32 bytes long');\n Assert.ok(sk.big < _N, 'ecdsa secret keys must be less than the curve order');\n Assert.ok(sk.big > 0, 'ecdsa secret keys must be greater than zero');\n}\nexport function verify_pubkey(pubkey, format) {\n const pk = serialize_bytes(pubkey);\n if (format === 'bip340') {\n Assert.size(pk, 32, 'bip340 public keys must be 32 bytes long');\n }\n else if (format === 'ecdsa') {\n Assert.size(pk, 33, 'ecdsa public keys must be 33 bytes long');\n }\n else {\n throw new Error(`invalid format: ${format}`);\n }\n verify_point(pk);\n}\nexport function sign_ecdsa(seckey, message) {\n const msg = serialize_bytes(message);\n const sk = serialize_bytes(seckey);\n const sig = secp256k1.sign(msg, sk, { format: 'der', prehash: false });\n return Buff.bytes(sig);\n}\nexport function sign_bip340(seckey, message) {\n const msg = serialize_bytes(message);\n const sk = serialize_bytes(seckey);\n const sig = schnorr.sign(msg, sk);\n return Buff.bytes(sig);\n}\nexport function verify_ecdsa(signature, message, pubkey) {\n const sig = serialize_bytes(signature);\n const msg = serialize_bytes(message);\n const pk = serialize_pubkey(pubkey, 'ecdsa');\n return secp256k1.verify(sig, msg, pk, { format: 'der', prehash: false });\n}\nexport function verify_bip340(signature, message, pubkey) {\n const sig = serialize_bytes(signature);\n const msg = serialize_bytes(message);\n const pk = serialize_pubkey(pubkey, 'bip340');\n return schnorr.verify(sig, msg, pk);\n}\nexport function verify_point(pubkey) {\n try {\n const pt = lift_point(pubkey);\n pt.assertValidity();\n }\n catch {\n throw new Error(`invalid secp256k1 point: ${pubkey}`);\n }\n}\nexport function lift_point(pubkey) {\n try {\n const pk = serialize_pubkey(pubkey, 'ecdsa');\n return secp256k1.Point.fromHex(pk.hex);\n }\n catch {\n throw new Error(`invalid pubkey: ${pubkey}`);\n }\n}\nexport function serialize_pubkey(pubkey, format) {\n try {\n const pk = serialize_bytes(pubkey);\n if (pk.length === 33 && format === 'bip340') {\n return pk.slice(1);\n }\n else if (pk.length === 32 && format === 'ecdsa') {\n const prefix = Buff.num(0x02, 1);\n return Buff.join([prefix, pk]);\n }\n else {\n return pk;\n }\n }\n catch {\n throw new Error(`invalid pubkey: ${String(pubkey)}`);\n }\n}\nexport function get_pubkey_format(pubkey) {\n const pk = serialize_bytes(pubkey);\n if (pk.length === 33)\n return 'ecdsa';\n if (pk.length === 32)\n return 'bip340';\n throw new Error(`invalid pubkey: ${String(pubkey)}`);\n}\nexport function serialize_bytes(bytes) {\n if (bytes instanceof Uint8Array) {\n return Buff.bytes(bytes);\n }\n if (typeof bytes === 'string') {\n if (bytes.length > 0 && bytes.length % 2 === 0 && /^[0-9a-fA-F]+$/.test(bytes)) {\n return Buff.hex(bytes);\n }\n throw new Error(`invalid hex string: ${bytes}`);\n }\n throw new Error(`invalid bytes: ${String(bytes)}`);\n}\n","/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nfunction isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n}\nfunction isArrayOf(isString, arr) {\n if (!Array.isArray(arr))\n return false;\n if (arr.length === 0)\n return true;\n if (isString) {\n return arr.every((item) => typeof item === 'string');\n }\n else {\n return arr.every((item) => Number.isSafeInteger(item));\n }\n}\nfunction afn(input) {\n if (typeof input !== 'function')\n throw new Error('function expected');\n return true;\n}\nfunction astr(label, input) {\n if (typeof input !== 'string')\n throw new Error(`${label}: string expected`);\n return true;\n}\nfunction anumber(n) {\n if (!Number.isSafeInteger(n))\n throw new Error(`invalid integer: ${n}`);\n}\nfunction aArr(input) {\n if (!Array.isArray(input))\n throw new Error('array expected');\n}\nfunction astrArr(label, input) {\n if (!isArrayOf(true, input))\n throw new Error(`${label}: array of strings expected`);\n}\nfunction anumArr(label, input) {\n if (!isArrayOf(false, input))\n throw new Error(`${label}: array of numbers expected`);\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction chain(...args) {\n const id = (a) => a;\n // Wrap call in closure so JIT can inline calls\n const wrap = (a, b) => (c) => a(b(c));\n // Construct chain of args[-1].encode(args[-2].encode([...]))\n const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n // Construct chain of args[0].decode(args[1].decode(...))\n const decode = args.map((x) => x.decode).reduce(wrap, id);\n return { encode, decode };\n}\n/**\n * Encodes integer radix representation to array of strings using alphabet and back.\n * Could also be array of strings.\n * @__NO_SIDE_EFFECTS__\n */\nfunction alphabet(letters) {\n // mapping 1 to \"b\"\n const lettersA = typeof letters === 'string' ? letters.split('') : letters;\n const len = lettersA.length;\n astrArr('alphabet', lettersA);\n // mapping \"b\" to 1\n const indexes = new Map(lettersA.map((l, i) => [l, i]));\n return {\n encode: (digits) => {\n aArr(digits);\n return digits.map((i) => {\n if (!Number.isSafeInteger(i) || i < 0 || i >= len)\n throw new Error(`alphabet.encode: digit index outside alphabet \"${i}\". Allowed: ${letters}`);\n return lettersA[i];\n });\n },\n decode: (input) => {\n aArr(input);\n return input.map((letter) => {\n astr('alphabet.decode', letter);\n const i = indexes.get(letter);\n if (i === undefined)\n throw new Error(`Unknown letter: \"${letter}\". Allowed: ${letters}`);\n return i;\n });\n },\n };\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction join(separator = '') {\n astr('join', separator);\n return {\n encode: (from) => {\n astrArr('join.decode', from);\n return from.join(separator);\n },\n decode: (to) => {\n astr('join.decode', to);\n return to.split(separator);\n },\n };\n}\n/**\n * Pad strings array so it has integer number of bits\n * @__NO_SIDE_EFFECTS__\n */\nfunction padding(bits, chr = '=') {\n anumber(bits);\n astr('padding', chr);\n return {\n encode(data) {\n astrArr('padding.encode', data);\n while ((data.length * bits) % 8)\n data.push(chr);\n return data;\n },\n decode(input) {\n astrArr('padding.decode', input);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('padding: invalid, string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n const last = end - 1;\n const byte = last * bits;\n if (byte % 8 === 0)\n throw new Error('padding: invalid, string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction normalize(fn) {\n afn(fn);\n return { encode: (from) => from, decode: (to) => fn(to) };\n}\n/**\n * Slow: O(n^2) time complexity\n */\nfunction convertRadix(data, from, to) {\n // base 1 is impossible\n if (from < 2)\n throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);\n if (to < 2)\n throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);\n aArr(data);\n if (!data.length)\n return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data, (d) => {\n anumber(d);\n if (d < 0 || d >= from)\n throw new Error(`invalid integer: ${d}`);\n return d;\n });\n const dlen = digits.length;\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < dlen; i++) {\n const digit = digits[i];\n const fromCarry = from * carry;\n const digitBase = fromCarry + digit;\n if (!Number.isSafeInteger(digitBase) ||\n fromCarry / from !== carry ||\n digitBase - digit !== fromCarry) {\n throw new Error('convertRadix: carry overflow');\n }\n const div = digitBase / to;\n carry = digitBase % to;\n const rounded = Math.floor(div);\n digits[i] = rounded;\n if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done)\n continue;\n else if (!rounded)\n pos = i;\n else\n done = false;\n }\n res.push(carry);\n if (done)\n break;\n }\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++)\n res.push(0);\n return res.reverse();\n}\nconst gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));\nconst radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to));\nconst powers = /* @__PURE__ */ (() => {\n let res = [];\n for (let i = 0; i < 40; i++)\n res.push(2 ** i);\n return res;\n})();\n/**\n * Implemented with numbers, because BigInt is 5x slower\n */\nfunction convertRadix2(data, from, to, padding) {\n aArr(data);\n if (from <= 0 || from > 32)\n throw new Error(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32)\n throw new Error(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);\n }\n let carry = 0;\n let pos = 0; // bitwise position in current element\n const max = powers[from];\n const mask = powers[to] - 1;\n const res = [];\n for (const n of data) {\n anumber(n);\n if (n >= max)\n throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32)\n throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to)\n res.push(((carry >> (pos - to)) & mask) >>> 0);\n const pow = powers[pos];\n if (pow === undefined)\n throw new Error('invalid carry');\n carry &= pow - 1; // clean carry, otherwise it will cause overflow\n }\n carry = (carry << (to - pos)) & mask;\n if (!padding && pos >= from)\n throw new Error('Excess padding');\n if (!padding && carry > 0)\n throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0)\n res.push(carry >>> 0);\n return res;\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix(num) {\n anumber(num);\n const _256 = 2 ** 8;\n return {\n encode: (bytes) => {\n if (!isBytes(bytes))\n throw new Error('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), _256, num);\n },\n decode: (digits) => {\n anumArr('radix.decode', digits);\n return Uint8Array.from(convertRadix(digits, num, _256));\n },\n };\n}\n/**\n * If both bases are power of same number (like `2**8 <-> 2**64`),\n * there is a linear algorithm. For now we have implementation for power-of-two bases only.\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix2(bits, revPadding = false) {\n anumber(bits);\n if (bits <= 0 || bits > 32)\n throw new Error('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new Error('radix2: carry overflow');\n return {\n encode: (bytes) => {\n if (!isBytes(bytes))\n throw new Error('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits) => {\n anumArr('radix2.decode', digits);\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\nfunction unsafeWrapper(fn) {\n afn(fn);\n return function (...args) {\n try {\n return fn.apply(null, args);\n }\n catch (e) { }\n };\n}\nfunction checksum(len, fn) {\n anumber(len);\n afn(fn);\n return {\n encode(data) {\n if (!isBytes(data))\n throw new Error('checksum.encode: input should be Uint8Array');\n const sum = fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(sum, data.length);\n return res;\n },\n decode(data) {\n if (!isBytes(data))\n throw new Error('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const oldChecksum = data.slice(-len);\n const newChecksum = fn(payload).slice(0, len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i])\n throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\n// prettier-ignore\nexport const utils = {\n alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,\n};\n// RFC 4648 aka RFC 3548\n// ---------------------\n/**\n * base16 encoding from RFC 4648.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\n/**\n * base32 encoding from RFC 4648. Has padding.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''));\n/**\n * base32 encoding from RFC 4648. No padding.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), join(''));\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''));\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), join(''));\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * https://www.crockford.com/base32.html\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')));\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// prettier-ignore\nconst hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === 'function' &&\n typeof Uint8Array.fromBase64 === 'function')();\nconst decodeBase64Builtin = (s, isUrl) => {\n astr('base64', s);\n const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;\n const alphabet = isUrl ? 'base64url' : 'base64';\n if (s.length > 0 && !re.test(s))\n throw new Error('invalid base64');\n return Uint8Array.fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n/**\n * base64 from RFC 4648. Padded.\n * Use `base64nopad` for unpadded version.\n * Also check out `base64url`, `base64urlnopad`.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64 = hasBase64Builtin ? {\n encode(b) { abytes(b); return b.toBase64(); },\n decode(s) { return decodeBase64Builtin(s, false); },\n} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join(''));\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), join(''));\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url = hasBase64Builtin ? {\n encode(b) { abytes(b); return b.toBase64({ alphabet: 'base64url' }); },\n decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join(''));\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), join(''));\n// base58 code\n// -----------\nconst genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => chain(radix(58), alphabet(abc), join(''));\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * base58.decode('01abcdef');\n * // => '3UhJW'\n * ```\n */\nexport const base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');\n/**\n * base58: flickr version. Check out `base58`.\n */\nexport const base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ');\n/**\n * base58: XRP version. Check out `base58`.\n */\nexport const base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz');\n// Data len (index) -> encoded block len\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n */\nexport const base58xmr = {\n encode(data) {\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');\n }\n return res;\n },\n decode(str) {\n let res = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0)\n throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n};\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n */\nexport const createBase58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), base58);\n/**\n * Use `createBase58check` instead.\n * @deprecated\n */\nexport const base58check = createBase58check;\nconst BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre) {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1)\n chk ^= POLYMOD_GENERATORS[i];\n }\n return chk;\n}\nfunction bechChecksum(prefix, words, encodingConst = 1) {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126)\n throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++)\n chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words)\n chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++)\n chk = bech32Polymod(chk);\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]], 30, 5, false));\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction genBech32(encoding) {\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n function encode(prefix, words, limit = 90) {\n astr('bech32.encode prefix', prefix);\n if (isBytes(words))\n words = Array.from(words);\n anumArr('bech32.encode', words);\n const plen = prefix.length;\n if (plen === 0)\n throw new TypeError(`Invalid prefix length ${plen}`);\n const actualLength = plen + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n const lowered = prefix.toLowerCase();\n const sum = bechChecksum(lowered, words, ENCODING_CONST);\n return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`;\n }\n function decode(str, limit = 90) {\n astr('bech32.decode input', str);\n const slen = str.length;\n if (slen < 8 || (limit !== false && slen > limit))\n throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);\n // don't allow mixed case\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n const sepIndex = lowered.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = lowered.slice(0, sepIndex);\n const data = lowered.slice(sepIndex + 1);\n if (data.length < 6)\n throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(data).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!data.endsWith(sum))\n throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n const decodeUnsafe = unsafeWrapper(decode);\n function decodeToBytes(str) {\n const { prefix, words } = decode(str, false);\n return { prefix, words, bytes: fromWords(words) };\n }\n function encodeFromBytes(prefix, bytes) {\n return encode(prefix, toWords(bytes));\n }\n return {\n encode,\n decode,\n encodeFromBytes,\n decodeToBytes,\n decodeUnsafe,\n fromWords,\n fromWordsUnsafe,\n toWords,\n };\n}\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32 = genBech32('bech32');\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32m = genBech32('bech32m');\n/**\n * UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8 = {\n encode: (data) => new TextDecoder().decode(data),\n decode: (str) => new TextEncoder().encode(str),\n};\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === 'function' &&\n typeof Uint8Array.fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin = {\n encode(data) { abytes(data); return data.toHex(); },\n decode(s) { astr('hex', s); return Uint8Array.fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex = hasHexBuiltin\n ? hexBuiltin\n : chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => {\n if (typeof s !== 'string' || s.length % 2 !== 0)\n throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);\n return s.toLowerCase();\n }));\n// prettier-ignore\nconst CODERS = {\n utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\nconst coderTypeError = 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';\n/** @deprecated */\nexport const bytesToString = (type, bytes) => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))\n throw new TypeError(coderTypeError);\n if (!isBytes(bytes))\n throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\n/** @deprecated */\nexport const str = bytesToString; // as in python, but for bytes only\n/** @deprecated */\nexport const stringToBytes = (type, str) => {\n if (!CODERS.hasOwnProperty(type))\n throw new TypeError(coderTypeError);\n if (typeof str !== 'string')\n throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str);\n};\n/** @deprecated */\nexport const bytes = stringToBytes;\n//# sourceMappingURL=index.js.map","import { sha256 } from '@noble/hashes/sha2.js';\nimport { Assert } from './assert.js';\nimport { createBase58check, base64, base64urlnopad, bech32, bech32m } from '@scure/base';\nexport var B58chk;\n(function (B58chk) {\n B58chk.encode = (data) => {\n Assert.is_u8a(data);\n return createBase58check(sha256).encode(data);\n };\n B58chk.decode = (data) => {\n Assert.is_base58(data);\n return createBase58check(sha256).decode(data);\n };\n})(B58chk || (B58chk = {}));\nexport var Base64;\n(function (Base64) {\n Base64.encode = (data) => {\n Assert.is_u8a(data);\n return base64.encode(data);\n };\n Base64.decode = (data) => {\n Assert.is_base64(data);\n return base64.decode(data);\n };\n})(Base64 || (Base64 = {}));\nexport var B64url;\n(function (B64url) {\n B64url.encode = (data) => {\n Assert.is_u8a(data);\n return base64urlnopad.encode(data);\n };\n B64url.decode = (data) => {\n Assert.is_b64url(data);\n return base64urlnopad.decode(data);\n };\n})(B64url || (B64url = {}));\nexport var Bech32;\n(function (Bech32) {\n Bech32.to_words = bech32.toWords;\n Bech32.to_bytes = bech32.fromWords;\n Bech32.encode = (prefix, words, limit = false) => {\n assert_prefix(prefix);\n assert_words(words);\n return bech32.encode(prefix, words, limit);\n };\n Bech32.decode = (data, limit = false) => {\n Assert.is_bech32(data);\n return bech32.decode(data, limit);\n };\n})(Bech32 || (Bech32 = {}));\nexport var Bech32m;\n(function (Bech32m) {\n Bech32m.to_words = bech32m.toWords;\n Bech32m.to_bytes = bech32m.fromWords;\n Bech32m.encode = (prefix, words, limit = false) => {\n assert_prefix(prefix);\n assert_words(words);\n return bech32m.encode(prefix, words, limit);\n };\n Bech32m.decode = (data, limit = false) => {\n Assert.is_bech32(data);\n return bech32m.decode(data, limit);\n };\n})(Bech32m || (Bech32m = {}));\nfunction assert_prefix(value) {\n if (typeof value !== 'string' || value.length === 0) {\n throw new Error(`invalid prefix: ${String(value)}`);\n }\n}\nfunction assert_words(value) {\n if (!(Array.isArray(value) &&\n value.every(word => typeof word === 'number'))) {\n throw new Error(`invalid words: ${String(value)}`);\n }\n}\n","import { Buff } from \"@vbyte/buff\";\n\nimport { Assert } from \"@vbyte/util\";\nimport { B58chk, Bech32, Bech32m } from \"@vbyte/crypto\";\n\nimport { ValidationError } from \"@/error.js\";\nimport type { AddressFormat, EncoderConfig } from \"@/types/address.js\";\n\nconst ENCODING_REGEX = {\n\tbase58: /^[13mn2][a-km-zA-HJ-NP-Z1-9]{25,34}$/,\n\tbech32: /^(bc|tb|bcrt)1q[ac-hj-np-z02-9]{6,87}$/,\n\tbech32m: /^(bc|tb|bcrt)1p[ac-hj-np-z02-9]{6,87}$/,\n};\n\nconst VERSION = {\n\tbech32: 0,\n\tbech32m: 1,\n};\n\n/**\n * Decode an address.\n *\n * @param address - The address to decode.\n * @returns The decoded address.\n */\nexport function decode_address(address: string): EncoderConfig {\n\t// Get the address format.\n\tconst format = get_address_format(address);\n\t// If the format is not found, throw an error.\n\tif (format === null)\n\t\tthrow new ValidationError(`unrecognized address format: ${address}`, \"address\");\n\t// Decode the address based on the format.\n\tif (format === \"base58\") return base58_decode(address);\n\tif (format === \"bech32\") return bech32_decode(address);\n\tif (format === \"bech32m\") return bech32m_decode(address);\n\t// If we didn't find a matching decoder, throw.\n\tthrow new ValidationError(\"unable to find a matching address configuration\", \"address\");\n}\n\n/**\n * Encode an address.\n *\n * @param address - The address to encode.\n * @returns The encoded address as a string, or null if the address is not\n * recognized.\n */\nexport function encode_address(config: EncoderConfig): string {\n\t// Encode the address based on the format.\n\tif (config.format === \"base58\") return base58_encode(config);\n\tif (config.format === \"bech32\") return bech32_encode(config);\n\tif (config.format === \"bech32m\") return bech32m_encode(config);\n\t// If the format is not recognized, throw an error.\n\tthrow new ValidationError(`unrecognized encoding format: ${config.format}`, \"format\");\n}\n\n/**\n * Get the encoding type for a given address.\n *\n * @param address - The address to get the encoding type for.\n * @returns The encoding type, or null if the address is not recognized.\n */\nfunction get_address_format(address: string): AddressFormat | null {\n\t// For each encoding type, check if the address matches the regex.\n\tfor (const [format, regex] of Object.entries(ENCODING_REGEX)) {\n\t\t// If the address matches the regex, return the format.\n\t\tif (regex.test(address)) return format as AddressFormat;\n\t\t// If the address does not match the regex, continue to the next encoding type.\n\t}\n\t// If no encoding type matches the address, return null.\n\treturn null;\n}\n\n/**\n * Encode data as a base58 string.\n *\n * @param config - The encoder configuration.\n * @returns The encoded base58 string.\n */\nfunction base58_encode(config: EncoderConfig): string {\n\t// Assert the format is correct.\n\tAssert.ok(config.format === \"base58\", \"encoding mismatch\");\n\t// Assert the version is specified.\n\tAssert.exists(config.version, \"must specify a version\");\n\t// Convert the data into bytes with a version prefix.\n\tconst bytes = Buff.join([config.version, config.data]);\n\t// Encode the data as a base58 string.\n\treturn B58chk.encode(bytes);\n}\n\n/**\n * Decode data as a base58 string.\n *\n * @param encoded - The base58 string to decode.\n * @returns The decoded data.\n */\nfunction base58_decode(encoded: string): EncoderConfig {\n\t// Decode the encoded data.\n\tconst bytes = B58chk.decode(encoded);\n\t// Get the data from the decoded bytes.\n\tconst data = bytes.slice(1);\n\t// Get the version from the decoded bytes.\n\tconst version = bytes[0];\n\t// Return the decoded address.\n\treturn { data, format: \"base58\", version };\n}\n\n/**\n * Encode data as a bech32 string.\n *\n * @param config - The encoder configuration.\n * @returns The encoded bech32 string.\n */\nfunction bech32_encode(config: EncoderConfig): string {\n\t// Assert the format is correct.\n\tAssert.ok(config.format === \"bech32\", \"encoding mismatch\");\n\t// Assert the prefix is specified.\n\tAssert.exists(config.prefix, \"prefix is required\");\n\t// Convert the data into bytes.\n\tconst bytes = Buff.bytes(config.data);\n\t// Convert the bytes into words.\n\tconst words = Bech32.to_words(bytes);\n\t// Encode the data as a bech32 string.\n\treturn Bech32.encode(config.prefix, [VERSION.bech32, ...words]);\n}\n\n/**\n * Decode data as a bech32 string.\n *\n * @param encoded - The bech32 string to decode.\n * @returns The decoded data.\n */\nfunction bech32_decode(encoded: string): EncoderConfig {\n\t// Decode the encoded data.\n\tconst { prefix, words } = Bech32.decode(encoded);\n\t// Get the version and rest of the words.\n\tconst [version, ...rest] = words;\n\t// Assert the version is correct.\n\tAssert.ok(version === VERSION.bech32, \"bech32 version mismatch\");\n\t// Convert the rest of the words into bytes.\n\tconst data = Bech32.to_bytes(rest);\n\t// Return the decoded address.\n\treturn { data, format: \"bech32\", prefix, version };\n}\n\n/**\n * Encode data as a bech32 string.\n *\n * @param config - The encoder configuration.\n * @returns The encoded bech32 string.\n */\nfunction bech32m_encode(config: EncoderConfig): string {\n\t// Assert the format is correct.\n\tAssert.ok(config.format === \"bech32m\", \"encoding mismatch\");\n\t// Assert the prefix is specified.\n\tAssert.exists(config.prefix, \"prefix is required\");\n\t// Convert the data into bytes.\n\tconst bytes = Buff.bytes(config.data);\n\t// Convert the bytes into words.\n\tconst words = Bech32m.to_words(bytes);\n\t// Encode the data as a bech32m string.\n\treturn Bech32m.encode(config.prefix, [VERSION.bech32m, ...words]);\n}\n\n/**\n * Decode data as a bech32 string.\n *\n * @param encoded - The bech32 string to decode.\n * @returns The decoded data.\n */\nfunction bech32m_decode(encoded: string): EncoderConfig {\n\t// Decode the encoded data.\n\tconst { prefix, words } = Bech32m.decode(encoded);\n\t// Get the version and rest of the words.\n\tconst [version, ...rest] = words;\n\t// Assert the version is correct.\n\tAssert.ok(version === VERSION.bech32m, \"bech32m version mismatch\");\n\t// Convert the rest of the words into bytes.\n\tconst data = Bech32m.to_bytes(rest);\n\t// Return the decoded address.\n\treturn { data, format: \"bech32m\", prefix, version };\n}\n","import type { AddressType, ScriptInfo } from \"@/types/index.js\";\n\n/**\n * Get the address script.\n *\n * @param script_key - The script key.\n * @param script_type - The script type.\n * @returns The address script.\n */\nexport function get_address_script(\n\tscript_key: string,\n\tscript_type: AddressType,\n): ScriptInfo {\n\tswitch (script_type) {\n\t\tcase \"p2pkh\":\n\t\t\treturn get_p2pkh_script(script_key);\n\t\tcase \"p2sh\":\n\t\t\treturn get_p2sh_script(script_key);\n\t\tcase \"p2wpkh\":\n\t\t\treturn get_p2w_pkh_script(script_key);\n\t\tcase \"p2wsh\":\n\t\t\treturn get_p2w_sh_script(script_key);\n\t\tcase \"p2tr\":\n\t\t\treturn get_p2tr_script(script_key);\n\t\tdefault:\n\t\t\tthrow new Error(`unrecognized script type: ${script_type}`);\n\t}\n}\n\nfunction get_p2pkh_script(script_key: string) {\n\treturn {\n\t\thex: `76a914${script_key}88ac`,\n\t\tasm: [\"OP_DUP\", \"OP_HASH160\", script_key, \"OP_EQUALVERIFY\", \"OP_CHECKSIG\"],\n\t};\n}\n\nfunction get_p2sh_script(script_key: string) {\n\treturn {\n\t\thex: `a914${script_key}87`,\n\t\tasm: [\"OP_HASH160\", script_key, \"OP_EQUAL\"],\n\t};\n}\n\nfunction get_p2w_pkh_script(script_key: string) {\n\treturn {\n\t\thex: `0014${script_key}`,\n\t\tasm: [\"OP_0\", script_key],\n\t};\n}\n\nfunction get_p2w_sh_script(script_key: string) {\n\treturn {\n\t\thex: `0020${script_key}`,\n\t\tasm: [\"OP_0\", script_key],\n\t};\n}\n\nfunction get_p2tr_script(script_key: string) {\n\treturn {\n\t\thex: `5120${script_key}`,\n\t\tasm: [\"OP_1\", script_key],\n\t};\n}\n","import { Buff } from \"@vbyte/buff\";\nimport { ConfigError } from \"@/error.js\";\nimport type {\n\tAddressConfig,\n\tAddressConfigEntry,\n\tAddressInfo,\n\tChainNetwork,\n\tLockScriptType,\n} from \"@/types/index.js\";\nimport { decode_address } from \"./encode.js\";\nimport { get_address_script } from \"./script.js\";\n\nconst CONFIG_TABLE: AddressConfigEntry[] = [\n\t[\"1\", \"p2pkh\", \"main\", 20, \"base58\", 0x00],\n\t[\"3\", \"p2sh\", \"main\", 20, \"base58\", 0x05],\n\t[\"m\", \"p2pkh\", \"testnet\", 20, \"base58\", 0x6f],\n\t[\"n\", \"p2pkh\", \"testnet\", 20, \"base58\", 0x6f],\n\t[\"2\", \"p2sh\", \"testnet\", 20, \"base58\", 0xc4],\n\t[\"m\", \"p2pkh\", \"regtest\", 20, \"base58\", 0x6f],\n\t[\"n\", \"p2pkh\", \"regtest\", 20, \"base58\", 0x6f],\n\t[\"2\", \"p2sh\", \"regtest\", 20, \"base58\", 0xc4],\n\t[\"bc\", \"p2wpkh\", \"main\", 20, \"bech32\", 0],\n\t[\"tb\", \"p2wpkh\", \"testnet\", 20, \"bech32\", 0],\n\t[\"bcrt\", \"p2wpkh\", \"regtest\", 20, \"bech32\", 0],\n\t[\"bc\", \"p2wsh\", \"main\", 32, \"bech32\", 0],\n\t[\"tb\", \"p2wsh\", \"testnet\", 32, \"bech32\", 0],\n\t[\"bcrt\", \"p2wsh\", \"regtest\", 32, \"bech32\", 0],\n\t[\"bc\", \"p2tr\", \"main\", 32, \"bech32m\", 1],\n\t[\"tb\", \"p2tr\", \"testnet\", 32, \"bech32m\", 1],\n\t[\"bcrt\", \"p2tr\", \"regtest\", 32, \"bech32m\", 1],\n];\n\n/**\n * Lookup an address configuration by its type and network.\n *\n * @param address_network - The network of the address.\n * @param address_type - The type of the address.\n * @returns The address information, or null if the address is not recognized.\n */\nexport function get_address_config(\n\taddress_network: ChainNetwork,\n\taddress_type: LockScriptType,\n): AddressConfig | null {\n\t// For each configuration in the table,\n\tfor (const [prefix, type, network, size, format, version] of CONFIG_TABLE) {\n\t\t// Check if the address matches the configuration\n\t\tif (type === address_type && network === address_network) {\n\t\t\t// Return the address configuration.\n\t\t\treturn { type, prefix, network, size, format, version };\n\t\t}\n\t}\n\t// If no configuration matches the address, return null.\n\treturn null;\n}\n\n/**\n * Parse an address into its data and script.\n *\n * @param address - The address to parse.\n * @returns The address data and script.\n */\nexport function get_address_info(address: string): AddressInfo {\n\t// Decode the address.\n\tconst dec = decode_address(address);\n\t// For each configuration in the table,\n\tfor (const [prefix, type, network, size, format, version] of CONFIG_TABLE) {\n\t\t// Check if the address matches the configuration\n\t\tif (format !== dec.format) continue;\n\t\tif (size !== dec.data.length) continue;\n\t\tif (version !== dec.version) continue;\n\n\t\tif (dec.prefix) {\n\t\t\tif (prefix !== dec.prefix) continue;\n\t\t} else {\n\t\t\tif (!address.startsWith(prefix)) continue;\n\t\t}\n\n\t\t// Convert the decoded data into a hex string.\n\t\tconst data = Buff.bytes(dec.data).hex;\n\t\tconst script = get_address_script(data, type);\n\t\t// Return the address configuration and data.\n\t\treturn { data, script, type, prefix, network, size, format, version };\n\t}\n\t// Otherwise, throw an error with context about what was decoded\n\tthrow new ConfigError(\n\t\t`unrecognized address configuration: format=${dec.format}, size=${dec.data.length}, version=${dec.version}. ` +\n\t\t`Supported formats: base58 (p2pkh, p2sh), bech32 (p2wpkh, p2wsh), bech32m (p2tr)`\n\t);\n}\n","/**\n * P2PKH (Pay-to-Public-Key-Hash) address utilities.\n *\n * P2PKH is the original Bitcoin address format (addresses starting with \"1\").\n * Uses RIPEMD160(SHA256(pubkey)) as the locking condition.\n *\n * @module\n */\n\nimport { Buff, type Bytes } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/util\";\nimport { hash160 } from \"@vbyte/crypto/hash\";\nimport { LOCK_SCRIPT_TYPE } from \"@/const.js\";\nimport { is_p2pkh_script } from \"@/lib/script/lock.js\";\nimport type { AddressInfo, ChainNetwork } from \"@/types/index.js\";\nimport { encode_address } from \"./encode.js\";\nimport { get_address_config, get_address_info } from \"./util.js\";\n\nconst ADDRESS_TYPE = LOCK_SCRIPT_TYPE.P2PKH;\n\n/**\n * P2PKH address namespace.\n *\n * @example\n * ```typescript\n * // Create address from public key\n * const address = P2PKH.create_address(pubkey, 'main')\n *\n * // Decode address to get script info\n * const info = P2PKH.decode_address('1BvBMSE...')\n * ```\n */\nexport namespace P2PKH {\n\texport const create_address = create_p2pkh_address;\n\texport const create_script = create_p2pkh_script;\n\texport const encode_address = encode_p2pkh_address;\n\texport const encode_script = encode_p2pkh_script;\n\texport const decode_address = decode_p2pkh_address;\n\texport const decode_script = decode_p2pkh_script;\n}\n\nfunction create_p2pkh_address(\n\tpubkey: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Create the p2pkh script.\n\tconst script = create_p2pkh_script(pubkey);\n\t// Encode the script as an address.\n\treturn encode_p2pkh_address(script, network);\n}\n\nfunction create_p2pkh_script(pubkey: Bytes): Buff {\n\t// Convert the public key into bytes.\n\tconst bytes = Buff.bytes(pubkey);\n\t// Assert the public key is 33 bytes.\n\tAssert.ok(bytes.length === 33, \"invalid pubkey size\");\n\t// Convert the bytes into a hash.\n\tconst hash = hash160(bytes);\n\t// Return the script.\n\treturn encode_p2pkh_script(hash);\n}\n\nfunction encode_p2pkh_script(pk_hash: Bytes): Buff {\n\treturn Buff.join([\"76a914\", pk_hash, \"88ac\"]);\n}\n\nfunction encode_p2pkh_address(\n\tscript: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Get the public key hash from the script.\n\tconst pk_hash = decode_p2pkh_script(script);\n\t// Get the address configuration.\n\tconst config = get_address_config(network, ADDRESS_TYPE);\n\t// Assert the configuration exists.\n\tAssert.exists(\n\t\tconfig,\n\t\t`unrecognized address config: ${ADDRESS_TYPE} on ${network}`,\n\t);\n\t// Assert the payload size is correct.\n\tAssert.ok(\n\t\tpk_hash.length === config.size,\n\t\t`invalid payload size: ${pk_hash.length} !== ${config.size}`,\n\t);\n\t// Encode the address.\n\treturn encode_address({\n\t\tdata: pk_hash,\n\t\tformat: \"base58\",\n\t\tversion: config.version,\n\t});\n}\n\nfunction decode_p2pkh_address(address: string): AddressInfo {\n\t// Parse the address.\n\tconst parsed = get_address_info(address);\n\t// Assert the address type is correct.\n\tAssert.ok(\n\t\tparsed.type === \"p2pkh\",\n\t\t`address type mismatch: ${parsed.type} !== ${ADDRESS_TYPE}`,\n\t);\n\t// Return the parsed address.\n\treturn parsed;\n}\n\nfunction decode_p2pkh_script(script: Bytes): Buff {\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Assert the script is a p2pkh script.\n\tAssert.ok(is_p2pkh_script(script), `invalid p2pkh script`);\n\t// Return the public key hash from the script.\n\treturn bytes.slice(3, 23);\n}\n","/**\n * P2SH (Pay-to-Script-Hash) address utilities.\n *\n * P2SH addresses (starting with \"3\") can lock funds to any script.\n * Commonly used for multisig and wrapped SegWit (P2SH-P2WPKH).\n *\n * @module\n */\n\nimport { Buff, type Bytes } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/util\";\nimport { hash160 } from \"@vbyte/crypto/hash\";\nimport { LOCK_SCRIPT_TYPE } from \"@/const.js\";\nimport { is_p2sh_script } from \"@/lib/script/lock.js\";\nimport type { AddressInfo, ChainNetwork } from \"@/types/index.js\";\nimport { encode_address } from \"./encode.js\";\nimport { get_address_config, get_address_info } from \"./util.js\";\n\nconst ADDRESS_TYPE = LOCK_SCRIPT_TYPE.P2SH;\n\n/**\n * P2SH address namespace.\n *\n * @example\n * ```typescript\n * // Create address from redeem script\n * const address = P2SH.create_address(redeemScript, 'main')\n * // Returns: 3...\n *\n * // Decode address to get script info\n * const info = P2SH.decode_address('3...')\n * ```\n */\nexport namespace P2SH {\n\texport const create_address = create_p2sh_address;\n\texport const create_script = create_p2sh_script;\n\texport const encode_address = encode_p2sh_address;\n\texport const encode_script = encode_p2sh_script;\n\texport const decode_address = decode_p2sh_address;\n\texport const decode_script = decode_p2sh_script;\n}\n\nfunction create_p2sh_address(\n\tscript: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Convert the bytes into a hash.\n\tconst hash = hash160(bytes);\n\t// Create the p2sh script.\n\tconst p2sh_script = encode_p2sh_script(hash);\n\t// Encode the address.\n\treturn encode_p2sh_address(p2sh_script, network);\n}\n\nfunction create_p2sh_script(script: Bytes): Buff {\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Convert the bytes into a hash.\n\tconst hash = hash160(bytes);\n\t// Return the script.\n\treturn encode_p2sh_script(hash);\n}\n\nfunction encode_p2sh_script(script_hash: Bytes): Buff {\n\treturn Buff.join([\"a914\", script_hash, \"87\"]);\n}\n\nfunction encode_p2sh_address(\n\tscript_pk: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Get the script hash from the script.\n\tconst script_hash = decode_p2sh_script(script_pk);\n\t// Get the address configuration.\n\tconst config = get_address_config(network, ADDRESS_TYPE);\n\t// Assert the configuration exists.\n\tAssert.exists(\n\t\tconfig,\n\t\t`unrecognized address config: ${ADDRESS_TYPE} on ${network}`,\n\t);\n\t// Assert the payload size is correct.\n\tAssert.ok(\n\t\tscript_hash.length === config.size,\n\t\t`invalid payload size: ${script_hash.length} !== ${config.size}`,\n\t);\n\t// Encode the address.\n\treturn encode_address({\n\t\tdata: script_hash,\n\t\tformat: \"base58\",\n\t\tversion: config.version,\n\t});\n}\n\nfunction decode_p2sh_address(address: string): AddressInfo {\n\t// Parse the address.\n\tconst parsed = get_address_info(address);\n\t// Assert the address type is correct.\n\tAssert.ok(\n\t\tparsed.type === \"p2sh\",\n\t\t`address type mismatch: ${parsed.type} !== ${ADDRESS_TYPE}`,\n\t);\n\t// Return the parsed address.\n\treturn parsed;\n}\n\nfunction decode_p2sh_script(script: Bytes): Buff {\n\t// Assert the script is a p2sh script.\n\tAssert.ok(is_p2sh_script(script), `invalid p2sh script`);\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Return the script hash from the script.\n\treturn bytes.slice(2, 22);\n}\n","/**\n * P2TR (Pay-to-Taproot) address utilities.\n *\n * P2TR is the Taproot (SegWit v1) address format (addresses starting with \"bc1p\").\n * Supports both key-path and script-path spending with improved privacy.\n *\n * @see https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki\n * @module\n */\n\nimport { Buff, type Bytes } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/util\";\nimport { LOCK_SCRIPT_TYPE } from \"@/const.js\";\nimport { is_p2tr_script } from \"@/lib/script/lock.js\";\nimport type { AddressInfo, ChainNetwork } from \"@/types/index.js\";\nimport { encode_address } from \"./encode.js\";\nimport { get_address_config, get_address_info } from \"./util.js\";\n\nconst ADDRESS_TYPE = LOCK_SCRIPT_TYPE.P2TR;\n\n/**\n * P2TR address namespace.\n *\n * @example\n * ```typescript\n * // Create address from x-only public key (32 bytes)\n * const address = P2TR.create_address(xonlyPubkey, 'main')\n * // Returns: bc1p...\n *\n * // Decode address to get script info\n * const info = P2TR.decode_address('bc1p...')\n * ```\n */\nexport namespace P2TR {\n\texport const create_address = create_p2tr_address;\n\texport const create_script = create_p2tr_script;\n\texport const encode_address = encode_p2tr_address;\n\texport const encode_script = encode_p2tr_script;\n\texport const decode_address = decode_p2tr_address;\n\texport const decode_script = decode_p2tr_script;\n}\n\nfunction create_p2tr_address(\n\tpubkey: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Create the p2tr script.\n\tconst script = create_p2tr_script(pubkey);\n\t// Encode the script as an address.\n\treturn encode_p2tr_address(script, network);\n}\n\nfunction create_p2tr_script(pubkey: Bytes): Buff {\n\t// Convert the public key into bytes.\n\tconst bytes = Buff.bytes(pubkey);\n\t// Assert the public key is 32 bytes.\n\tAssert.ok(bytes.length === 32, \"invalid pubkey size\");\n\t// Return the script.\n\treturn encode_p2tr_script(bytes);\n}\n\nfunction encode_p2tr_script(pubkey: Bytes): Buff {\n\treturn Buff.join([\"5120\", pubkey]);\n}\n\nfunction encode_p2tr_address(\n\tscript_pk: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Get the public key from the script.\n\tconst pubkey = decode_p2tr_script(script_pk);\n\t// Get the address configuration.\n\tconst config = get_address_config(network, ADDRESS_TYPE);\n\t// Assert the configuration exists.\n\tAssert.exists(\n\t\tconfig,\n\t\t`unrecognized address config: ${ADDRESS_TYPE} on ${network}`,\n\t);\n\t// Assert the payload size is correct.\n\tAssert.ok(\n\t\tpubkey.length === config.size,\n\t\t`invalid payload size: ${pubkey.length} !== ${config.size}`,\n\t);\n\t// Encode the address.\n\treturn encode_address({\n\t\tdata: pubkey,\n\t\tformat: \"bech32m\",\n\t\tprefix: config.prefix,\n\t});\n}\n\nfunction decode_p2tr_address(address: string): AddressInfo {\n\t// Parse the address.\n\tconst parsed = get_address_info(address);\n\t// Assert the address type is correct.\n\tAssert.ok(\n\t\tparsed.type === \"p2tr\",\n\t\t`address type mismatch: ${parsed.type} !== ${ADDRESS_TYPE}`,\n\t);\n\t// Return the parsed address.\n\treturn parsed;\n}\n\nfunction decode_p2tr_script(script: Bytes): Buff {\n\t// Assert the script is a p2tr script.\n\tAssert.ok(is_p2tr_script(script), `invalid p2tr script`);\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Return the public key from the script.\n\treturn bytes.slice(2, 34);\n}\n","/**\n * P2WPKH (Pay-to-Witness-Public-Key-Hash) address utilities.\n *\n * P2WPKH is the native SegWit v0 address format (addresses starting with \"bc1q\").\n * More efficient than P2PKH with lower transaction fees.\n *\n * @module\n */\n\nimport { Buff, type Bytes } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/util\";\nimport { hash160 } from \"@vbyte/crypto/hash\";\nimport { LOCK_SCRIPT_TYPE } from \"@/const.js\";\nimport { is_p2wpkh_script } from \"@/lib/script/lock.js\";\nimport type { AddressInfo, ChainNetwork } from \"@/types/index.js\";\nimport { encode_address } from \"./encode.js\";\nimport { get_address_config, get_address_info } from \"./util.js\";\n\nconst ADDRESS_TYPE = LOCK_SCRIPT_TYPE.P2WPKH;\n\n/**\n * P2WPKH address namespace.\n *\n * @example\n * ```typescript\n * // Create address from public key\n * const address = P2WPKH.create_address(pubkey, 'main')\n * // Returns: bc1q...\n *\n * // Decode address to get script info\n * const info = P2WPKH.decode_address('bc1q...')\n * ```\n */\nexport namespace P2WPKH {\n\texport const create_address = create_p2wpkh_address;\n\texport const create_script = create_p2wpkh_script;\n\texport const encode_address = encode_p2wpkh_address;\n\texport const encode_script = encode_p2wpkh_script;\n\texport const decode_address = decode_p2wpkh_address;\n\texport const decode_script = decode_p2wpkh_script;\n}\n\nfunction create_p2wpkh_address(\n\tpubkey: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Create the p2wpkh script.\n\tconst script = create_p2wpkh_script(pubkey);\n\t// Encode the script as an address.\n\treturn encode_p2wpkh_address(script, network);\n}\n\nfunction create_p2wpkh_script(pubkey: Bytes): Buff {\n\t// Convert the public key into bytes.\n\tconst bytes = Buff.bytes(pubkey);\n\t// Assert the public key is 33 bytes.\n\tAssert.ok(bytes.length === 33, \"invalid pubkey size\");\n\t// Convert the bytes into a hash.\n\tconst hash = hash160(bytes);\n\t// Return the script.\n\treturn encode_p2wpkh_script(hash);\n}\n\nfunction encode_p2wpkh_script(pk_hash: Bytes): Buff {\n\treturn Buff.join([\"0014\", pk_hash]);\n}\n\nfunction encode_p2wpkh_address(\n\tscript_pk: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Get the public key hash from the script.\n\tconst pk_hash = decode_p2wpkh_script(script_pk);\n\t// Get the address configuration.\n\tconst config = get_address_config(network, ADDRESS_TYPE);\n\t// Assert the configuration exists.\n\tAssert.exists(\n\t\tconfig,\n\t\t`unrecognized address config: ${ADDRESS_TYPE} on ${network}`,\n\t);\n\t// Assert the payload size is correct.\n\tAssert.ok(\n\t\tpk_hash.length === config.size,\n\t\t`invalid payload size: ${pk_hash.length} !== ${config.size}`,\n\t);\n\t// Encode the address.\n\treturn encode_address({\n\t\tdata: pk_hash,\n\t\tformat: \"bech32\",\n\t\tprefix: config.prefix,\n\t});\n}\n\nfunction decode_p2wpkh_address(address: string): AddressInfo {\n\t// Parse the address.\n\tconst parsed = get_address_info(address);\n\t// Assert the address type is correct.\n\tAssert.ok(\n\t\tparsed.type === \"p2wpkh\",\n\t\t`address type mismatch: ${parsed.type} !== ${ADDRESS_TYPE}`,\n\t);\n\t// Return the parsed address.\n\treturn parsed;\n}\n\nfunction decode_p2wpkh_script(script: Bytes): Buff {\n\t// Assert the script is a p2wpkh script.\n\tAssert.ok(is_p2wpkh_script(script), `invalid p2wpkh script`);\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Return the public key hash from the script.\n\treturn bytes.slice(2, 22);\n}\n","/**\n * P2WSH (Pay-to-Witness-Script-Hash) address utilities.\n *\n * P2WSH is native SegWit v0 for script-based outputs (addresses starting with \"bc1q\"\n * but longer than P2WPKH). Used for native SegWit multisig and complex scripts.\n *\n * @module\n */\n\nimport { Buff, type Bytes } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/util\";\nimport { sha256 } from \"@vbyte/crypto/hash\";\nimport { LOCK_SCRIPT_TYPE } from \"@/const.js\";\nimport { is_p2wsh_script } from \"@/lib/script/lock.js\";\nimport type { AddressInfo, ChainNetwork } from \"@/types/index.js\";\nimport { encode_address } from \"./encode.js\";\nimport { get_address_config, get_address_info } from \"./util.js\";\n\nconst ADDRESS_TYPE = LOCK_SCRIPT_TYPE.P2WSH;\n\n/**\n * P2WSH address namespace.\n *\n * @example\n * ```typescript\n * // Create address from witness script\n * const address = P2WSH.create_address(witnessScript, 'main')\n * // Returns: bc1q... (62 characters)\n *\n * // Decode address to get script info\n * const info = P2WSH.decode_address('bc1q...')\n * ```\n */\nexport namespace P2WSH {\n\texport const create_address = create_p2wsh_address;\n\texport const create_script = create_p2wsh_script;\n\texport const encode_address = encode_p2wsh_address;\n\texport const encode_script = encode_p2wsh_script;\n\texport const decode_address = decode_p2wsh_address;\n\texport const decode_script = decode_p2wsh_script;\n}\n\nfunction create_p2wsh_address(\n\tscript: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Create the p2wsh script.\n\tconst wsh_script = create_p2wsh_script(script);\n\t// Encode the script as an address.\n\treturn encode_p2wsh_address(wsh_script, network);\n}\n\nfunction create_p2wsh_script(script: Bytes): Buff {\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Convert the bytes into a hash.\n\tconst hash = sha256(bytes);\n\t// Return the script.\n\treturn encode_p2wsh_script(hash);\n}\n\nfunction encode_p2wsh_script(script_hash: Bytes): Buff {\n\treturn Buff.join([\"0020\", script_hash]);\n}\n\nfunction encode_p2wsh_address(\n\tscript_pk: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Get the script hash from the script.\n\tconst script_hash = decode_p2wsh_script(script_pk);\n\t// Get the address configuration.\n\tconst config = get_address_config(network, ADDRESS_TYPE);\n\t// Assert the configuration exists.\n\tAssert.exists(\n\t\tconfig,\n\t\t`unrecognized address config: ${ADDRESS_TYPE} on ${network}`,\n\t);\n\t// Assert the payload size is correct.\n\tAssert.ok(\n\t\tscript_hash.length === config.size,\n\t\t`invalid payload size: ${script_hash.length} !== ${config.size}`,\n\t);\n\t// Encode the address.\n\treturn encode_address({\n\t\tdata: script_hash,\n\t\tformat: \"bech32\",\n\t\tprefix: config.prefix,\n\t});\n}\n\nfunction decode_p2wsh_address(address: string): AddressInfo {\n\t// Parse the address.\n\tconst parsed = get_address_info(address);\n\t// Assert the address type is correct.\n\tAssert.ok(\n\t\tparsed.type === \"p2wsh\",\n\t\t`address type mismatch: ${parsed.type} !== ${ADDRESS_TYPE}`,\n\t);\n\t// Return the parsed address.\n\treturn parsed;\n}\n\nfunction decode_p2wsh_script(script: Bytes): Buff {\n\t// Assert the script is a p2wsh script.\n\tAssert.ok(is_p2wsh_script(script), `invalid p2wsh script`);\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Return the script hash from the script.\n\treturn bytes.slice(2, 34);\n}\n","import { Buff, type Bytes } from \"@vbyte/buff\";\nimport { LOCK_SCRIPT_TYPE } from \"@/const.js\";\nimport { ConfigError } from \"@/error.js\";\nimport { get_lock_script_type } from \"@/lib/script/lock.js\";\nimport type { AddressInfo, ChainNetwork } from \"@/types/index.js\";\n\nimport { P2PKH } from \"./p2pkh.js\";\nimport { P2SH } from \"./p2sh.js\";\nimport { P2TR } from \"./p2tr.js\";\nimport { P2WPKH } from \"./p2wpkh.js\";\nimport { P2WSH } from \"./p2wsh.js\";\nimport { get_address_info } from \"./util.js\";\n\n/**\n * Get the address for a given locking script.\n *\n * @param script - The locking script.\n * @param network - The network to use.\n * @returns The address.\n */\nexport function get_address(\n\tscript: Bytes,\n\tnetwork: ChainNetwork = \"main\",\n): string {\n\t// Convert the script into bytes.\n\tconst bytes = Buff.bytes(script);\n\t// Get the address configuration.\n\tconst type = get_lock_script_type(bytes);\n\t// If the script type is not recognized, throw an error.\n\tif (type === null)\n\t\tthrow new ConfigError(\"Unknown or unsupported locking script type\");\n\t// Create the address based on the script type.\n\tswitch (type) {\n\t\tcase LOCK_SCRIPT_TYPE.P2PKH:\n\t\t\treturn P2PKH.encode_address(script, network);\n\t\tcase LOCK_SCRIPT_TYPE.P2SH:\n\t\t\treturn P2SH.encode_address(script, network);\n\t\tcase LOCK_SCRIPT_TYPE.P2WPKH:\n\t\t\treturn P2WPKH.encode_address(script, network);\n\t\tcase LOCK_SCRIPT_TYPE.P2WSH:\n\t\t\treturn P2WSH.encode_address(script, network);\n\t\tcase LOCK_SCRIPT_TYPE.P2TR:\n\t\t\treturn P2TR.encode_address(script, network);\n\t\tdefault:\n\t\t\tthrow new ConfigError(`unknown script type: ${type}`);\n\t}\n}\n\n/**\n * Parse a Bitcoin address and return its information.\n *\n * Analyzes the address format and extracts type, network, and data.\n * Supports all standard address formats: P2PKH, P2SH, P2WPKH, P2WSH, P2TR.\n *\n * @param address - The Bitcoin address to parse\n * @returns Address information including type, network, format, and data\n * @throws Error if the address format is invalid or unrecognized\n *\n * @example\n * ```typescript\n * // Parse a mainnet P2WPKH address\n * const info = parse_address('bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4')\n * // { type: 'p2wpkh', network: 'main', format: 'bech32', data: '751e76e8199196d454941c45d1b3a323f1433bd6' }\n *\n * // Parse a testnet P2TR address\n * const info = parse_address('tb1p...')\n * // { type: 'p2tr', network: 'testnet', format: 'bech32m', data: '...' }\n * ```\n */\nexport function parse_address(address: string): AddressInfo {\n\treturn get_address_info(address);\n}\n","/**\n * Bitcoin Transaction Locktime Field Manipulation.\n *\n * This module provides functionality for encoding and decoding the locktime field\n * in Bitcoin transactions. The locktime field is a 32-bit integer that specifies:\n *\n * - Values < 500,000,000: Block height at which the transaction becomes valid\n * - Values >= 500,000,000: Unix timestamp at which the transaction becomes valid\n *\n * The implementation follows BIP-65 (CHECKLOCKTIMEVERIFY) semantics.\n *\n * @see https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki\n * @module\n */\n\nimport { Assert } from \"@vbyte/util\";\n\nimport { ConfigError } from \"@/error.js\";\nimport type { LocktimeData } from \"@/types/index.js\";\n\n/** The threshold between block height and timestamp (500,000,000). */\nconst LOCKTIME_THRESHOLD = 500000000;\n\nexport namespace LocktimeField {\n\texport const encode = encode_locktime;\n\texport const decode = decode_locktime;\n}\n\n/**\n * Encode locktime data into a numeric locktime value.\n *\n * Converts a locktime configuration into the 32-bit locktime field value.\n * For heightlock, the value is the block height directly.\n * For timelock, the value is the Unix timestamp.\n *\n * @param locktime - The locktime configuration to encode\n * @returns The 32-bit locktime value\n * @throws Error if the locktime type or value is invalid\n *\n * @example\n * ```typescript\n * // Height-based locktime (block 800000)\n * encode_locktime({ type: 'heightlock', height: 800000 })\n * // 800000\n *\n * // Time-based locktime (Jan 1, 2024)\n * encode_locktime({ type: 'timelock', stamp: 1704067200 })\n * // 1704067200\n * ```\n */\nexport function encode_locktime(locktime: LocktimeData): number {\n\tswitch (locktime.type) {\n\t\tcase \"timelock\":\n\t\t\tAssert.ok(locktime.stamp >= LOCKTIME_THRESHOLD, \"Invalid timestamp\");\n\t\t\treturn locktime.stamp;\n\t\tcase \"heightlock\":\n\t\t\tAssert.ok(locktime.height > 0, \"height must be greater than 0\");\n\t\t\tAssert.ok(locktime.height < LOCKTIME_THRESHOLD, \"invalid block height\");\n\t\t\treturn locktime.height;\n\t\tdefault:\n\t\t\tthrow new ConfigError(`Invalid locktime type: expected 'timelock' or 'heightlock'`);\n\t}\n}\n\n/**\n * Decode a locktime value into a locktime data object.\n *\n * According to BIP-65, values below 500,000,000 are interpreted as block heights,\n * while values at or above this threshold are interpreted as Unix timestamps.\n *\n * @param locktime - The 32-bit locktime value to decode\n * @returns Decoded locktime data, or null if the value is invalid (NaN or <= 0)\n *\n * @example\n * ```typescript\n * // Decode block height locktime\n * decode_locktime(800000)\n * // { type: 'heightlock', height: 800000 }\n *\n * // Decode timestamp locktime\n * decode_locktime(1704067200)\n * // { type: 'timelock', stamp: 1704067200 }\n *\n * // Invalid locktime\n * decode_locktime(0)\n * // null\n * ```\n */\nexport function decode_locktime(locktime: number): LocktimeData | null {\n\t// Check if the value is valid (non-negative)\n\tif (Number.isNaN(locktime) || locktime <= 0) {\n\t\treturn null;\n\t}\n\t// Return the appropriate locktime type.\n\tif (locktime < LOCKTIME_THRESHOLD) {\n\t\treturn {\n\t\t\ttype: \"heightlock\",\n\t\t\theight: locktime,\n\t\t};\n\t} else {\n\t\treturn {\n\t\t\ttype: \"timelock\",\n\t\t\tstamp: locktime,\n\t\t};\n\t}\n}\n","import { ValidationError } from \"@/error.js\";\n\nexport namespace RefPointer {\n\texport const outpoint = {\n\t\tencode: encode_outpoint,\n\t\tdecode: decode_outpoint,\n\t\tverify: verify_outpoint,\n\t\tassert: assert_outpoint,\n\t};\n\texport const record_id = {\n\t\tencode: encode_inscription_id,\n\t\tdecode: decode_inscription_id,\n\t\tverify: verify_inscription_id,\n\t\tassert: assert_inscription_id,\n\t};\n\texport const rune_id = {\n\t\tencode: encode_rune_id,\n\t\tdecode: decode_rune_id,\n\t\tverify: verify_rune_id,\n\t\tassert: assert_rune_id,\n\t};\n}\n\nfunction encode_inscription_id(txid: string, order: number = 0): string {\n\treturn `${txid}i${order}`;\n}\n\nfunction decode_inscription_id(inscription_id: string): {\n\ttxid: string;\n\torder: number;\n} {\n\tassert_inscription_id(inscription_id);\n\tconst [txid, order] = inscription_id.split(\"i\");\n\treturn { txid, order: parseInt(order, 10) };\n}\n\nfunction verify_inscription_id(inscription_id: string): boolean {\n\treturn inscription_id.match(/^[a-f0-9]{64}i\\d+$/) !== null;\n}\n\nfunction assert_inscription_id(inscription_id: string): void {\n\tif (!verify_inscription_id(inscription_id)) {\n\t\tthrow new ValidationError(\n\t\t\t`invalid inscription id: \"${inscription_id}\". Expected format: <64-char-txid>i<index> (e.g., \"abc123...i0\")`\n\t\t);\n\t}\n}\n\nfunction encode_rune_id(block_height: number, block_index: number): string {\n\treturn `${block_height}:${block_index}`;\n}\n\nfunction decode_rune_id(rune_id: string): {\n\tblock_height: number;\n\tblock_index: number;\n} {\n\tassert_rune_id(rune_id);\n\tconst [block_height, block_index] = rune_id.split(\":\");\n\treturn {\n\t\tblock_height: parseInt(block_height, 10),\n\t\tblock_index: parseInt(block_index, 10),\n\t};\n}\n\nfunction verify_rune_id(rune_id: string): boolean {\n\treturn rune_id.match(/^\\d+:\\d+$/) !== null;\n}\n\nfunction assert_rune_id(rune_id: string): void {\n\tif (!verify_rune_id(rune_id)) {\n\t\tthrow new ValidationError(\n\t\t\t`invalid rune id: \"${rune_id}\". Expected format: <block_height>:<block_index> (e.g., \"840000:1\")`\n\t\t);\n\t}\n}\n\nfunction encode_outpoint(txid: string, vout: number): string {\n\treturn `${txid}:${vout}`;\n}\n\nfunction decode_outpoint(outpoint: string): { txid: string; vout: number } {\n\tassert_outpoint(outpoint);\n\tconst [txid, vout] = outpoint.split(\":\");\n\treturn { txid, vout: parseInt(vout, 10) };\n}\n\nfunction verify_outpoint(outpoint: string): boolean {\n\treturn outpoint.match(/^[a-f0-9]{64}:[0-9]+$/) !== null;\n}\n\nfunction assert_outpoint(outpoint: string): void {\n\tif (!verify_outpoint(outpoint)) {\n\t\tthrow new ValidationError(\n\t\t\t`invalid outpoint: \"${outpoint}\". Expected format: <64-char-txid>:<vout> (e.g., \"abc123...:0\")`\n\t\t);\n\t}\n}\n","import { ValidationError } from \"@/error.js\";\n\nexport const OPCODE_MAP = {\n\tOP_0: 0x00,\n\tOP_PUSHDATA1: 0x4c,\n\tOP_PUSHDATA2: 0x4d,\n\tOP_PUSHDATA4: 0x4e,\n\tOP_1NEGATE: 0x4f,\n\tOP_SUCCESS80: 0x50,\n\tOP_1: 0x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ESS142: 0x8e,\n\tOP_NEGATE: 0x8f,\n\tOP_ABS: 0x90,\n\tOP_NOT: 0x91,\n\tOP_0NOTEQUAL: 0x92,\n\tOP_ADD: 0x93,\n\tOP_SUB: 0x94,\n\tOP_SUCCESS149: 0x95,\n\tOP_SUCCESS150: 0x96,\n\tOP_SUCCESS151: 0x97,\n\tOP_SUCCESS152: 0x98,\n\tOP_SUCCESS153: 0x99,\n\tOP_BOOLAND: 0x9a,\n\tOP_BOOLOR: 0x9b,\n\tOP_NUMEQUAL: 0x9c,\n\tOP_NUMEQUALVERIFY: 0x9d,\n\tOP_NUMNOTEQUAL: 0x9e,\n\tOP_LESSTHAN: 0x9f,\n\tOP_GREATERTHAN: 0xa0,\n\tOP_LESSTHANOREQUAL: 0xa1,\n\tOP_GREATERTHANOREQUAL: 0xa2,\n\tOP_MIN: 0xa3,\n\tOP_MAX: 0xa4,\n\tOP_WITHIN: 0xa5,\n\tOP_RIPEMD160: 0xa6,\n\tOP_SHA1: 0xa7,\n\tOP_SHA256: 0xa8,\n\tOP_HASH160: 0xa9,\n\tOP_HASH256: 0xaa,\n\tOP_CODESEPARATOR: 0xab,\n\tOP_CHECKSIG: 0xac,\n\tOP_CHECKSIGVERIFY: 0xad,\n\tOP_CHECKMULTISIG: 0xae,\n\tOP_CHECKMULTISIGVERIFY: 0xaf,\n\tOP_NOP1: 0xb0,\n\tOP_CHECKLOCKTIMEVERIFY: 0xb1,\n\tOP_CHECKSEQUENCEVERIFY: 0xb2,\n\tOP_NOP4: 0xb3,\n\tOP_NOP5: 0xb4,\n\tOP_NOP6: 0xb5,\n\tOP_NOP7: 0xb6,\n\tOP_NOP8: 0xb7,\n\tOP_NOP9: 0xb8,\n\tOP_NOP10: 0xb9,\n\tOP_CHECKSIGADD: 0xba,\n};\n\n/**\n * Get the sting-representation of an opcode\n * based on its number value.\n */\nexport function get_op_code(num: number): string {\n\tif (num > 186 && num < 255) {\n\t\treturn `OP_SUCCESS${String(num)}`;\n\t}\n\tfor (const [k, v] of Object.entries(OPCODE_MAP)) {\n\t\tif (v === num) return k;\n\t}\n\tthrow new ValidationError(\n\t\t`opcode not found for value: ${num} (0x${num.toString(16)}). Valid range is 0x00-0xba`\n\t);\n}\n\n/**\n * Get the number-representation of an opcode\n * based on its asm string value.\n */\nexport function get_asm_code(string: string): number {\n\tfor (const [k, v] of Object.entries(OPCODE_MAP)) {\n\t\tif (k === string) return Number(v);\n\t}\n\tthrow new ValidationError(\n\t\t`opcode not found: \"${string}\". Valid opcodes start with \"OP_\" (e.g., OP_DUP, OP_CHECKSIG)`\n\t);\n}\n\n/**\n * Get the type of word based on its number value.\n */\nexport function get_op_type(word: number): string {\n\tswitch (true) {\n\t\tcase word === 0:\n\t\t\treturn \"opcode\";\n\t\tcase word >= 1 && word <= 75:\n\t\t\treturn \"varint\";\n\t\tcase word === 76:\n\t\t\treturn \"pushdata1\";\n\t\tcase word === 77:\n\t\t\treturn \"pushdata2\";\n\t\tcase word === 78:\n\t\t\treturn \"pushdata4\";\n\t\tcase word <= 254:\n\t\t\treturn \"opcode\";\n\t\tdefault:\n\t\t\tthrow new ValidationError(`invalid word value: ${word}. Expected 0-254`);\n\t}\n}\n\n/**\n * Check if the provided value is a valid script opcode.\n */\nexport function is_valid_op(word: number): boolean {\n\tconst MIN_RANGE = 75;\n\tconst MAX_RANGE = 254;\n\n\tconst DISABLED_OPCODES: number[] = [];\n\n\tswitch (true) {\n\t\tcase typeof word !== \"number\":\n\t\t\treturn false;\n\t\tcase word === 0:\n\t\t\treturn true;\n\t\tcase DISABLED_OPCODES.includes(word):\n\t\t\treturn false;\n\t\tcase MIN_RANGE < word && word < MAX_RANGE:\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n","import { Buff, type Bytes, Stream } from \"@vbyte/buff\";\nimport { DecodingError } from \"@/error.js\";\nimport type { ScriptInfo } from \"@/types/script.js\";\nimport { get_op_code, get_op_type, is_valid_op } from \"./words.js\";\n\nexport function parse_script(script: Bytes): ScriptInfo {\n\tconst bytes = Buff.bytes(script);\n\treturn {\n\t\tasm: decode_script(bytes),\n\t\thex: bytes.hex,\n\t};\n}\n\n/**\n * Decode a bitcoin script into asm instructions.\n */\nexport function decode_script(script: Bytes): string[] {\n\tconst stream = new Stream(script);\n\n\tconst stack: string[] = [];\n\tconst stack_size = stream.size;\n\n\tlet word: number;\n\tlet word_type: string;\n\tlet word_size: number;\n\n\tlet count = 0;\n\n\twhile (count < stack_size) {\n\t\tword = stream.read(1).num;\n\t\tword_type = get_op_type(word);\n\t\tcount++;\n\t\tswitch (word_type) {\n\t\t\tcase \"varint\":\n\t\t\t\ttry {\n\t\t\t\t\tstack.push(stream.read(word).hex);\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new DecodingError(\n\t\t\t\t\t\t`Malformed script: varint push at position ${count - 1} requires ${word} bytes but stream exhausted`,\n\t\t\t\t\t\tcount - 1,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcount += word;\n\t\t\t\tbreak;\n\t\t\tcase \"pushdata1\":\n\t\t\t\ttry {\n\t\t\t\t\tword_size = stream.read(1).reverse().num;\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new DecodingError(\n\t\t\t\t\t\t`Malformed script: PUSHDATA1 at position ${count - 1} missing size byte`,\n\t\t\t\t\t\tcount - 1,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tstack.push(stream.read(word_size).hex);\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new DecodingError(\n\t\t\t\t\t\t`Malformed script: PUSHDATA1 at position ${count - 1} requires ${word_size} bytes but stream exhausted`,\n\t\t\t\t\t\tcount - 1,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcount += word_size + 1;\n\t\t\t\tbreak;\n\t\t\tcase \"pushdata2\":\n\t\t\t\ttry {\n\t\t\t\t\tword_size = stream.read(2).reverse().num;\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new DecodingError(\n\t\t\t\t\t\t`Malformed script: PUSHDATA2 at position ${count - 1} missing size bytes`,\n\t\t\t\t\t\tcount - 1,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tstack.push(stream.read(word_size).hex);\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new DecodingError(\n\t\t\t\t\t\t`Malformed script: PUSHDATA2 at position ${count - 1} requires ${word_size} bytes but stream exhausted`,\n\t\t\t\t\t\tcount - 1,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcount += word_size + 2;\n\t\t\t\tbreak;\n\t\t\tcase \"pushdata4\":\n\t\t\t\ttry {\n\t\t\t\t\tword_size = stream.read(4).reverse().num;\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new DecodingError(\n\t\t\t\t\t\t`Malformed script: PUSHDATA4 at position ${count - 1} missing size bytes`,\n\t\t\t\t\t\tcount - 1,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tstack.push(stream.read(word_size).hex);\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new DecodingError(\n\t\t\t\t\t\t`Malformed script: PUSHDATA4 at position ${count - 1} requires ${word_size} bytes but stream exhausted`,\n\t\t\t\t\t\tcount - 1,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcount += word_size + 4;\n\t\t\t\tbreak;\n\t\t\tcase \"opcode\":\n\t\t\t\tif (!is_valid_op(word)) {\n\t\t\t\t\tthrow new DecodingError(`Invalid OPCODE: ${word}`, count - 1);\n\t\t\t\t}\n\t\t\t\tstack.push(get_op_code(word));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new DecodingError(`Word type undefined: ${word}`, count - 1);\n\t\t}\n\t}\n\treturn stack;\n}\n\n/**\n * Check if a script is valid.\n */\nexport function is_valid_script(script: string | Uint8Array): boolean {\n\ttry {\n\t\tconst stack = decode_script(script);\n\t\treturn stack.length > 0;\n\t} catch {\n\t\treturn false;\n\t}\n}\n","import { Buff, Stream } from \"@vbyte/buff\";\nimport { MAX_SCRIPT_SIZE, OP_1_OFFSET } from \"@/const.js\";\nimport { ValidationError } from \"@/error.js\";\nimport { get_asm_code } from \"./words.js\";\n\n// The maximum size of a word in bytes.\nconst MAX_WORD_SIZE = 520;\n\n/**\n * Encode script asm instructions into a byte buffer.\n *\n * @param words - Array of script words (opcodes, hex data, strings, numbers, or bytes)\n * @param varint - If true, prefix the script with its length as a varint\n * @returns Encoded script as a Buff\n *\n * @example\n * ```typescript\n * // Encode a P2PKH script\n * const script = encode_script(['OP_DUP', 'OP_HASH160', pubkeyHash, 'OP_EQUALVERIFY', 'OP_CHECKSIG'])\n *\n * // Encode with varint prefix\n * const scriptWithLen = encode_script(['OP_1', pubkey, 'OP_1', 'OP_CHECKMULTISIG'], true)\n * ```\n */\nexport function encode_script(\n\twords: (string | number | Uint8Array)[],\n\tvarint = false,\n): Buff {\n\tif (words.length === 0) return Buff.num(0, 1);\n\n\tconst bytes = [];\n\n\tfor (const word of words) {\n\t\tbytes.push(encode_script_word(word));\n\t}\n\n\tconst buffer = Buff.join(bytes);\n\n\t// Validate script size against Bitcoin consensus limit\n\tif (buffer.length > MAX_SCRIPT_SIZE) {\n\t\tthrow new ValidationError(\n\t\t\t`script size ${buffer.length} exceeds consensus limit of ${MAX_SCRIPT_SIZE} bytes`,\n\t\t);\n\t}\n\n\treturn varint\n\t\t? buffer.prepend(Buff.create_varint(buffer.length, \"le\"))\n\t\t: buffer;\n}\n\n/** Check if the word is a valid opcode,\n * and return its integer value.\n */\nexport function encode_script_word(\n\tword: string | number | Uint8Array,\n): Uint8Array {\n\tlet buff: Buff;\n\n\t// If word is a string:\n\tif (typeof word === \"string\") {\n\t\t// If word is an opcode:\n\t\tif (word.startsWith(\"OP_\")) {\n\t\t\t// Get the opcode number value.\n\t\t\tconst asm_code = get_asm_code(word);\n\t\t\t// Return the opcode as a single byte.\n\t\t\treturn Buff.num(asm_code, 1);\n\t\t\t// If word is valid hex:\n\t\t} else if (Buff.is_hex(word)) {\n\t\t\t// Encode as hex.\n\t\t\tbuff = Buff.hex(word);\n\t\t} else {\n\t\t\t// Encode as UTF8 string.\n\t\t\tbuff = Buff.str(word);\n\t\t}\n\t\t// If word is a number:\n\t} else if (typeof word === \"number\") {\n\t\t// Encode the number value.\n\t\tbuff = Buff.num(word);\n\t\t// If word is a Uint8Array:\n\t} else if (word instanceof Uint8Array) {\n\t\t// Encode as bytes.\n\t\tbuff = new Buff(word);\n\t} else {\n\t\t// If word is not a string, number, or Uint8Array, throw an error.\n\t\tthrow new ValidationError(\n\t\t\t`invalid script word type: ${typeof word}. Expected string, number, or Uint8Array`\n\t\t);\n\t}\n\n\t// Format and return the word based on its size.\n\tif (buff.length === 1 && buff[0] <= 16) {\n\t\t// Number values 0-16 must be treated as opcodes.\n\t\tif (buff[0] !== 0) buff[0] += OP_1_OFFSET;\n\t} else if (buff.length > MAX_WORD_SIZE) {\n\t\t// Number values larger than max size must be split into chunks.\n\t\tlet words: Buff[];\n\t\t// Split bytes into chunks, based on max word size.\n\t\twords = split_script_word(buff);\n\t\t// Prefix a varint length byte for each chunk.\n\t\twords = words.map((e) => prefix_word_size(e));\n\t\t// Concatenate the chunks\n\t\tbuff = Buff.join(words);\n\t} else {\n\t\t// Else, return the word with a varint prefix.\n\t\tbuff = prefix_word_size(buff);\n\t}\n\t// Return the final result.\n\treturn buff;\n}\n\n/**\n * Split a word into smaller chunks.\n *\n * @internal\n */\nexport function split_script_word(word: Uint8Array): Buff[] {\n\tconst words = [];\n\tconst buff = new Stream(word);\n\twhile (buff.size > MAX_WORD_SIZE) {\n\t\t// Push a word chunk to the array.\n\t\twords.push(buff.read(MAX_WORD_SIZE));\n\t}\n\t// Push the remainder to the array.\n\twords.push(buff.read(buff.size));\n\treturn words;\n}\n\n/**\n * Prefix a word with its size, encoded as a varint.\n *\n * @internal\n */\nexport function prefix_word_size(word: Uint8Array): Buff {\n\tconst varint = get_size_varint(word.length);\n\treturn Buff.join([varint, word]);\n}\n\n/**\n * Return a varint that encodes a size value.\n *\n * @internal\n */\nexport function get_size_varint(size: number): Buff {\n\tconst OP_PUSHDATA1 = Buff.num(0x4c, 1);\n\tconst OP_PUSHDATA2 = Buff.num(0x4d, 1);\n\tswitch (true) {\n\t\tcase size <= 0x4b:\n\t\t\treturn Buff.num(size);\n\t\tcase size > 0x4b && size < 0x100:\n\t\t\treturn Buff.join([OP_PUSHDATA1, Buff.num(size, 1, \"le\")]);\n\t\tcase size >= 0x100 && size <= MAX_WORD_SIZE:\n\t\t\treturn Buff.join([OP_PUSHDATA2, Buff.num(size, 2, \"le\")]);\n\t\tdefault:\n\t\t\tthrow new ValidationError(\n\t\t\t\t`invalid script word size: ${size}. Maximum allowed is ${MAX_WORD_SIZE} bytes`\n\t\t\t);\n\t}\n}\n","/**\n * Bitcoin inscription (Ordinals) encoding and decoding utilities.\n *\n * Implements the Ordinals inscription envelope format for embedding\n * arbitrary data in Bitcoin transactions.\n *\n * @see https://docs.ordinals.com/inscriptions.html\n * @module\n */\n\nimport { Buff, type Bytes, Stream } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/util\";\nimport { ValidationError } from \"@/error.js\";\nimport { decode_script } from \"@/lib/script/decode.js\";\nimport { encode_script } from \"@/lib/script/encode.js\";\n\nimport type { InscriptionData } from \"@/types/index.js\";\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _26n = BigInt(26);\n\n/**\n * Inscription utility namespace.\n *\n * @example\n * ```typescript\n * // Decode inscriptions from witness script\n * const inscriptions = InscriptionUtil.decode(witnessScript)\n *\n * // Encode inscription data to script\n * const script = InscriptionUtil.encode([{\n * mimetype: 'text/plain',\n * content: 'Hello, Bitcoin!'\n * }])\n * ```\n */\nexport namespace InscriptionUtil {\n\texport type Type = InscriptionData;\n\texport const encode = encode_inscription;\n\texport const decode = decode_inscription;\n}\n\n/**\n * Decode inscription envelopes from a script.\n *\n * Parses the Ordinals envelope format (OP_0 OP_IF ... OP_ENDIF)\n * and extracts inscription data including mimetype, content, parent, etc.\n *\n * @param script - Script bytes containing inscription envelopes\n * @returns Array of decoded inscription data objects\n * @throws {Error} If envelope format is invalid\n */\nexport function decode_inscription(script: Bytes): InscriptionData[] {\n\tconst envelopes = parse_envelopes(script);\n\treturn envelopes.map(parse_record);\n}\n\n/**\n * Encode inscription data into a script.\n *\n * Creates Ordinals envelope format scripts that can be embedded\n * in taproot witness data.\n *\n * @param data - Array of inscription data objects to encode\n * @returns Encoded script as Buff\n *\n * @example\n * ```typescript\n * const script = encode_inscription([{\n * mimetype: 'image/png',\n * content: pngHexData\n * }])\n * ```\n */\nexport function encode_inscription(data: InscriptionData[]): Buff {\n\treturn Buff.join(data.map(create_envelope));\n}\n\nfunction create_envelope(data: InscriptionData): Buff {\n\tconst asm: string[] = [\"OP_0\", \"OP_IF\", \"6f7264\"];\n\n\tif (typeof data.delegate === \"string\") {\n\t\tconst id = encode_id(data.delegate);\n\t\tasm.push(\"OP_11\", id);\n\t}\n\n\tif (typeof data.ref === \"string\") {\n\t\tasm.push(\"OP_WITHIN\", data.ref);\n\t}\n\n\tif (typeof data.parent === \"string\") {\n\t\tconst id = encode_id(data.parent);\n\t\tasm.push(\"OP_3\", id);\n\t}\n\n\tif (typeof data.opcode === \"number\") {\n\t\tconst code = encode_pointer(data.opcode);\n\t\tasm.push(\"OP_NOP\", code);\n\t}\n\n\tif (typeof data.pointer === \"number\") {\n\t\tconst ptr = encode_pointer(data.pointer);\n\t\tasm.push(\"OP_2\", ptr);\n\t}\n\n\tif (typeof data.rune === \"string\") {\n\t\tconst label = encode_rune_label(data.rune);\n\t\tasm.push(\"OP_13\", label);\n\t}\n\n\tif (typeof data.mimetype === \"string\") {\n\t\tconst label = encode_label(data.mimetype);\n\t\tasm.push(\"OP_1\", label);\n\t}\n\n\tif (typeof data.content === \"string\") {\n\t\tconst chunks = encode_content(data.content);\n\t\tasm.push(\"OP_0\", ...chunks);\n\t}\n\n\tasm.push(\"OP_ENDIF\");\n\n\treturn encode_script(asm);\n}\n\nfunction parse_envelopes(script: Bytes): string[][] {\n\tconst words = decode_script(script);\n\tconst start_idx = words.indexOf(\"OP_0\");\n\n\tAssert.ok(start_idx !== -1, \"inscription envelope not found\");\n\n\tconst envelopes = [];\n\n\tfor (let idx = start_idx; idx < words.length; idx++) {\n\t\tAssert.ok(idx + 2 < words.length, \"incomplete envelope: missing OP_IF or magic bytes\");\n\t\tAssert.ok(words[idx + 1] === \"OP_IF\", \"OP_IF missing from envelope\");\n\t\tAssert.ok(words[idx + 2] === \"6f7264\", \"magic bytes missing from envelope\");\n\n\t\tconst stop_idx = words.indexOf(\"OP_ENDIF\", idx);\n\t\tAssert.ok(stop_idx !== -1, \"inscription envelope missing OP_ENDIF statement\");\n\n\t\tconst env = words.slice(idx + 3, stop_idx);\n\t\tenvelopes.push(env);\n\t\tidx = stop_idx;\n\t}\n\n\treturn envelopes;\n}\n\nfunction parse_record(envelope: Bytes[]) {\n\tconst record: InscriptionData = {};\n\n\tfor (let i = 0; i < envelope.length; i++) {\n\t\tswitch (envelope[i]) {\n\t\t\tcase \"OP_1\":\n\t\t\t\trecord.mimetype = decode_label(envelope[i + 1]);\n\t\t\t\ti += 1;\n\t\t\t\tbreak;\n\t\t\tcase \"OP_2\":\n\t\t\t\trecord.pointer = decode_pointer(envelope[i + 1]);\n\t\t\t\ti += 1;\n\t\t\t\tbreak;\n\t\t\tcase \"OP_3\":\n\t\t\t\trecord.parent = decode_id(envelope[i + 1]);\n\t\t\t\ti += 1;\n\t\t\t\tbreak;\n\t\t\tcase \"OP_11\":\n\t\t\t\trecord.delegate = decode_id(envelope[i + 1]);\n\t\t\t\ti += 1;\n\t\t\t\tbreak;\n\t\t\tcase \"OP_13\":\n\t\t\t\trecord.rune = decode_rune_label(envelope[i + 1]);\n\t\t\t\ti += 1;\n\t\t\t\tbreak;\n\t\t\tcase \"OP_WITHIN\":\n\t\t\t\trecord.ref = decode_bytes(envelope[i + 1]);\n\t\t\t\ti += 1;\n\t\t\t\tbreak;\n\t\t\tcase \"OP_NOP\":\n\t\t\t\trecord.opcode = decode_pointer(envelope[i + 1]);\n\t\t\t\ti += 1;\n\t\t\t\tbreak;\n\t\t\tcase \"OP_0\":\n\t\t\t\trecord.content = decode_content(envelope.slice(i + 1));\n\t\t\t\treturn record;\n\t\t}\n\t}\n\treturn record;\n}\n\nfunction decode_bytes(bytes: Bytes): string {\n\treturn Buff.bytes(bytes).hex;\n}\n\n/**\n * Normalize a script word that may have been converted to an opcode.\n * Small values (0-16) are converted to OP_0 through OP_16 by the script encoder.\n * This function converts them back to their byte representation.\n */\nfunction normalize_script_word(word: Bytes): Bytes {\n\tif (typeof word === \"string\" && word.startsWith(\"OP_\")) {\n\t\t// OP_0 represents 0, OP_1-OP_16 represent 1-16\n\t\tif (word === \"OP_0\") return Buff.num(0).hex;\n\t\tconst match = word.match(/^OP_(\\d+)$/);\n\t\tif (match) {\n\t\t\tconst num = parseInt(match[1], 10);\n\t\t\tif (num >= 1 && num <= 16) return Buff.num(num).hex;\n\t\t}\n\t}\n\treturn word;\n}\n\nfunction encode_id(identifier: string): string {\n\tAssert.ok(identifier.includes(\"i\"), \"identifier must include an index\");\n\tconst parts = identifier.split(\"i\");\n\tconst bytes = Buff.hex(parts[0]);\n\tconst idx = Number(parts[1]);\n\tconst txid = bytes.reverse().hex;\n\treturn idx !== 0 ? txid + Buff.num(idx).hex : txid;\n}\n\nfunction decode_id(identifier: Bytes): string {\n\tconst bytes = Buff.bytes(identifier);\n\t// If exactly 32 bytes, no index was included (idx=0)\n\tif (bytes.length === 32) {\n\t\treturn `${bytes.reverse().hex}i0`;\n\t}\n\tconst idx = bytes.at(-1) ?? 0;\n\tconst txid = bytes.slice(0, -1).reverse().hex;\n\treturn `${txid}i${String(idx)}`;\n}\n\nfunction encode_pointer(pointer: number): string {\n\treturn Buff.num(pointer).reverse().hex;\n}\n\nfunction decode_pointer(bytes: Bytes): number {\n\treturn Buff.bytes(normalize_script_word(bytes)).reverse().num;\n}\n\nfunction encode_label(label: string): string {\n\treturn Buff.str(label).hex;\n}\n\nfunction decode_label(label: Bytes): string {\n\treturn Buff.bytes(label).str;\n}\n\nfunction encode_content(content: string): string[] {\n\tconst bytes = Buff.is_hex(content) ? Buff.hex(content) : Buff.str(content);\n\tconst stream = new Stream(bytes);\n\tconst chunks: string[] = [];\n\twhile (stream.size > 0) {\n\t\tif (stream.size > 520) {\n\t\t\tconst chunk = stream.read(520);\n\t\t\tchunks.push(chunk.hex);\n\t\t} else {\n\t\t\tconst chunk = stream.read(stream.size);\n\t\t\tchunks.push(chunk.hex);\n\t\t}\n\t}\n\treturn chunks;\n}\n\nfunction decode_content(\n\tchunks: Bytes[],\n\tformat: \"hex\" | \"utf8\" = \"hex\",\n): string {\n\tconst data = Buff.join(chunks);\n\treturn format === \"hex\" ? data.hex : data.str;\n}\n\nfunction encode_rune_label(label: string): string {\n\tconst str = label.toUpperCase();\n\tlet big = _0n;\n\tfor (const char of str) {\n\t\tif (char >= \"A\" && char <= \"Z\") {\n\t\t\tbig = big * _26n + BigInt(char.charCodeAt(0) - (\"A\".charCodeAt(0) - 1));\n\t\t} else {\n\t\t\tthrow new ValidationError(`invalid character in rune label: '${char}' (only A-Z allowed)`, \"label\");\n\t\t}\n\t}\n\tbig = big - _1n;\n\treturn Buff.big(big).reverse().hex;\n}\n\nfunction decode_rune_label(label: Bytes): string {\n\t// Normalize OP_N opcodes back to their byte values\n\tconst normalized = normalize_script_word(label);\n\t// Convert hex to BigInt, with byte order reversed\n\tlet big = Buff.bytes(normalized).reverse().big;\n\t// Add 1 as per the encoding algorithm\n\tbig = big + _1n;\n\t// Initialize result string\n\tlet result = \"\";\n\t// Convert the BigInt back to a string of alphabet characters\n\twhile (big > _0n) {\n\t\t// Get remainder after division by 26\n\t\tconst mod = big % _26n;\n\t\t// Convert remainder to character (0 maps to 'Z', 1 to 'A', 2 to 'B', etc.)\n\t\tif (mod === _0n) {\n\t\t\tresult = `Z${result}`;\n\t\t\tbig = big / _26n - _1n; // Adjust for special case of 'Z'\n\t\t} else {\n\t\t\t// Map 1 to 'A', 2 to 'B', etc.\n\t\t\tconst charCode = Number(mod) + \"A\".charCodeAt(0) - 1;\n\t\t\tresult = String.fromCharCode(charCode) + result;\n\t\t\tbig = big / _26n;\n\t\t}\n\t}\n\treturn result;\n}\n","/**\n * Bitcoin Transaction Sequence Field Manipulation\n *\n * This module provides functionality for encoding and decoding the sequence field in Bitcoin transactions.\n * The sequence field is a 32-bit integer that can be used for various purposes:\n *\n * 1. Relative timelocks (BIP-68).\n * 2. Custom protocol data.\n *\n * The implementation follows BIP-68 for timelock functionality, and extends it with a custom protocol\n * that allows additional metadata to be encoded in the sequence field (to be used by on-chain indexers).\n */\n\nimport { ValidationError } from \"@/error.js\";\nimport type { SequenceConfig, SequenceData } from \"@/types/index.js\";\n\n/* ===== [ Constants ] ===================================================== */\n\nconst TIMELOCK_DISABLE = 0x80000000; // Bit 31: When set, disables relative timelock per BIP-68.\nconst TIMELOCK_TYPE = 0x00400000; // Bit 22: When set, indicates timestamp-based lock; when clear, indicates block-height-based lock.\nconst TIMELOCK_VALUE_MASK = 0x0000ffff; // Bits 0-15: Mask for extracting timelock value (16 bits).\nconst TIMELOCK_VALUE_MAX = 0xffff; // Maximum value for timelock (2^16 - 1).\nconst TIMELOCK_GRANULARITY = 512; // Seconds per timestamp unit (BIP-68 specification).\n\n/* ===== [ API ] ============================================================ */\n\nexport namespace SequenceField {\n\texport const encode = encode_sequence;\n\texport const decode = decode_sequence;\n}\n\n/* ===== [ Encoder ] ======================================================== */\n\n/**\n * Encodes a SequenceData object into a 32-bit integer sequence value\n *\n * @param data - The sequence data to encode\n * @returns A 32-bit integer representing the encoded sequence\n * @throws Error if the input data is invalid or exceeds maximum values\n */\nexport function encode_sequence(data: SequenceConfig): number {\n\t// If the timelock is based on a block height,\n\tif (data.mode === \"height\") {\n\t\t// Validate the height value.\n\t\tconst height = parse_height(data.height);\n\t\t// For heightlock, only encode the height value (TIMELOCK_TYPE bit remains clear)\n\t\treturn (height & TIMELOCK_VALUE_MASK) >>> 0;\n\t}\n\t// If the timelock is based on a timestamp,\n\tif (data.mode === \"stamp\") {\n\t\t// Convert timestamp to 512-second granularity units as per BIP-68.\n\t\tconst stamp = parse_stamp(data.stamp);\n\t\t// Set the TIMELOCK_TYPE bit and encode the timestamp value.\n\t\treturn (TIMELOCK_TYPE | (stamp & TIMELOCK_VALUE_MASK)) >>> 0;\n\t}\n\t// Throw an error if the mode is unrecognized.\n\tthrow new ValidationError(\n\t\t`invalid timelock mode: \"${data.mode}\". Valid modes are \"height\" or \"stamp\"`\n\t);\n}\n\n/* ===== [ Decoder ] ========================================================= */\n\n/**\n * Decodes a 32-bit sequence value into a SequenceData object\n *\n * @param sequence - The 32-bit sequence value to decode\n * @returns A SequenceData object or null if the sequence doesn't represent special data\n * @throws Error if the sequence value is invalid or exceeds maximum values\n */\nexport function decode_sequence(\n\tsequence: number | string,\n): SequenceData | null {\n\t// Parse and validate the sequence value.\n\tconst seq = parse_sequence(sequence);\n\t// If the sequence is disabled, return null.\n\tif (seq & TIMELOCK_DISABLE) return null;\n\t// Extract the value.\n\tconst value = seq & TIMELOCK_VALUE_MASK;\n\t// Check for timestamp-based lock (TIMELOCK_TYPE bit is set).\n\tif (seq & TIMELOCK_TYPE) {\n\t\t// Convert granularity units back to seconds for timestamp.\n\t\tconst stamp = value * TIMELOCK_GRANULARITY;\n\t\t// Validate the timestamp value.\n\t\tif (stamp > 0xffffffff) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t`decoded timestamp ${stamp} exceeds 32-bit limit (max: ${0xffffffff})`\n\t\t\t);\n\t\t}\n\t\t// Return the decoded timelock.\n\t\treturn { mode: \"stamp\", stamp };\n\t} else {\n\t\t// Validate the height value.\n\t\tif (value > TIMELOCK_VALUE_MAX) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t`decoded height ${value} exceeds maximum (${TIMELOCK_VALUE_MAX})`\n\t\t\t);\n\t\t}\n\t\t// Return the decoded heightlock.\n\t\treturn { mode: \"height\", height: value };\n\t}\n}\n\n/* ===== [ Helpers ] ========================================================= */\n\n/**\n * Parses a sequence value into a number.\n *\n * @param sequence - The sequence value to parse.\n * @returns The parsed sequence value.\n * @throws Error if the sequence value is invalid.\n */\nfunction parse_sequence(sequence: number | string): number {\n\tconst seq = typeof sequence === \"string\" ? parseInt(sequence, 16) : sequence;\n\tif (!Number.isInteger(seq) || seq < 0 || seq > 0xffffffff) {\n\t\tthrow new ValidationError(\n\t\t\t`invalid sequence value: ${seq}. Must be an integer between 0 and 0xffffffff`\n\t\t);\n\t}\n\treturn seq;\n}\n\n/**\n * Parses a timestamp value into a 512-second granularity units.\n *\n * @param stamp - The timestamp value to parse.\n * @returns The parsed timestamp value.\n * @throws Error if the timestamp value is invalid.\n */\nfunction parse_stamp(stamp?: number): number {\n\tif (stamp === undefined || !Number.isInteger(stamp)) {\n\t\tthrow new ValidationError(`timestamp must be an integer, got: ${stamp}`);\n\t}\n\t// Convert timestamp to 512-second granularity units as per BIP-68.\n\tconst ts = Math.floor(stamp / TIMELOCK_GRANULARITY);\n\t// Validate the timestamp value.\n\tif (!Number.isInteger(ts) || ts < 0 || ts > TIMELOCK_VALUE_MAX) {\n\t\tthrow new ValidationError(\n\t\t\t`timelock value must be an integer between 0 and ${TIMELOCK_VALUE_MAX} (in 512-second increments)`\n\t\t);\n\t}\n\treturn ts;\n}\n\n/**\n * Parses a height value into a number.\n *\n * @param height - The height value to parse.\n * @returns The parsed height value.\n * @throws Error if the height value is invalid.\n */\nfunction parse_height(height?: number): number {\n\tif (\n\t\theight === undefined ||\n\t\t!Number.isInteger(height) ||\n\t\theight < 0 ||\n\t\theight > TIMELOCK_VALUE_MAX\n\t) {\n\t\tthrow new ValidationError(\n\t\t\t`heightlock value must be an integer between 0 and ${TIMELOCK_VALUE_MAX}, got: ${height}`\n\t\t);\n\t}\n\treturn height;\n}\n","/**\n * Script utility functions.\n *\n * Helper functions for script manipulation including size prefixing\n * and public key extraction.\n *\n * @module\n */\n\nimport { Buff } from \"@vbyte/buff\";\n\n/**\n * Prefix a script with its size as a varint.\n *\n * Adds a Bitcoin-style varint length prefix to a script.\n * Used when embedding scripts in transactions.\n *\n * @param script - Script bytes (hex string or Uint8Array)\n * @returns Hex string of the script prefixed with its length\n *\n * @example\n * ```typescript\n * const prefixed = prefix_script_size('76a914...88ac')\n * // Returns: '19' + '76a914...88ac' (0x19 = 25 bytes)\n * ```\n */\nexport function prefix_script_size(script: string | Uint8Array): string {\n\treturn Buff.bytes(script).prefix_varint(\"le\").hex;\n}\n\n/**\n * Extract x-only public keys from a script.\n *\n * Searches for 32-byte public keys followed by signature checking\n * opcodes (OP_CHECKSIG, OP_CHECKSIGVERIFY, or OP_CHECKSIGADD).\n * Useful for analyzing tapscripts to find all signing keys.\n *\n * @param script - Script bytes (hex string or Uint8Array)\n * @returns Array of 32-byte x-only public keys (hex strings)\n *\n * @example\n * ```typescript\n * // Script: <pubkey1> OP_CHECKSIG <pubkey2> OP_CHECKSIGADD\n * const pubkeys = parse_script_pubkeys(script)\n * // Returns: ['abc123...', 'def456...']\n * ```\n */\nexport function parse_script_pubkeys(script: string | Uint8Array): string[] {\n\t// Convert the script to a string if it's a Uint8Array\n\tconst scriptHex =\n\t\ttypeof script === \"string\" ? script : Buff.bytes(script).hex;\n\n\t// Define the regex pattern to match the specified pattern\n\t// 20 = pushdata byte for 32 bytes (0x20)\n\t// [0-9a-f]{64} = 32-byte hex string (64 hex characters)\n\t// (ac|ad|ba) = OP_CHECKSIG (0xac), OP_CHECKSIGVERIFY (0xad), or OP_CHECKSIGADD (0xba)\n\tconst pubkeyPattern = /20([0-9a-f]{64})(ac|ad|ba)/gi;\n\n\t// Find all matches in the script\n\tconst matches = [...scriptHex.matchAll(pubkeyPattern)];\n\n\t// Extract the public keys from the matches\n\treturn matches.map((match) => match[1]);\n}","/**\n * Transaction decoding utilities.\n *\n * Functions for decoding raw transaction bytes into structured data.\n * Handles both legacy and SegWit transaction formats.\n *\n * @module\n */\n\nimport { Stream } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/util\";\nimport { COINBASE, MAX_VARINT_SIZE } from \"@/const.js\";\nimport { DecodingError } from \"@/error.js\";\n\nimport type {\n\tTxCoinbaseInput,\n\tTxDecodedData,\n\tTxInput,\n\tTxOutput,\n\tTxVirtualInput,\n} from \"@/types/index.js\";\n\n/** Maximum transaction size in bytes (4MB, Bitcoin consensus limit) */\nconst MAX_TX_SIZE = 4_000_000;\n\n/** Maximum number of inputs/outputs per transaction */\nconst MAX_TX_ELEMENTS = 100_000;\n\n/**\n * Decode raw transaction bytes into structured data.\n *\n * Parses a raw Bitcoin transaction (hex or bytes) and returns\n * a TxDecodedData object containing version, inputs, outputs,\n * witness data, and locktime.\n *\n * @param txdata - Raw transaction as hex string or Uint8Array\n * @param use_segwit - Parse witness data if present (default: true)\n * @returns Decoded transaction data\n * @throws {DecodingError} If transaction is malformed or exceeds limits\n *\n * @example\n * ```typescript\n * const tx = decode_tx('0200000001...')\n * console.log(tx.version) // 2\n * console.log(tx.vin.length) // Number of inputs\n * ```\n */\nexport function decode_tx(\n\ttxdata: string | Uint8Array,\n\tuse_segwit = true,\n): TxDecodedData {\n\t// Assert the txdata is a bytes object.\n\tAssert.ok(\n\t\ttypeof txdata === \"string\" || txdata instanceof Uint8Array,\n\t\t\"txdata must be hex or bytes\",\n\t);\n\n\t// Check transaction size limit\n\tconst txSize = typeof txdata === \"string\" ? txdata.length / 2 : txdata.length;\n\tif (txSize > MAX_TX_SIZE) {\n\t\tthrow new DecodingError(\n\t\t\t`Transaction size ${txSize} exceeds maximum ${MAX_TX_SIZE} bytes`,\n\t\t);\n\t}\n\n\t// Setup a byte-stream.\n\tconst stream = new Stream(txdata);\n\t// Parse tx version.\n\tconst version = read_version(stream);\n\t// Check and enable any flags that are set.\n\tlet has_witness = check_witness_flag(stream);\n\t// If use_segwit is false, set has_witness to false.\n\thas_witness = use_segwit ? has_witness : false;\n\t// Parse our inputs and outputs.\n\tconst vin = read_inputs(stream);\n\tconst vout = read_outputs(stream);\n\t// If witness flag is set, parse witness data.\n\tif (has_witness) {\n\t\tfor (const txin of vin) {\n\t\t\ttxin.witness = read_witness(stream);\n\t\t}\n\t}\n\t// Parse locktime.\n\tconst locktime = read_locktime(stream);\n\t// Return transaction object with calculated fields.\n\treturn { version, vin, vout, locktime };\n}\n\nfunction read_version(stream: Stream): number {\n\treturn stream.read(4).reverse().to_num();\n}\n\nfunction check_witness_flag(stream: Stream): boolean {\n\tconst [marker, flag]: number[] = [...stream.peek(2)];\n\tif (marker === 0) {\n\t\tstream.read(2);\n\t\tif (flag === 1) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthrow new DecodingError(`Invalid witness flag: ${flag}`, 1);\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction read_inputs(stream: Stream): TxInput[] {\n\tconst inputs = [];\n\tconst vinCount = stream.read_varint();\n\tif (vinCount > MAX_TX_ELEMENTS) {\n\t\tthrow new DecodingError(\n\t\t\t`Input count ${vinCount} exceeds maximum ${MAX_TX_ELEMENTS}`,\n\t\t);\n\t}\n\tfor (let i = 0; i < vinCount; i++) {\n\t\tconst txinput = read_vin(stream);\n\t\tinputs.push(txinput);\n\t}\n\treturn inputs;\n}\n\nfunction read_vin(stream: Stream): TxInput {\n\tconst txid = stream.read(32).reverse().hex;\n\tconst vout = stream.read(4).reverse().num;\n\tconst script_sig = read_payload(stream);\n\tconst sequence = stream.read(4).reverse().num;\n\tconst witness: string[] = [];\n\tif (txid === COINBASE.TXID && vout === COINBASE.VOUT) {\n\t\treturn {\n\t\t\tcoinbase: script_sig,\n\t\t\tprevout: null,\n\t\t\tscript_sig: null,\n\t\t\tsequence,\n\t\t\ttxid,\n\t\t\tvout,\n\t\t\twitness,\n\t\t} as TxCoinbaseInput;\n\t} else {\n\t\treturn {\n\t\t\tcoinbase: null,\n\t\t\tprevout: null,\n\t\t\tscript_sig,\n\t\t\tsequence,\n\t\t\ttxid,\n\t\t\tvout,\n\t\t\twitness,\n\t\t} as TxVirtualInput;\n\t}\n}\n\nfunction read_outputs(stream: Stream): TxOutput[] {\n\tconst outputs = [];\n\tconst vcount = stream.read_varint();\n\tif (vcount > MAX_TX_ELEMENTS) {\n\t\tthrow new DecodingError(\n\t\t\t`Output count ${vcount} exceeds maximum ${MAX_TX_ELEMENTS}`,\n\t\t);\n\t}\n\tfor (let i = 0; i < vcount; i++) {\n\t\ttry {\n\t\t\toutputs.push(read_vout(stream));\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthrow new DecodingError(`Failed to decode output at index ${i}: ${message}`);\n\t\t}\n\t}\n\treturn outputs;\n}\n\nfunction read_vout(stream: Stream): TxOutput {\n\tconst value = stream.read(8).reverse().big;\n\tconst script_pk = read_payload(stream);\n\tAssert.exists(script_pk, \"failed to decode script_pk\");\n\treturn { value, script_pk };\n}\n\nfunction read_witness(stream: Stream): string[] {\n\tconst stack = [];\n\tconst count = stream.read_varint();\n\tif (count > MAX_TX_ELEMENTS) {\n\t\tthrow new DecodingError(\n\t\t\t`Witness element count ${count} exceeds maximum ${MAX_TX_ELEMENTS}`,\n\t\t);\n\t}\n\tfor (let i = 0; i < count; i++) {\n\t\tconst element = read_payload(stream);\n\t\tif (element === null) {\n\t\t\tthrow new DecodingError(`Failed to decode witness element at index ${i}`);\n\t\t}\n\t\tstack.push(element);\n\t}\n\treturn stack;\n}\n\nexport function read_payload(stream: Stream): string | null {\n\tconst size = stream.read_varint(\"le\");\n\tif (size > MAX_VARINT_SIZE) {\n\t\tthrow new DecodingError(\n\t\t\t`Payload size ${size} exceeds maximum ${MAX_VARINT_SIZE}`,\n\t\t);\n\t}\n\treturn size > 0 ? stream.read(size).hex : null;\n}\n\nfunction read_locktime(stream: Stream): number {\n\treturn stream.read(4).reverse().to_num();\n}\n","/** A special constant with type `never` */\nexport const NEVER = Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepString = step.toString();\n let stepDecCount = (stepString.split(\".\")[1] || \"\").length;\n if (stepDecCount === 0 && /\\d?e-\\d?/.test(stepString)) {\n const match = stepString.match(/\\d?e-(\\d?)/);\n if (match?.[1]) {\n stepDecCount = Number.parseInt(match[1]);\n }\n }\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nconst EVALUATING = Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = cached(() => {\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: [], // delete existing checks\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\";\n full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues });\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues });\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, issue.path));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\nexport const cuid = /^[cC][^\\s-]{8,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emoji = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\n// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// const dateSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const time = timeSource({ precision: args.precision });\n const opts = [\"Z\"];\n if (args.local)\n opts.push(\"\");\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n if (def.value < curr) {\n if (def.inclusive)\n bag.maximum = def.value;\n else\n bag.exclusiveMaximum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n if (def.value > curr) {\n if (def.inclusive)\n bag.minimum = def.value;\n else\n bag.exclusiveMinimum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n var _a;\n (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n });\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n if (isInt)\n bag.pattern = regexes.integer;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.size;\n bag.maximum = def.size;\n bag.size = def.size;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.length;\n bag.maximum = def.length;\n bag.length = def.length;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n if (def.pattern) {\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(def.pattern);\n }\n });\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.mime = def.mime;\n });\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export class Doc {\n constructor(args = []) {\n this.content = [];\n this.indent = 0;\n if (this)\n this.args = args;\n }\n indented(fn) {\n this.indent += 1;\n fn(this);\n this.indent -= 1;\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const args = this?.args;\n const content = this?.content ?? [``];\n const lines = [...content.map((x) => ` ${x}`)];\n // console.log(lines.join(\"\\n\"));\n return new F(...args, lines.join(\"\\n\"));\n }\n}\n","export const version = {\n major: 4,\n minor: 3,\n patch: 6,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\n }\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer\n // inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary\n // initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n // Lazy initialize ~standard to avoid creating objects for every schema\n util.defineLazy(inst, \"~standard\", () => ({\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\n },\n vendor: \"zod\",\n version: 1,\n }));\n});\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n // @ts-ignore\n const url = new URL(trimmed);\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n // Set the output value based on normalize flag\n if (def.normalize) {\n // Use normalized URL\n payload.value = url.href;\n }\n else {\n // Preserve the original input (trimmed)\n payload.value = trimmed;\n }\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv4`;\n});\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv6`;\n inst._zod.check = (payload) => {\n try {\n // @ts-ignore\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n const parts = payload.value.split(\"/\");\n try {\n if (parts.length !== 2)\n throw new Error();\n const [address, prefix] = parts;\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n // @ts-ignore\n new URL(`http://[${address}]`);\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64\";\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64url\";\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? \"Infinity\"\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = Array(input.length);\n const proms = [];\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalOut) {\n if (result.issues.length) {\n // For optional-out schemas, ignore errors on absent keys\n if (isOptionalOut && !(key in input)) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (result.value === undefined) {\n if (key in input) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n // iterate over input keys\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const isOptionalOut = _catchall.optout === \"optional\";\n for (const key in input) {\n if (keySet.has(key))\n continue;\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalOut);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n // const sh = def.shape;\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n if (!desc?.get) {\n const sh = def.shape;\n Object.defineProperty(def, \"shape\", {\n get: () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", {\n value: newSh,\n });\n return newSh;\n },\n });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n const isOptionalOut = el._zod.optout === \"optional\";\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalOut);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {};`);\n for (const key of normalized.keys) {\n const id = ids[key];\n const k = util.esc(key);\n const schema = shape[key];\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(key)};`);\n if (isOptionalOut) {\n // For optional-out schemas, ignore errors on absent keys\n doc.write(`\n if (${id}.issues.length) {\n if (${k} in input) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const single = def.options.length === 1;\n const first = def.options[0]._zod.run;\n inst._zod.parse = (payload, ctx) => {\n if (single) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const successes = results.filter((r) => r.issues.length === 0);\n if (successes.length === 1) {\n final.value = successes[0].value;\n return final;\n }\n if (successes.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const single = def.options.length === 1;\n const first = def.options[0]._zod.run;\n inst._zod.parse = (payload, ctx) => {\n if (single) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n if (def.unionFallback) {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nfunction mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) report each key as unrecognized\n const unrecKeys = new Map();\n let unrecIssue;\n for (const iss of left.issues) {\n if (iss.code === \"unrecognized_keys\") {\n unrecIssue ?? (unrecIssue = iss);\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).l = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n for (const iss of right.issues) {\n if (iss.code === \"unrecognized_keys\") {\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).r = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n // Report only keys unrecognized by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length && unrecIssue) {\n result.issues.push({ ...unrecIssue, keys: bothKeys });\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = [];\n const proms = [];\n const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== \"optional\");\n const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex;\n if (!def.rest) {\n const tooBig = input.length > items.length;\n const tooSmall = input.length < optStart - 1;\n if (tooBig || tooSmall) {\n payload.issues.push({\n ...(tooBig\n ? { code: \"too_big\", maximum: items.length, inclusive: true }\n : { code: \"too_small\", minimum: items.length }),\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n }\n let i = -1;\n for (const item of items) {\n i++;\n if (i >= input.length)\n if (i >= optStart)\n continue;\n const result = item._zod.run({\n value: input[i],\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n if (def.rest) {\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({\n value: el,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n const values = def.keyType._zod.values;\n if (values) {\n payload.value = {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[key] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[key] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key)\n // This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = new Map();\n for (const [key, value] of input) {\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = new Set();\n for (const item of input) {\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n if (def.values.length === 0) {\n throw new Error(\"Cannot create literal schema with no valid values\");\n }\n const values = new Set(def.values);\n inst._zod.values = values;\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(result, input) {\n if (result.issues.length && input === undefined) {\n return { issues: [], value: undefined };\n }\n return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, payload.value));\n return handleOptionalResult(result, payload.value);\n }\n if (payload.value === undefined) {\n return payload;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"pattern\", () => def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => {\n const v = def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n if (left.issues.length) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n payload.value = Object.freeze(payload.value);\n return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._def = def;\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n return function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n };\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n };\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // let _innerType!: any;\n // util.defineLazy(def, \"getter\", () => {\n // if (!_innerType) {\n // _innerType = def.getter();\n // }\n // return () => _innerType;\n // });\n util.defineLazy(inst._zod, \"innerType\", () => def.getter());\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n util.defineLazy(inst._zod, \"optout\", () => inst._zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n external: params?.external ?? undefined,\n };\n}\nexport function process(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n process(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n Object.assign(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && result.schema._prefault)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema\n // defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes\n // multiple schemas map to the same seen object.\n // e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${id}` };\n }\n if (entry[1] === root) {\n return { ref: \"#\" };\n }\n // self-contained schema\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + defId };\n };\n // stored cached version in `def` property\n // remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema\n // or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n // biome-ignore lint:\n continue;\n }\n }\n }\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n Object.assign(schema, refSchema);\n }\n // restore child's own properties (child wins)\n Object.assign(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema\n // This handles cases like: readonly().meta({id}).describe()\n // where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n Object.assign(result, root.def ?? root.schema);\n // build defs object\n const defs = ctx.external?.defs ?? {};\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n defs[seen.defId] = seen.def;\n }\n }\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed\n // each call to finalize() is functionally independent\n // though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\nimport { getEnumValues } from \"./util.js\";\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n .bag;\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // JSON Schema format: \"time\" requires a full time with offset or Z\n // z.iso.time() does not include timezone information, so format: \"time\" should never be used\n if (format === \"time\") {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const regexes = [...patterns];\n if (regexes.length === 1)\n json.pattern = regexes[0].source;\n else if (regexes.length > 1) {\n json.allOf = [\n ...regexes.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n if (typeof format === \"string\" && format.includes(\"int\"))\n json.type = \"integer\";\n else\n json.type = \"number\";\n if (typeof exclusiveMinimum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n if (typeof minimum === \"number\") {\n json.minimum = minimum;\n if (typeof exclusiveMinimum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMinimum >= minimum)\n delete json.minimum;\n else\n delete json.exclusiveMinimum;\n }\n }\n if (typeof exclusiveMaximum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n if (typeof maximum === \"number\") {\n json.maximum = maximum;\n if (typeof exclusiveMaximum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMaximum <= maximum)\n delete json.maximum;\n else\n delete json.exclusiveMaximum;\n }\n }\n if (typeof multipleOf === \"number\")\n json.multipleOf = multipleOf;\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt cannot be represented in JSON Schema\");\n }\n};\nexport const symbolProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Symbols cannot be represented in JSON Schema\");\n }\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Undefined cannot be represented in JSON Schema\");\n }\n};\nexport const voidProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Void cannot be represented in JSON Schema\");\n }\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Date cannot be represented in JSON Schema\");\n }\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, _params) => {\n const def = schema._zod.def;\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n }\n else {\n // do not add to vals\n }\n }\n else if (typeof val === \"bigint\") {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n }\n else {\n vals.push(Number(val));\n }\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"NaN cannot be represented in JSON Schema\");\n }\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const file = {\n type: \"string\",\n format: \"binary\",\n contentEncoding: \"binary\",\n };\n const { minimum, maximum, mime } = schema._zod.bag;\n if (minimum !== undefined)\n file.minLength = minimum;\n if (maximum !== undefined)\n file.maxLength = maximum;\n if (mime) {\n if (mime.length === 1) {\n file.contentMediaType = mime[0];\n Object.assign(_json, file);\n }\n else {\n Object.assign(_json, file); // shared props at root\n _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n }\n }\n else {\n Object.assign(_json, file);\n }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Custom types cannot be represented in JSON Schema\");\n }\n};\nexport const functionProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Function types cannot be represented in JSON Schema\");\n }\n};\nexport const transformProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Transforms cannot be represented in JSON Schema\");\n }\n};\nexport const mapProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Map cannot be represented in JSON Schema\");\n }\n};\nexport const setProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Set cannot be represented in JSON Schema\");\n }\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = process(def.element, ctx, { ...params, path: [...params.path, \"items\"] });\n};\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n json.properties = {};\n const shape = def.shape;\n for (const key in shape) {\n json.properties[key] = process(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n });\n }\n // required keys\n const allKeys = new Set(Object.keys(shape));\n const requiredKeys = new Set([...allKeys].filter((key) => {\n const v = def.shape[key]._zod;\n if (ctx.io === \"input\") {\n return v.optin === undefined;\n }\n else {\n return v.optout === undefined;\n }\n }));\n if (requiredKeys.size > 0) {\n json.required = Array.from(requiredKeys);\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = process(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)\n // This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = process(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = process(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? process(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (rest) {\n json.items = rest;\n }\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n json.minItems = prefixItems.length;\n if (!rest) {\n json.maxItems = prefixItems.length;\n }\n }\n else {\n json.items = prefixItems;\n if (rest) {\n json.additionalItems = rest;\n }\n }\n // length\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties\n // This correctly represents \"only validate keys matching the pattern\" semantics\n // and composes well with allOf (intersections)\n const keyType = def.keyType;\n const keyBag = keyType._zod.bag;\n const patterns = keyBag?.patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n json.patternProperties[pattern.source] = valueSchema;\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = process(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n }\n json.additionalProperties = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n if (keyValues) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues;\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.default = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io === \"input\")\n json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const innerType = ctx.io === \"input\" ? (def.in._zod.def.type === \"transform\" ? def.out : def.in) : def.out;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n process(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n schemas[key] = finalize(ctx, schema);\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n process(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function datetime(params) {\n return core._isoDateTime(ZodISODateTime, params);\n}\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function date(params) {\n return core._isoDate(ZodISODate, params);\n}\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function time(params) {\n return core._isoTime(ZodISOTime, params);\n}\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function duration(params) {\n return core._isoDuration(ZodISODuration, params);\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = core.$constructor(\"ZodError\", initializer, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport * as checks from \"./checks.js\";\nimport * as iso from \"./iso.js\";\nimport * as parse from \"./parse.js\";\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n core.$ZodType.init(inst, def);\n Object.assign(inst[\"~standard\"], {\n jsonSchema: {\n input: createStandardJSONSchemaMethod(inst, \"input\"),\n output: createStandardJSONSchemaMethod(inst, \"output\"),\n },\n });\n inst.toJSONSchema = createToJSONSchemaMethod(inst, {});\n inst.def = def;\n inst.type = def.type;\n Object.defineProperty(inst, \"_def\", { value: def });\n // base methods\n inst.check = (...checks) => {\n return inst.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...checks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), {\n parent: true,\n });\n };\n inst.with = inst.check;\n inst.clone = (def, params) => core.clone(inst, def, params);\n inst.brand = () => inst;\n inst.register = ((reg, meta) => {\n reg.add(inst, meta);\n return inst;\n });\n // parsing\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.spa = inst.safeParseAsync;\n // encoding/decoding\n inst.encode = (data, params) => parse.encode(inst, data, params);\n inst.decode = (data, params) => parse.decode(inst, data, params);\n inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);\n inst.decodeAsync = async (data, params) => parse.decodeAsync(inst, data, params);\n inst.safeEncode = (data, params) => parse.safeEncode(inst, data, params);\n inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);\n inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);\n inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);\n // refinements\n inst.refine = (check, params) => inst.check(refine(check, params));\n inst.superRefine = (refinement) => inst.check(superRefine(refinement));\n inst.overwrite = (fn) => inst.check(checks.overwrite(fn));\n // wrappers\n inst.optional = () => optional(inst);\n inst.exactOptional = () => exactOptional(inst);\n inst.nullable = () => nullable(inst);\n inst.nullish = () => optional(nullable(inst));\n inst.nonoptional = (params) => nonoptional(inst, params);\n inst.array = () => array(inst);\n inst.or = (arg) => union([inst, arg]);\n inst.and = (arg) => intersection(inst, arg);\n inst.transform = (tx) => pipe(inst, transform(tx));\n inst.default = (def) => _default(inst, def);\n inst.prefault = (def) => prefault(inst, def);\n // inst.coalesce = (def, params) => coalesce(inst, def, params);\n inst.catch = (params) => _catch(inst, params);\n inst.pipe = (target) => pipe(inst, target);\n inst.readonly = () => readonly(inst);\n // meta\n inst.describe = (description) => {\n const cl = inst.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n };\n Object.defineProperty(inst, \"description\", {\n get() {\n return core.globalRegistry.get(inst)?.description;\n },\n configurable: true,\n });\n inst.meta = (...args) => {\n if (args.length === 0) {\n return core.globalRegistry.get(inst);\n }\n const cl = inst.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n };\n // helpers\n inst.isOptional = () => inst.safeParse(undefined).success;\n inst.isNullable = () => inst.safeParse(null).success;\n inst.apply = (fn) => fn(inst);\n return inst;\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n const bag = inst._zod.bag;\n inst.format = bag.format ?? null;\n inst.minLength = bag.minimum ?? null;\n inst.maxLength = bag.maximum ?? null;\n // validations\n inst.regex = (...args) => inst.check(checks.regex(...args));\n inst.includes = (...args) => inst.check(checks.includes(...args));\n inst.startsWith = (...args) => inst.check(checks.startsWith(...args));\n inst.endsWith = (...args) => inst.check(checks.endsWith(...args));\n inst.min = (...args) => inst.check(checks.minLength(...args));\n inst.max = (...args) => inst.check(checks.maxLength(...args));\n inst.length = (...args) => inst.check(checks.length(...args));\n inst.nonempty = (...args) => inst.check(checks.minLength(1, ...args));\n inst.lowercase = (params) => inst.check(checks.lowercase(params));\n inst.uppercase = (params) => inst.check(checks.uppercase(params));\n // transforms\n inst.trim = () => inst.check(checks.trim());\n inst.normalize = (...args) => inst.check(checks.normalize(...args));\n inst.toLowerCase = () => inst.check(checks.toLowerCase());\n inst.toUpperCase = () => inst.check(checks.toUpperCase());\n inst.slugify = () => inst.check(checks.slugify());\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n inst.email = (params) => inst.check(core._email(ZodEmail, params));\n inst.url = (params) => inst.check(core._url(ZodURL, params));\n inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params));\n inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params));\n inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params));\n inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params));\n inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params));\n inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params));\n inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params));\n inst.ulid = (params) => inst.check(core._ulid(ZodULID, params));\n inst.base64 = (params) => inst.check(core._base64(ZodBase64, params));\n inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params));\n inst.xid = (params) => inst.check(core._xid(ZodXID, params));\n inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params));\n inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params));\n inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params));\n inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params));\n inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params));\n inst.e164 = (params) => inst.check(core._e164(ZodE164, params));\n // iso\n inst.datetime = (params) => inst.check(iso.datetime(params));\n inst.date = (params) => inst.check(iso.date(params));\n inst.time = (params) => inst.check(iso.time(params));\n inst.duration = (params) => inst.check(iso.duration(params));\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: /^https?$/,\n hostname: core.regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.int = (params) => inst.check(int(params));\n inst.safe = (params) => inst.check(int(params));\n inst.positive = (params) => inst.check(checks.gt(0, params));\n inst.nonnegative = (params) => inst.check(checks.gte(0, params));\n inst.negative = (params) => inst.check(checks.lt(0, params));\n inst.nonpositive = (params) => inst.check(checks.lte(0, params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n inst.step = (value, params) => inst.check(checks.multipleOf(value, params));\n // inst.finite = (params) => inst.check(core.finite(params));\n inst.finite = () => inst;\n const bag = inst._zod.bag;\n inst.minValue =\n Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n inst.maxValue =\n Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n inst.isFinite = true;\n inst.format = bag.format ?? null;\n});\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.positive = (params) => inst.check(checks.gt(BigInt(0), params));\n inst.negative = (params) => inst.check(checks.lt(BigInt(0), params));\n inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params));\n inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n const bag = inst._zod.bag;\n inst.minValue = bag.minimum ?? null;\n inst.maxValue = bag.maximum ?? null;\n inst.format = bag.format ?? null;\n});\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\n// int64\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\n// uint64\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n const c = inst._zod.bag;\n inst.minDate = c.minimum ? new Date(c.minimum) : null;\n inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n inst.min = (minLength, params) => inst.check(checks.minLength(minLength, params));\n inst.nonempty = (params) => inst.check(checks.minLength(1, params));\n inst.max = (maxLength, params) => inst.check(checks.maxLength(maxLength, params));\n inst.length = (len, params) => inst.check(checks.length(len, params));\n inst.unwrap = () => inst.element;\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.defineLazy(inst, \"shape\", () => {\n return def.shape;\n });\n inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));\n inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall });\n inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });\n inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });\n inst.extend = (incoming) => {\n return util.extend(inst, incoming);\n };\n inst.safeExtend = (incoming) => {\n return util.safeExtend(inst, incoming);\n };\n inst.merge = (other) => util.merge(inst, other);\n inst.pick = (mask) => util.pick(inst, mask);\n inst.omit = (mask) => util.omit(inst, mask);\n inst.partial = (...args) => util.partial(ZodOptional, inst, args[0]);\n inst.required = (...args) => util.required(ZodNonOptional, inst, args[0]);\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n inst.rest = (rest) => inst.clone({\n ...inst._zod.def,\n rest: rest,\n });\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n const k = core.clone(keyType);\n k._zod.values = undefined;\n return new ZodRecord({\n type: \"record\",\n keyType: k,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n inst.options = Object.values(def.entries);\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n payload.value = output;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn) {\n return core._superRefine(fn);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodCustom({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\n// /** @deprecated Use `z.pipe()` and `z.transform()` instead. */\nexport function preprocess(fn, schema) {\n return pipe(transform(fn), schema);\n}\n","import { z } from \"zod\";\n\ntype Literal = z.infer<typeof literal>;\ntype Json = Literal | { [key: string]: Json } | Json[];\n\nexport const big = z.bigint();\nexport const bool = z.boolean();\nexport const date = z.date();\nexport const num = z\n\t.number()\n\t.min(Number.MIN_SAFE_INTEGER)\n\t.max(Number.MAX_SAFE_INTEGER);\nexport const int = num.int();\nexport const u8a = z.instanceof(Uint8Array);\nexport const str = z.string();\nexport const stamp = int.min(500_000_000);\nexport const any = z.any();\nexport const zod = z;\nexport const char = int.min(0).max(0xff);\nexport const short = int.min(0).max(0xffff);\nexport const uint = int.min(0).max(0xffffffff);\n\nexport const float = z.number().refine((e) => String(e).includes(\".\"));\n\nexport const float2 = float.refine((e) => {\n\tconst parts = String(e).split(\".\").at(1);\n\treturn parts !== undefined && parts.length <= 2;\n});\n\nexport const hex = z\n\t.string()\n\t.regex(/^[0-9a-fA-F]*$/)\n\t.refine((e) => e.length % 2 === 0);\n\nexport const literal = z.union([z.string(), z.number(), z.boolean(), z.null()]);\n\nexport const json: z.ZodType<Json> = z.lazy(() =>\n\tz.union([literal, z.array(json), z.record(str, json)]),\n);\n\nexport const u8a20 = u8a.refine((e) => e.length === 20);\nexport const u8a32 = u8a.refine((e) => e.length === 32);\nexport const u8a33 = u8a.refine((e) => e.length === 33);\nexport const u8a64 = u8a.refine((e) => e.length === 64);\n\nexport const hex20 = hex.refine((e) => e.length === 40);\nexport const hex32 = hex.refine((e) => e.length === 64);\nexport const hex33 = hex.refine((e) => e.length === 66);\nexport const hex64 = hex.refine((e) => e.length === 128);\n\nexport const bytes = z.union([hex, u8a]);\nexport const byte32 = z.union([hex32, u8a32]);\nexport const byte33 = z.union([hex33, u8a33]);\nexport const byte64 = z.union([hex64, u8a64]);\n\nexport const base58 = z.string().regex(/^[1-9A-HJ-NP-Za-km-z]+$/);\nexport const base64 = z.string().regex(/^[a-zA-Z0-9+/]+={0,2}$/);\nexport const base64url = z.string().regex(/^[a-zA-Z0-9\\-_]+={0,2}$/);\nexport const bech32 = z\n\t.string()\n\t.regex(/^[a-z]+1[023456789acdefghjklmnpqrstuvwxyz]+$/);\n","import { z } from \"zod\";\n\nimport { byte32, uint } from \"./base.js\";\n\nexport const taptree = z.union([z.array(byte32), byte32]);\n\nexport const config = z.object({\n\tpubkey: byte32,\n\tleaves: taptree.array().optional(),\n\ttarget: byte32.optional(),\n\tversion: uint.optional(),\n});\n","import { z } from \"zod\";\nimport type { TxOutput, TxOutputTemplate } from \"@/types/index.js\";\nimport { hex, hex32, uint } from \"./base.js\";\n\nconst sats = z.bigint().min(0n).max(2_100_000_000_000_000n);\n\nexport const tx_output = z.object({\n\tvalue: sats,\n\tscript_pk: hex,\n}) satisfies z.ZodType<TxOutput>;\n\nexport const tx_input = z.object({\n\tcoinbase: hex.nullable(),\n\ttxid: hex32,\n\tvout: uint,\n\tprevout: tx_output.nullable(),\n\tscript_sig: hex.nullable(),\n\tsequence: uint,\n\twitness: z.array(hex),\n});\n\nexport const tx_data = z.object({\n\tversion: uint,\n\tvin: z.array(tx_input),\n\tvout: z.array(tx_output),\n\tlocktime: uint,\n});\n\nexport const vout_template = tx_output.extend({\n\tvalue: z.union([uint, sats]),\n}) satisfies z.ZodType<TxOutputTemplate>;\n\nexport const vin_template = tx_input.extend({\n\tcoinbase: hex.nullable().optional(),\n\tprevout: vout_template.nullable().optional(),\n\tscript_sig: hex.nullable().optional(),\n\tsequence: z.union([hex, uint]).optional(),\n\twitness: z.array(hex).optional(),\n});\n\nexport const tx_template = z.object({\n\tversion: uint.optional(),\n\tvin: z.array(vin_template),\n\tvout: z.array(vout_template),\n\tlocktime: uint.optional(),\n});\n","import * as Schema from \"@/schema/index.js\";\nimport { ValidationError } from \"@/error.js\";\nimport type { ZodError } from \"zod\";\n\nimport type {\n\tTxData,\n\tTxInput,\n\tTxInputTemplate,\n\tTxOutput,\n\tTxOutputTemplate,\n\tTxSpendData,\n\tTxSpendInput,\n\tTxTemplate,\n} from \"@/types/index.js\";\n\n/**\n * Format a Zod error into a user-friendly message.\n * @internal\n */\nfunction format_zod_error(error: ZodError): string {\n\tconst issues = error.issues.map((issue) => {\n\t\tconst path = issue.path.length > 0 ? `${issue.path.join(\".\")}: ` : \"\";\n\t\treturn `${path}${issue.message}`;\n\t});\n\treturn issues.join(\"; \");\n}\n\nexport function assert_tx_template(\n\ttxdata: unknown,\n): asserts txdata is TxTemplate {\n\tconst result = Schema.tx.tx_template.safeParse(txdata);\n\tif (!result.success) {\n\t\tthrow new ValidationError(`invalid transaction template: ${format_zod_error(result.error)}`);\n\t}\n}\n\nexport function assert_has_prevouts(\n\tvin: TxInput[],\n): asserts vin is TxSpendInput[] {\n\tconst missingIdx = vin.findIndex((txin) => txin.prevout === null || txin.prevout === undefined);\n\tif (missingIdx !== -1) {\n\t\tthrow new ValidationError(\n\t\t\t`transaction input at index ${missingIdx} is missing prevout data. ` +\n\t\t\t`Prevout (previous output) is required for signing`\n\t\t);\n\t}\n}\n\nexport function assert_tx_data(txdata: unknown): asserts txdata is TxData {\n\tconst result = Schema.tx.tx_data.safeParse(txdata);\n\tif (!result.success) {\n\t\tthrow new ValidationError(`invalid transaction data: ${format_zod_error(result.error)}`);\n\t}\n}\n\nexport function assert_tx_spend_data(\n\ttxdata: unknown,\n): asserts txdata is TxSpendData {\n\t// Assert the txdata is a valid tx data object.\n\tassert_tx_data(txdata);\n\t// Assert the txdata has prevouts.\n\tassert_has_prevouts(txdata.vin);\n}\n\nexport function assert_tx_input(\n\ttx_input: unknown,\n): asserts tx_input is TxInput {\n\tconst result = Schema.tx.tx_input.safeParse(tx_input);\n\tif (!result.success) {\n\t\tthrow new ValidationError(`invalid transaction input: ${format_zod_error(result.error)}`);\n\t}\n}\n\nexport function assert_tx_output(\n\ttx_output: unknown,\n): asserts tx_output is TxOutput {\n\tconst result = Schema.tx.tx_output.safeParse(tx_output);\n\tif (!result.success) {\n\t\tthrow new ValidationError(`invalid transaction output: ${format_zod_error(result.error)}`);\n\t}\n}\n\nexport function assert_vin_template(\n\tvin: unknown,\n): asserts vin is TxInputTemplate {\n\tconst result = Schema.tx.vin_template.safeParse(vin);\n\tif (!result.success) {\n\t\tthrow new ValidationError(`invalid input template: ${format_zod_error(result.error)}`);\n\t}\n}\n\nexport function assert_vout_template(\n\tvout: unknown,\n): asserts vout is TxOutputTemplate {\n\tconst result = Schema.tx.vout_template.safeParse(vout);\n\tif (!result.success) {\n\t\tthrow new ValidationError(`invalid output template: ${format_zod_error(result.error)}`);\n\t}\n}\n","/**\n * Transaction encoding utilities.\n *\n * Functions for serializing transaction data into raw bytes for\n * broadcasting or signature hash calculation.\n *\n * @module\n */\n\nimport { Buff } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/util\";\nimport { COINBASE } from \"@/const.js\";\nimport type { TxData, TxInput, TxOutput } from \"@/types/index.js\";\nimport { assert_tx_data } from \"./validate.js\";\n\n/**\n * Encode a complete transaction to raw bytes.\n *\n * @param txdata - Transaction data object\n * @param use_segwit - Include witness data (default: true)\n * @returns Serialized transaction as Buff\n *\n * @example\n * ```typescript\n * const rawTx = encode_tx(txdata)\n * console.log(rawTx.hex) // Transaction hex for broadcasting\n * ```\n */\nexport function encode_tx(txdata: TxData, use_segwit = true): Buff {\n\t// Assert the txdata is a valid tx data object.\n\tassert_tx_data(txdata);\n\t// Unpack the transaction data.\n\tconst { version, vin, vout, locktime } = txdata;\n\t// Create a buffer for the transaction.\n\tconst buffer: Buff[] = [encode_tx_version(version)];\n\t// If the transaction is a segwit transaction,\n\tif (use_segwit) {\n\t\t// Add the segwit marker to the buffer.\n\t\tbuffer.push(Buff.hex(\"0001\"));\n\t}\n\t// Add the inputs to the buffer.\n\tbuffer.push(encode_tx_inputs(vin));\n\t// Add the outputs to the buffer.\n\tbuffer.push(encode_tx_outputs(vout));\n\t// If the transaction is a segwit transaction,\n\tif (use_segwit) {\n\t\t// For each input in the transaction,\n\t\tfor (const input of vin) {\n\t\t\t// Add the witness data to the buffer.\n\t\t\tbuffer.push(encode_vin_witness(input.witness));\n\t\t}\n\t}\n\t// Add the locktime to the buffer.\n\tbuffer.push(encode_tx_locktime(locktime));\n\t// Return the buffer as a single payload.\n\treturn Buff.join(buffer);\n}\n\n/**\n * Encode transaction version as 4-byte little-endian.\n * @param num - Version number (typically 1 or 2)\n * @returns Encoded version bytes\n */\nexport function encode_tx_version(num: number): Buff {\n\t// Encode the transaction version as a 4-byte little-endian number.\n\treturn Buff.num(num, 4).reverse();\n}\n\n/**\n * Encode input txid as 32-byte little-endian.\n * @param txid - Transaction ID (64 hex characters)\n * @returns Encoded txid bytes (reversed for wire format)\n */\nexport function encode_txin_txid(txid: string): Buff {\n\t// Encode the transaction ID as a 32-byte little-endian number.\n\treturn Buff.hex(txid, 32).reverse();\n}\n\n/**\n * Encode input vout index as 4-byte little-endian.\n * @param vout - Output index being spent\n * @returns Encoded vout bytes\n */\nexport function encode_txin_vout(vout: number): Buff {\n\t// Encode the output index as a 4-byte little-endian number.\n\treturn Buff.num(vout, 4).reverse();\n}\n\n/**\n * Encode input sequence number as 4-byte little-endian.\n * @param sequence - Sequence number (affects RBF and relative timelocks)\n * @returns Encoded sequence bytes\n */\nexport function encode_txin_sequence(sequence: number): Buff {\n\t// Encode the sequence number as a 4-byte little-endian number.\n\treturn Buff.num(sequence, 4).reverse();\n}\n\n/**\n * Encode all transaction inputs with varint length prefix.\n * @param vin - Array of transaction inputs\n * @returns Encoded inputs with count prefix\n */\nexport function encode_tx_inputs(vin: TxInput[]): Buff {\n\t// Create a buffer for the inputs, starting with the array length.\n\tconst raw: Buff[] = [Buff.create_varint(vin.length, \"le\")];\n\t// For each input in the array,\n\tfor (const input of vin) {\n\t\t// Encode the input, and add it to the buffer.\n\t\traw.push(encode_vin(input));\n\t}\n\t// Return the buffer as a single payload.\n\treturn Buff.join(raw);\n}\n\n/**\n * Encode a single transaction input.\n * Handles both coinbase and regular inputs.\n * @param txin - Transaction input\n * @returns Encoded input (txid + vout + scriptSig + sequence)\n */\nexport function encode_vin(txin: TxInput): Buff {\n\t// If the input is a coinbase,\n\tif (txin.coinbase !== null) {\n\t\t// Encode and return the coinbase as a single payload.\n\t\treturn Buff.join([\n\t\t\tencode_txin_txid(COINBASE.TXID),\n\t\t\tencode_txin_vout(COINBASE.VOUT),\n\t\t\tencode_script_data(txin.coinbase),\n\t\t\tencode_txin_sequence(txin.sequence),\n\t\t]);\n\t} else {\n\t\t// Encode and return the input as a single payload.\n\t\treturn Buff.join([\n\t\t\tencode_txin_txid(txin.txid),\n\t\t\tencode_txin_vout(txin.vout),\n\t\t\tencode_script_data(txin.script_sig),\n\t\t\tencode_txin_sequence(txin.sequence),\n\t\t]);\n\t}\n}\n\n/**\n * Encode output value as 8-byte little-endian.\n * @param value - Amount in satoshis\n * @returns Encoded value bytes\n */\nexport function encode_vout_value(value: bigint): Buff {\n\t// Encode the value as an 8-byte little-endian number.\n\treturn Buff.big(value, 8).reverse();\n}\n\n/**\n * Encode all transaction outputs with varint length prefix.\n * @param vout - Array of transaction outputs\n * @returns Encoded outputs with count prefix\n */\nexport function encode_tx_outputs(vout: TxOutput[]): Buff {\n\t// Create a buffer for the outputs, starting with the array length.\n\tconst buffer: Buff[] = [Buff.create_varint(vout.length, \"le\")];\n\t// For each output in the array,\n\tfor (const output of vout) {\n\t\t// Encode the output, and add it to the buffer.\n\t\tbuffer.push(encode_tx_vout(output));\n\t}\n\t// Return the buffer as a single payload.\n\treturn Buff.join(buffer);\n}\n\n/**\n * Encode a single transaction output.\n * @param txout - Transaction output\n * @returns Encoded output (value + scriptPubKey)\n */\nexport function encode_tx_vout(txout: TxOutput): Buff {\n\t// Get the value and script pubkey from the output.\n\tconst { value, script_pk } = txout;\n\t// Return the data encoded as a single payload.\n\treturn Buff.join([encode_vout_value(value), encode_script_data(script_pk)]);\n}\n\n/**\n * Encode witness data for a single input.\n * @param data - Array of witness elements (hex strings)\n * @returns Encoded witness stack with element count prefix\n */\nexport function encode_vin_witness(data: string[]): Buff {\n\t// Create a buffer for the witness data, starting with the array length.\n\tconst buffer: Buff[] = [Buff.create_varint(data.length)];\n\t// For each parameter in the witness array,\n\tfor (const param of data) {\n\t\t// Encode the parameter, and add it to the buffer.\n\t\tbuffer.push(encode_script_data(param));\n\t}\n\t// Return the buffer as a single payload.\n\treturn Buff.join(buffer);\n}\n\n/**\n * Encode transaction locktime as 4-byte little-endian.\n * @param locktime - Block height or unix timestamp\n * @returns Encoded locktime bytes\n */\nexport function encode_tx_locktime(locktime: number): Buff {\n\t// Encode the locktime as a 4-byte little-endian number.\n\treturn Buff.num(locktime, 4).reverse();\n}\n\n/**\n * Encode script data with varint length prefix.\n * @param script - Script hex string, or null for empty script\n * @returns Encoded script with length prefix (or 0x00 for null)\n */\nexport function encode_script_data(script: string | null): Buff {\n\t// If the script is not null,\n\tif (script !== null) {\n\t\t// Assert that the script is a hex string.\n\t\tAssert.is_hex(script);\n\t\t// Encode the script, and add it to the buffer.\n\t\treturn Buff.hex(script).prefix_varint(\"le\");\n\t} else {\n\t\t// Return a single byte of zero.\n\t\treturn Buff.hex(\"00\");\n\t}\n}\n","/**\n * Transaction parsing utilities.\n *\n * Functions for parsing transaction data from various formats\n * (raw hex, bytes, or template objects).\n *\n * @module\n */\n\nimport { Assert } from \"@vbyte/util\";\nimport type { TxData, TxOutputTemplate } from \"@/types/index.js\";\nimport { create_tx, create_tx_output } from \"./create.js\";\nimport { decode_tx } from \"./decode.js\";\nimport { assert_tx_template } from \"./validate.js\";\n\n/**\n * Parse transaction data from hex string, bytes, or template object.\n *\n * This is the main entry point for working with transactions. It accepts\n * multiple input formats and returns a normalized TxData object.\n *\n * @param txdata - Transaction as hex string, Uint8Array, or template object\n * @param prevouts - Optional prevout data to attach to inputs\n * @returns Normalized transaction data object\n * @throws {DecodingError} If raw transaction data is malformed\n *\n * @example\n * ```typescript\n * // Parse from hex\n * const tx = parse_tx('0200000001...')\n *\n * // Parse from template with prevouts\n * const tx = parse_tx(template, [\n * { value: 100000n, script_pk: '0014...' }\n * ])\n * ```\n */\nexport function parse_tx(\n\ttxdata: unknown,\n\tprevouts?: TxOutputTemplate[],\n): TxData {\n\t// Define the tx variable.\n\tlet tx: TxData;\n\t// If the txdata is a string or Uint8Array,\n\tif (typeof txdata === \"string\" || txdata instanceof Uint8Array) {\n\t\t// Decode the tx.\n\t\ttx = decode_tx(txdata);\n\t} else {\n\t\t// Assert the txdata is a valid tx template.\n\t\tassert_tx_template(txdata);\n\t\t// Create the tx.\n\t\ttx = create_tx(txdata);\n\t}\n\t// If the prevouts are provided,\n\tif (prevouts) {\n\t\t// Assert the prevouts are a non-empty array.\n\t\tAssert.has_items(prevouts, \"prevouts must be a non-empty array\");\n\t\t// Iterate over the inputs.\n\t\tfor (const [idx, vin] of tx.vin.entries()) {\n\t\t\t// Get the prevout.\n\t\t\tconst prevout = prevouts.at(idx);\n\t\t\t// Assert the prevout exists.\n\t\t\tAssert.exists(prevout, `prevout not found for input index: ${idx}`);\n\t\t\t// Create the prevout.\n\t\t\tvin.prevout = create_tx_output(prevout);\n\t\t}\n\t}\n\t// Return the tx.\n\treturn tx;\n}\n\n/**\n * Serialize transaction data to a plain JSON-compatible object.\n *\n * Converts BigInt values to strings for JSON serialization without precision loss.\n * Useful for debugging or API responses.\n *\n * @param txdata - Transaction data in any supported format\n * @returns Plain object with serializable values (values as strings)\n */\nexport function serialize_tx(txdata: unknown): Record<string, unknown> {\n\tconst tx = parse_tx(txdata);\n\tconst version = tx.version;\n\tconst locktime = tx.locktime;\n\n\tconst vin: Record<string, unknown>[] = [];\n\tconst vout: Record<string, unknown>[] = [];\n\n\tfor (const e of tx.vin) {\n\t\tif (e.prevout !== null) {\n\t\t\tvin.push({\n\t\t\t\tscript_pk: e.prevout.script_pk,\n\t\t\t\tvalue: String(e.prevout.value),\n\t\t\t});\n\t\t}\n\t}\n\n\tfor (const e of tx.vout) {\n\t\tvout.push({\n\t\t\tscript_pk: e.script_pk,\n\t\t\tvalue: String(e.value),\n\t\t});\n\t}\n\n\treturn { version, locktime, vin, vout };\n}\n","import { Buff } from \"@vbyte/buff\";\nimport { Assert, Test } from \"@vbyte/util\";\nimport { hash256 } from \"@vbyte/crypto/hash\";\nimport { DEFAULT } from \"@/const.js\";\nimport type {\n\tTxData,\n\tTxOutput,\n\tTxOutputTemplate,\n\tTxValue,\n} from \"@/types/index.js\";\nimport { decode_tx } from \"./decode.js\";\nimport { encode_tx } from \"./encode.js\";\nimport { parse_tx } from \"./parse.js\";\nimport { assert_tx_template } from \"./validate.js\";\n\nexport function transcode_tx(\n\ttxdata: string | Uint8Array,\n\tuse_segwit = true,\n): Buff {\n\t// Decode the transaction data.\n\tconst decoded = decode_tx(txdata);\n\t// Re-encode and return the encoded transaction data.\n\treturn encode_tx(decoded, use_segwit);\n}\n\nexport function get_txid(txdata: string | Uint8Array | TxData): string {\n\tlet buffer: Uint8Array;\n\n\tif (txdata instanceof Uint8Array) {\n\t\t// Set the buffer to the transaction data.\n\t\tbuffer = transcode_tx(txdata, false);\n\t} else if (typeof txdata === \"object\") {\n\t\t// Assert the structure of the transaction data is valid.\n\t\tassert_tx_template(txdata);\n\t\t// Encode the transaction data.\n\t\tbuffer = encode_tx(txdata, false);\n\t} else if (typeof txdata === \"string\") {\n\t\t// Assert the transaction data is a hex string.\n\t\tAssert.is_hex(txdata);\n\t\t// Convert the hex string to a Uint8Array.\n\t\tbuffer = transcode_tx(txdata, false);\n\t} else {\n\t\tthrow new TypeError(`invalid txdata type: ${typeof txdata}`);\n\t}\n\t// Return the txid of the transaction data.\n\treturn hash256(buffer).reverse().hex;\n}\n\nexport function get_txhash(txdata: string | Uint8Array | TxData): string {\n\t// If the transaction data is an object,\n\tif (typeof txdata === \"object\") {\n\t\t// Assert the structure of the transaction data is valid.\n\t\tassert_tx_template(txdata);\n\t\t// Encode the transaction data.\n\t\ttxdata = encode_tx(txdata, true);\n\t}\n\t// Return the txhash of the transaction data.\n\treturn hash256(txdata).reverse().hex;\n}\n\nexport function get_tx_value(txdata: string | Uint8Array | TxData): TxValue {\n\t// Parse the transaction data.\n\tconst tx = parse_tx(txdata);\n\t// Assert the structure of the transaction data is valid.\n\tassert_tx_template(tx);\n\t// Calculate the value of the transaction.\n\tconst vin = tx.vin.reduce(\n\t\t(acc, txin) => acc + (txin.prevout?.value ?? 0n),\n\t\t0n,\n\t);\n\tconst vout = tx.vout.reduce((acc, txout) => acc + txout.value, 0n);\n\tconst fees = vin > vout ? vin - vout : 0n;\n\t// Return the value of the transaction.\n\treturn { fees, vin, vout };\n}\n\nexport function get_prevouts(txdata: TxData): TxOutput[] {\n\t// Assert the structure of the transaction data is valid.\n\tassert_tx_template(txdata);\n\t// Collect the prevouts from the transaction.\n\tconst prevouts = txdata.vin.map((e) => e.prevout);\n\t// Assert that all the prevouts are defined.\n\tAssert.ok(\n\t\tprevouts.every((e) => e !== null),\n\t\t\"prevouts missing from tx\",\n\t);\n\t// Return the array of prevouts.\n\treturn prevouts;\n}\n\nexport function normalize_sequence(sequence?: number | string | null): number {\n\t// If sequence is not defined, return a default sequence value.\n\tif (!Test.exists(sequence)) return DEFAULT.SEQUENCE;\n\t// If sequence is a hex string, decode it and return the number value.\n\tif (Test.is_hex(sequence))\n\t\treturn Buff.hex(sequence as string, 4).reverse().num;\n\t// If sequence is a valid unsigned integer, return the value.\n\tif (Test.is_uint(sequence)) return sequence;\n\t// Else, throw an error.\n\tthrow new Error(`invalid sequence value: ${String(sequence)}`);\n}\n\nexport function normalize_value(value: number | bigint): bigint {\n\t// If value is a unsigned integer, return it as a bigint.\n\tif (Test.is_uint(value)) return BigInt(value);\n\t// If value is a bigint, return it as-is.\n\tif (typeof value === \"bigint\") return value;\n\t// Else, throw an error.\n\tthrow new TypeError(`invalid output value: ${String(value)}`);\n}\n\nexport function normalize_prevout(prevout: TxOutputTemplate): TxOutput {\n\t// Return the output with a normalized value.\n\treturn {\n\t\tscript_pk: prevout.script_pk,\n\t\tvalue: normalize_value(prevout.value),\n\t};\n}\n","/**\n * Transaction creation utilities.\n *\n * Functions for creating transaction inputs, outputs, and complete transactions\n * from template objects. Handles coinbase, virtual (unsigned), and spend inputs.\n *\n * @module\n */\n\nimport { Assert } from \"@vbyte/util\";\nimport { COINBASE, DEFAULT } from \"@/const.js\";\nimport type {\n\tTxCoinbaseInput,\n\tTxData,\n\tTxInput,\n\tTxInputTemplate,\n\tTxOutput,\n\tTxOutputTemplate,\n\tTxSpendInput,\n\tTxTemplate,\n\tTxVirtualInput,\n} from \"@/types/index.js\";\nimport {\n\tnormalize_prevout,\n\tnormalize_sequence,\n\tnormalize_value,\n} from \"./util.js\";\nimport {\n\tassert_tx_template,\n\tassert_vin_template,\n\tassert_vout_template,\n} from \"./validate.js\";\n\n/**\n * Create a coinbase input for a block reward transaction.\n *\n * Coinbase inputs have a special txid (all zeros) and vout (0xFFFFFFFF).\n * The coinbase field contains arbitrary data (block height, miner message, etc.).\n *\n * @param config - Input template with coinbase data\n * @returns Coinbase input object\n * @throws {Error} If coinbase field is missing\n *\n * @example\n * ```typescript\n * const input = create_coinbase_input({\n * coinbase: '03a1b2c3', // Block height + extra nonce\n * witness: ['0000...'] // Witness commitment\n * })\n * ```\n */\nexport function create_coinbase_input(\n\tconfig: TxInputTemplate,\n): TxCoinbaseInput {\n\tassert_vin_template(config);\n\tAssert.exists(config.coinbase, \"coinbase is required\");\n\tconst txid = COINBASE.TXID;\n\tconst vout = COINBASE.VOUT;\n\tconst coinbase = config.coinbase;\n\tconst witness = config.witness ?? [];\n\tconst sequence = normalize_sequence(config.sequence);\n\treturn {\n\t\tcoinbase,\n\t\tprevout: null,\n\t\tscript_sig: null,\n\t\tsequence,\n\t\twitness,\n\t\ttxid,\n\t\tvout,\n\t};\n}\n\n/**\n * Create a virtual (unsigned) input without prevout data.\n *\n * Virtual inputs reference an output but don't include prevout value/script.\n * Used for building unsigned transactions before prevout data is available.\n *\n * @param config - Input template with txid and vout\n * @returns Virtual input object\n * @throws {Error} If coinbase or prevout fields are provided\n *\n * @example\n * ```typescript\n * const input = create_virtual_input({\n * txid: 'abc123...',\n * vout: 0,\n * sequence: 0xfffffffe\n * })\n * ```\n */\nexport function create_virtual_input(config: TxInputTemplate): TxVirtualInput {\n\tassert_vin_template(config);\n\tAssert.is_empty(config.coinbase, \"coinbase is not allowed\");\n\tAssert.is_empty(config.prevout, \"prevout is not allowed\");\n\tconst { txid, vout, script_sig = null, witness = [] } = config;\n\tconst sequence = normalize_sequence(config.sequence);\n\treturn {\n\t\ttxid,\n\t\tvout,\n\t\tcoinbase: null,\n\t\tprevout: null,\n\t\tscript_sig,\n\t\tsequence,\n\t\twitness,\n\t};\n}\n\n/**\n * Create a spend input with full prevout data.\n *\n * Spend inputs include the prevout value and scriptPubKey, which are\n * required for signature hash calculation.\n *\n * @param config - Input template with txid, vout, and prevout data\n * @returns Spend input object with prevout\n * @throws {Error} If prevout field is missing\n *\n * @example\n * ```typescript\n * const input = create_spend_input({\n * txid: 'abc123...',\n * vout: 0,\n * prevout: { value: 100000n, script_pk: '0014...' },\n * witness: ['signature', 'pubkey']\n * })\n * ```\n */\nexport function create_spend_input(config: TxInputTemplate): TxSpendInput {\n\tassert_vin_template(config);\n\tAssert.exists(config.prevout, \"prevout is required\");\n\tconst { txid, vout, script_sig = null, witness = [] } = config;\n\tconst prevout = normalize_prevout(config.prevout);\n\tconst sequence = normalize_sequence(config.sequence);\n\treturn { txid, vout, coinbase: null, prevout, script_sig, sequence, witness };\n}\n\n/**\n * Create a transaction input from a template.\n *\n * Automatically detects the input type based on fields present:\n * - If coinbase is set: creates coinbase input\n * - If prevout is set: creates spend input with prevout data\n * - Otherwise: creates virtual input (no prevout)\n *\n * @param config - Input template\n * @returns Transaction input of appropriate type\n */\nexport function create_tx_input(config: TxInputTemplate): TxInput {\n\tif (config.coinbase) return create_coinbase_input(config);\n\tif (config.prevout) return create_spend_input(config);\n\treturn create_virtual_input(config);\n}\n\n/**\n * Create a transaction output from a template.\n *\n * @param config - Output template with value and scriptPubKey\n * @returns Transaction output object\n *\n * @example\n * ```typescript\n * const output = create_tx_output({\n * value: 50000n, // satoshis\n * script_pk: '0014abc123...' // P2WPKH scriptPubKey\n * })\n * ```\n */\nexport function create_tx_output(config: TxOutputTemplate): TxOutput {\n\tassert_vout_template(config);\n\tconst script_pk = config.script_pk;\n\tconst value = normalize_value(config.value);\n\treturn { script_pk, value };\n}\n\n/**\n * Create a complete transaction from a template.\n *\n * @param config - Transaction template with vin, vout, version, locktime\n * @returns Complete transaction data object\n *\n * @example\n * ```typescript\n * const tx = create_tx({\n * version: 2,\n * locktime: 0,\n * vin: [{\n * txid: 'abc123...',\n * vout: 0,\n * prevout: { value: 100000n, script_pk: '0014...' }\n * }],\n * vout: [{\n * value: 50000n,\n * script_pk: '0014...'\n * }]\n * })\n * ```\n */\nexport function create_tx(config?: Partial<TxTemplate>): TxData {\n\tassert_tx_template(config);\n\tconst { vin = [], vout = [] } = config ?? { vin: [], vout: [] };\n\tconst locktime = config.locktime ?? DEFAULT.LOCKTIME;\n\tconst version = config.version ?? DEFAULT.VERSION;\n\tconst inputs = vin.map((txin) => create_tx_input(txin));\n\tconst outputs = vout.map((txout) => create_tx_output(txout));\n\treturn { locktime, vin: inputs, vout: outputs, version };\n}\n","import { Buff, type Bytes } from \"@vbyte/buff\";\nimport type { TxData, TxInput, TxOutput, TxSize } from \"@/types/index.js\";\n\nimport {\n\tencode_tx,\n\tencode_tx_inputs,\n\tencode_tx_outputs,\n\tencode_tx_vout,\n\tencode_vin,\n\tencode_vin_witness,\n} from \"./encode.js\";\nimport { parse_tx } from \"./parse.js\";\n\nconst WIT_FLAG_BYTES = 2;\n\nexport function get_vsize(bytes: Bytes): number {\n\tconst weight = Buff.bytes(bytes).length;\n\treturn Math.ceil(weight / 4);\n}\n\nexport function get_txsize(txdata: string | TxData): TxSize {\n\tconst json = parse_tx(txdata);\n\tconst base = encode_tx(json, false).length;\n\tconst total = encode_tx(json, true).length;\n\tconst weight = base * 3 + total;\n\tconst vsize = Math.ceil(weight / 4);\n\treturn { base, total, vsize, weight };\n}\n\nexport function get_vin_size(vin: TxInput[]): number {\n\tconst bytes = encode_tx_inputs(vin);\n\treturn bytes.length;\n}\n\nexport function get_vout_size(vout: TxOutput[]): number {\n\tconst bytes = encode_tx_outputs(vout);\n\treturn bytes.length;\n}\n\nexport function get_segwit_size(txinputs: TxInput[]): number {\n\tconst segwit_data = txinputs\n\t\t.filter((e) => e.witness.length > 0)\n\t\t.map((e) => e.witness);\n\treturn (\n\t\tWIT_FLAG_BYTES +\n\t\tsegwit_data.reduce((acc, e) => acc + encode_vin_witness(e).length, 0)\n\t);\n}\n\nexport function get_txin_size(txinput: TxInput): number {\n\tconst bytes = encode_vin(txinput);\n\treturn bytes.length;\n}\n\nexport function get_txout_size(txoutput: TxOutput): number {\n\tconst bytes = encode_tx_vout(txoutput);\n\treturn bytes.length;\n}\n","/**\n * Signature hash utility functions.\n *\n * Helper functions for extracting data needed for signature hash calculation.\n *\n * @module\n */\n\nimport { Buff } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/util\";\nimport { sha256 } from \"@vbyte/crypto/hash\";\nimport { ValidationError } from \"@/error.js\";\n\nimport type {\n\tSigHashOptions,\n\tTxData,\n\tTxInput,\n\tTxOutput,\n} from \"@/types/index.js\";\n\n/**\n * Get the prevout (previous output) data for a transaction input.\n *\n * Prevout data includes the value and scriptPubKey from the UTXO being spent.\n * This is required for signature hash calculation.\n *\n * @param vin - Transaction input with prevout data\n * @returns The prevout data (value and script_pk)\n * @throws Error if prevout data is missing\n *\n * @example\n * ```typescript\n * const prevout = get_prevout(txinput)\n * // { value: 50000, script_pk: '0014...' }\n * ```\n */\nexport function get_prevout(vin: TxInput): TxOutput {\n\tAssert.exists(\n\t\tvin.prevout,\n\t\t`Prevout data missing for input: ${String(vin.txid)}`,\n\t);\n\treturn vin.prevout;\n}\n\n/**\n * Extract a transaction input for signing.\n *\n * Retrieves the input to sign either by index or from a provided txinput object.\n * Used internally by sighash functions to get the input being signed.\n *\n * @param txdata - Full transaction data\n * @param config - Options containing either txindex or txinput\n * @returns The transaction input to sign\n * @throws {ValidationError} If txindex is out of bounds\n * @throws {Error} If neither txindex nor txinput is provided\n *\n * @example\n * ```typescript\n * const input = parse_txinput(txdata, { txindex: 0 })\n * // Returns txdata.vin[0]\n * ```\n */\nexport function parse_txinput(\n\ttxdata: TxData,\n\tconfig?: SigHashOptions,\n): TxInput {\n\tlet { txindex, txinput } = config ?? {};\n\tif (txindex !== undefined) {\n\t\tif (txindex >= txdata.vin.length) {\n\t\t\t// If index is out of bounds, throw error.\n\t\t\tthrow new ValidationError(\n\t\t\t\t`input index ${txindex} out of bounds. Transaction has ${txdata.vin.length} inputs (indices 0-${txdata.vin.length - 1})`\n\t\t\t);\n\t\t}\n\t\ttxinput = txdata.vin.at(txindex);\n\t}\n\tAssert.ok(txinput !== undefined);\n\treturn txinput;\n}\n\n/**\n * Extract and hash annex data from a taproot witness.\n *\n * In BIP-341, the annex is an optional element at the end of the witness\n * stack that starts with 0x50. If present, its SHA256 hash is included\n * in the signature hash.\n *\n * @param witness - Witness stack elements (hex strings)\n * @returns SHA256 hash of the annex with varint prefix, or undefined if no annex\n *\n * @example\n * ```typescript\n * // Witness with annex (last element starts with '50')\n * const annex = get_annex_data(['sig', 'script', 'cblock', '50abcd'])\n * // Returns SHA256 hash of the annex\n *\n * // Witness without annex\n * const noAnnex = get_annex_data(['sig', 'script', 'cblock'])\n * // Returns undefined\n * ```\n */\nexport function get_annex_data(witness?: string[]): Buff | undefined {\n\t// If no witness exists, return undefined.\n\tif (witness === undefined) return;\n\t// If there are less than two elements, return undefined.\n\tif (witness.length < 2) return;\n\t// Define the last element as the annex.\n\tconst annex = witness.at(-1);\n\t// If the annex is a string and starts with '50',\n\tif (typeof annex === \"string\" && annex.startsWith(\"50\")) {\n\t\t// Convert the annex to a buffer with a varint prefix.\n\t\tconst bytes = Buff.hex(annex).prefix_varint(\"be\");\n\t\t// Return the sha256 of the annex.\n\t\treturn sha256(bytes);\n\t}\n\t// Else, return undefined.\n\treturn undefined;\n}\n","/**\n * BIP-143 SegWit signature hash calculation.\n *\n * Implements the segwit v0 sighash algorithm as specified in BIP-143.\n * Used for signing P2WPKH and P2WSH transaction inputs.\n *\n * @see https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki\n * @module\n */\n\nimport { Buff } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/util\";\nimport { hash160, hash256 } from \"@vbyte/crypto/hash\";\nimport * as CONST from \"@/const.js\";\nimport { ValidationError } from \"@/error.js\";\n\nimport { decode_script, prefix_script_size } from \"@/lib/script/index.js\";\n\nimport {\n\tencode_tx_locktime,\n\tencode_tx_version,\n\tencode_txin_sequence,\n\tencode_txin_txid,\n\tencode_txin_vout,\n\tencode_vout_value,\n\tparse_tx,\n} from \"@/lib/tx/index.js\";\n\nimport type {\n\tSigHashOptions,\n\tTxData,\n\tTxInput,\n\tTxOutput,\n} from \"@/types/index.js\";\nimport { parse_txinput } from \"./util.js\";\n\n/**\n * Compute the segwit signature hash for a transaction input.\n *\n * This function computes the BIP-143 signature hash used for signing\n * SegWit v0 inputs (P2WPKH and P2WSH). For P2WPKH, provide a pubkey.\n * For P2WSH, provide the witness script.\n *\n * @param txdata - Transaction data object\n * @param options - Sighash options including txindex, sigflag, pubkey or script\n * @returns 32-byte signature hash as Buff\n * @throws {Error} If sigflag is invalid\n * @throws {Error} If prevout value is missing\n * @throws {Error} If neither pubkey nor script is provided\n * @throws {Error} If script contains OP_CODESEPARATOR (not supported)\n *\n * @example\n * ```typescript\n * // P2WPKH signing\n * const hash = hash_segwit_tx(tx, {\n * txindex: 0,\n * pubkey: '02...',\n * sigflag: 0x01 // SIGHASH_ALL\n * })\n *\n * // P2WSH signing\n * const hash = hash_segwit_tx(tx, {\n * txindex: 0,\n * script: witnessScript,\n * sigflag: 0x01\n * })\n * ```\n */\nexport function hash_segwit_tx(\n\ttxdata: TxData,\n\toptions: SigHashOptions = {},\n): Buff {\n\t// Unpack the sigflag from our config object.\n\tconst { sigflag = 0x01, txindex } = options;\n\t// Normalize the tx into JSON format.\n\tconst tx = parse_tx(txdata);\n\t// Check if the ANYONECANPAY flag is set.\n\tconst is_anypay = (sigflag & 0x80) === 0x80;\n\t// Save a normalized version of the sigflag.\n\tconst flag = sigflag % 0x80;\n\t// Check if the sigflag exists as a valid type.\n\tif (!CONST.SIGHASH_SEGWIT.includes(flag)) {\n\t\tthrow new ValidationError(\n\t\t\t`invalid sighash type: 0x${sigflag.toString(16)}. ` +\n\t\t\t`Valid values: SIGHASH_ALL (0x01), SIGHASH_NONE (0x02), SIGHASH_SINGLE (0x03), ` +\n\t\t\t`or combined with ANYONECANPAY (0x81, 0x82, 0x83)`\n\t\t);\n\t}\n\t// Unpack the tx object.\n\tconst { version, vin, vout, locktime } = tx;\n\t// Parse the input we are signing from the config.\n\tconst txinput = parse_txinput(tx, options);\n\t// Unpack the chosen input for signing.\n\tconst { txid, vout: prevIdx, prevout, sequence } = txinput;\n\t// Unpack the prevout for the chosen input.\n\tconst { value } = prevout ?? {};\n\t// Check if a prevout value is provided.\n\tif (value === undefined) {\n\t\tthrow new ValidationError(\"Prevout value is required for segwit sighash calculation\", \"prevout.value\");\n\t}\n\t// Initialize our script variable from the config.\n\tlet { pubkey, script } = options;\n\t// Check if a pubkey is provided (instead of a script).\n\tif (script === undefined && pubkey !== undefined) {\n\t\tconst pkhash = hash160(pubkey).hex;\n\t\tscript = `76a914${String(pkhash)}88ac`;\n\t}\n\t// Make sure that some form of script has been provided.\n\tif (script === undefined) {\n\t\tthrow new ValidationError(\"Either pubkey or script must be provided for segwit sighash\", \"pubkey/script\");\n\t}\n\t// Throw if OP_CODESEPARATOR is used in a script.\n\tif (decode_script(script).includes(\"OP_CODESEPARATOR\")) {\n\t\tthrow new ValidationError(\n\t\t\t\"OP_CODESEPARATOR is not supported in segwit scripts\",\n\t\t\t\"script\",\n\t\t);\n\t}\n\n\tconst sighash = [\n\t\tencode_tx_version(version),\n\t\tbip143_hash_prevouts(vin, is_anypay),\n\t\tbip143_hash_sequence(vin, flag, is_anypay),\n\t\tencode_txin_txid(txid),\n\t\tencode_txin_vout(prevIdx),\n\t\tprefix_script_size(script),\n\t\tencode_vout_value(value),\n\t\tencode_txin_sequence(sequence),\n\t\tbip143_hash_outputs(vout, flag, txindex),\n\t\tencode_tx_locktime(locktime),\n\t\tBuff.num(sigflag, 4).reverse(),\n\t];\n\n\treturn hash256(Buff.join(sighash));\n}\n\n/**\n * Compute double-SHA256 hash of all input outpoints (txid:vout pairs).\n *\n * Returns zeroes if ANYONECANPAY flag is set.\n *\n * @param vin - Array of transaction inputs\n * @param isAnypay - Whether ANYONECANPAY flag is set\n * @returns Hash of outpoints, or 32 zero bytes if ANYONECANPAY\n */\nexport function bip143_hash_prevouts(\n\tvin: TxInput[],\n\tisAnypay?: boolean,\n): Uint8Array {\n\tif (isAnypay === true) {\n\t\treturn Buff.num(0, 32);\n\t}\n\n\tconst stack = [];\n\n\tfor (const { txid, vout } of vin) {\n\t\tstack.push(encode_txin_txid(txid));\n\t\tstack.push(encode_txin_vout(vout));\n\t}\n\n\treturn hash256(Buff.join(stack));\n}\n\n/**\n * Compute double-SHA256 hash of all input sequence numbers.\n *\n * Returns zeroes if ANYONECANPAY flag is set or sigflag is not SIGHASH_ALL.\n *\n * @param vin - Array of transaction inputs\n * @param sigflag - Signature hash type (normalized, without ANYONECANPAY bit)\n * @param isAnyPay - Whether ANYONECANPAY flag is set\n * @returns Hash of sequences, or 32 zero bytes if conditions not met\n */\nexport function bip143_hash_sequence(\n\tvin: TxInput[],\n\tsigflag: number,\n\tisAnyPay: boolean,\n): Uint8Array {\n\tif (isAnyPay || sigflag !== 0x01) {\n\t\treturn Buff.num(0, 32);\n\t}\n\n\tconst stack = [];\n\n\tfor (const { sequence } of vin) {\n\t\tstack.push(encode_txin_sequence(sequence));\n\t}\n\treturn hash256(Buff.join(stack));\n}\n\n/**\n * Compute double-SHA256 hash of transaction outputs.\n *\n * Behavior depends on sigflag:\n * - SIGHASH_ALL (0x01): Hash all outputs\n * - SIGHASH_SINGLE (0x03): Hash only the output at the given index\n * - SIGHASH_NONE (0x02): Return 32 zero bytes\n *\n * @param vout - Array of transaction outputs\n * @param sigflag - Signature hash type (normalized, without ANYONECANPAY bit)\n * @param idx - Input index (required for SIGHASH_SINGLE)\n * @returns Hash of outputs, or 32 zero bytes for SIGHASH_NONE\n */\nexport function bip143_hash_outputs(\n\tvout: TxOutput[],\n\tsigflag: number,\n\tidx?: number,\n): Uint8Array {\n\tconst stack = [];\n\n\tif (sigflag === 0x01) {\n\t\tfor (const { value, script_pk } of vout) {\n\t\t\tstack.push(encode_vout_value(value));\n\t\t\tstack.push(prefix_script_size(script_pk));\n\t\t}\n\t\treturn hash256(Buff.join(stack));\n\t}\n\n\tif (sigflag === 0x03) {\n\t\tAssert.ok(idx !== undefined, \"txindex required for SIGHASH_SINGLE\");\n\t\tAssert.ok(idx >= 0, \"txindex must be non-negative\");\n\t\tif (idx < vout.length) {\n\t\t\tconst { value, script_pk } = vout[idx];\n\t\t\tstack.push(encode_vout_value(value));\n\t\t\tstack.push(prefix_script_size(script_pk));\n\t\t\treturn hash256(Buff.join(stack));\n\t\t}\n\t}\n\n\treturn Buff.num(0, 32);\n}\n","import { Buff } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/util\";\nimport { hash340 } from \"@vbyte/crypto/hash\";\nimport { TAPLEAF_DEFAULT_VERSION } from \"@/const.js\";\nimport { prefix_script_size } from \"@/lib/script/index.js\";\n\nconst DEFAULT_VERSION = TAPLEAF_DEFAULT_VERSION;\n\n/**\n * Encode a tapscript into a tapleaf hash.\n * Prefixes the script with its size and applies the TapLeaf tagged hash.\n *\n * @param script - The tapscript to encode (hex string or bytes)\n * @param version - Tapleaf version byte (default: 0xc0)\n * @returns Tapleaf hash as 32-byte Buff\n *\n * @example\n * ```typescript\n * const script = '20' + pubkey + 'ac' // <pubkey> OP_CHECKSIG\n * const tapleaf = encode_tapscript(script)\n * ```\n */\nexport function encode_tapscript(\n\tscript: string | Uint8Array,\n\tversion = DEFAULT_VERSION,\n): Buff {\n\tconst preimg = prefix_script_size(script);\n\treturn encode_tapleaf(preimg, version);\n}\n\n/**\n * Encode data into a tapleaf hash using the TapLeaf tagged hash.\n *\n * @param data - The data to hash (typically size-prefixed script)\n * @param version - Tapleaf version byte (default: 0xc0)\n * @returns Tapleaf hash as 32-byte Buff\n */\nexport function encode_tapleaf(\n\tdata: string | Uint8Array,\n\tversion = DEFAULT_VERSION,\n): Buff {\n\tconst vbyte = encode_leaf_version(version);\n\treturn hash340(\"TapLeaf\", vbyte, data);\n}\n\n/**\n * Encode two tapleaf/branch hashes into a tapbranch hash.\n * Combines two children using the TapBranch tagged hash.\n * Children are sorted lexicographically before hashing.\n *\n * @param leaf_a - First child hash (hex string)\n * @param leaf_b - Second child hash (hex string)\n * @returns Tapbranch hash as 32-byte Buff\n */\nexport function encode_tapbranch(leaf_a: string, leaf_b: string): Buff {\n\t// Compare leaves in lexical order.\n\tif (leaf_b < leaf_a) {\n\t\t// Swap leaves if needed.\n\t\t[leaf_a, leaf_b] = [leaf_b, leaf_a];\n\t}\n\t// Return digest of leaves as a branch hash.\n\treturn hash340(\"TapBranch\", leaf_a, leaf_b);\n}\n\n/**\n * Encode a tapleaf version byte by masking the parity bit.\n *\n * @param version - Tapleaf version (default: 0xc0)\n * @returns Version with parity bit cleared\n */\nexport function encode_leaf_version(version = 0xc0): number {\n\treturn version & 0xfe;\n}\n\n/**\n * Encode a taproot tweak from an internal pubkey and optional data.\n * Uses the TapTweak tagged hash.\n *\n * @param pubkey - 32-byte internal public key (x-only)\n * @param data - Optional commitment data (typically merkle root)\n * @returns Taptweak hash as 32-byte Buff\n * @throws Error if pubkey is not 32 bytes\n *\n * @example\n * ```typescript\n * // Key-only spend (no script tree)\n * const tweak = encode_taptweak(internalPubkey)\n *\n * // Script tree spend\n * const tweak = encode_taptweak(internalPubkey, merkleRoot)\n * ```\n */\nexport function encode_taptweak(\n\tpubkey: string | Uint8Array,\n\tdata: string | Uint8Array = new Uint8Array(),\n): Buff {\n\tAssert.ok(Buff.bytes(pubkey).length === 32, \"pubkey must be 32 bytes\");\n\treturn hash340(\"TapTweak\", pubkey, data);\n}\n","/**\n * BIP-341 Taproot signature hash calculation.\n *\n * Implements the taproot sighash algorithm as specified in BIP-341.\n * Used for signing taproot (SegWit v1) transaction inputs.\n *\n * @see https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki\n * @module\n */\n\nimport { Buff } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/util\";\nimport { hash340, sha256 } from \"@vbyte/crypto/hash\";\nimport * as CONST from \"@/const.js\";\nimport { ValidationError } from \"@/error.js\";\nimport { encode_tapscript } from \"@/lib/taproot/encode.js\";\nimport {\n\tencode_script_data,\n\tencode_tx_locktime,\n\tencode_tx_version,\n\tencode_txin_sequence,\n\tencode_txin_txid,\n\tencode_txin_vout,\n\tencode_vout_value,\n} from \"@/lib/tx/encode.js\";\nimport { parse_tx } from \"@/lib/tx/parse.js\";\nimport type {\n\tSigHashOptions,\n\tTxData,\n\tTxInput,\n\tTxOutput,\n} from \"@/types/index.js\";\nimport { get_annex_data, get_prevout, parse_txinput } from \"./util.js\";\n\n/**\n * Compute the taproot signature hash for a transaction input.\n *\n * This function computes the BIP-341 signature hash used for signing\n * taproot inputs. The hash is computed using the tagged hash function\n * with tag \"TapSighash\".\n *\n * @param template - Transaction data (hex string or TxData object)\n * @param config - Sighash options including txindex, sigflag, extension\n * @returns 32-byte signature hash as Buff\n * @throws {Error} If sigflag is invalid or extflag is out of range\n *\n * @example\n * ```typescript\n * const hash = hash_taproot_tx(tx, {\n * txindex: 0,\n * sigflag: 0x00, // SIGHASH_DEFAULT\n * })\n * ```\n */\nexport function hash_taproot_tx(\n\ttemplate: TxData | string,\n\tconfig: SigHashOptions = {},\n): Buff {\n\tconst preimage = get_taproot_tx_preimage(template, config);\n\treturn hash340(\"TapSighash\", preimage);\n}\n\n/**\n * Build the taproot signature preimage for a transaction input.\n *\n * Constructs the preimage that will be hashed to produce the signature hash.\n * This is the internal serialization format specified in BIP-341.\n *\n * @param template - Transaction data (hex string or TxData object)\n * @param config - Sighash options\n * @returns Serialized preimage as Buff\n * @throws {Error} If sigflag is invalid or extflag is out of range\n */\nexport function get_taproot_tx_preimage(\n\ttemplate: TxData | string,\n\tconfig: SigHashOptions = {},\n): Buff {\n\t// Unpack configuration.\n\tconst {\n\t\tscript,\n\t\ttxindex,\n\t\tsigflag = 0x00,\n\t\textflag = 0x00,\n\t\tkey_version = 0x00,\n\t\tseparator_pos = 0xffffffff,\n\t} = config;\n\n\t// Normalize the txdata object.\n\tconst tx = parse_tx(template);\n\t// Unpack the txdata object.\n\tconst { version, vin: input, vout: output, locktime } = tx;\n\t// Parse the input we are signing from the config.\n\tconst txinput = parse_txinput(tx, config);\n\t// Unpack the txinput object.\n\tconst { txid, vout, sequence, witness = [] } = txinput;\n\t// Check if we are using a valid hash type.\n\tif (!CONST.SIGHASH_TAPROOT.includes(sigflag)) {\n\t\t// If the sigflag is an invalid type, throw error.\n\t\tthrow new ValidationError(\n\t\t\t`invalid taproot sighash type: 0x${sigflag.toString(16)}. ` +\n\t\t\t`Valid values: SIGHASH_DEFAULT (0x00), SIGHASH_ALL (0x01), SIGHASH_NONE (0x02), SIGHASH_SINGLE (0x03), ` +\n\t\t\t`or combined with ANYONECANPAY (0x81, 0x82, 0x83)`\n\t\t);\n\t}\n\tif (extflag < 0 || extflag > 127) {\n\t\t// If the extflag is out of range, throw error.\n\t\tthrow new ValidationError(\n\t\t\t`extension flag out of range: ${extflag}. Valid range is 0-127`\n\t\t);\n\t}\n\n\tlet { extension } = config;\n\n\tif (script !== undefined) {\n\t\textension = encode_tapscript(script).hex;\n\t}\n\n\t// Define the parameters of the transaction.\n\tconst is_anypay = (sigflag & 0x80) === 0x80;\n\tconst annex = get_annex_data(witness);\n\tconst annexBit = annex !== undefined ? 1 : 0;\n\tconst extendBit = extension !== undefined ? 1 : 0;\n\tconst spendType = (extflag + extendBit) * 2 + annexBit;\n\n\t// Begin building our preimage.\n\tconst preimage: (string | Uint8Array)[] = [\n\t\tBuff.num(0x00, 1), // Add zero-byte.\n\t\tBuff.num(sigflag, 1), // Commit to signature flag.\n\t\tencode_tx_version(version), // Commit to tx version.\n\t\tencode_tx_locktime(locktime), // Commit to tx locktime.\n\t];\n\n\tif (!is_anypay) {\n\t\t// If flag ANYONE_CAN_PAY is not set,\n\t\t// then commit to all inputs.\n\t\tconst prevouts = input.map((e) => get_prevout(e));\n\t\tpreimage.push(\n\t\t\tbip341_hash_outpoints(input), // Commit to txid/vout for each input.\n\t\t\tbip341_hash_amounts(prevouts), // Commit to prevout amount for each input.\n\t\t\tbip341_hash_scripts(prevouts), // Commit to prevout script for each input.\n\t\t\tbip341_hash_sequence(input), // Commit to sequence value for each input.\n\t\t);\n\t}\n\n\tif ((sigflag & 0x03) < 2 || (sigflag & 0x03) > 3) {\n\t\t// If neither SINGLE or NONE flags are set,\n\t\t// include a commitment to all outputs.\n\t\tpreimage.push(bip341_hash_outputs(output));\n\t}\n\n\t// At this step, we include the spend type.\n\tpreimage.push(Buff.num(spendType, 1));\n\n\tif (is_anypay) {\n\t\t// If ANYONE_CAN_PAY flag is set, then we will\n\t\t// provide a commitment to the input being signed.\n\t\tconst { value, script_pk } = get_prevout(txinput);\n\t\tpreimage.push(\n\t\t\tencode_txin_txid(txid), // Commit to the input txid.\n\t\t\tencode_txin_vout(vout), // Commit to the input vout index.\n\t\t\tencode_vout_value(value), // Commit to the input's prevout value.\n\t\t\tencode_script_data(script_pk), // Commit to the input's prevout script.\n\t\t\tencode_txin_sequence(sequence), // Commit to the input's sequence value.\n\t\t);\n\t} else {\n\t\t// Otherwise, we must have already included a commitment\n\t\t// to all inputs in the tx, so simply add a commitment to\n\t\t// the index of the input we are signing for.\n\t\tAssert.ok(typeof txindex === \"number\");\n\t\tpreimage.push(Buff.num(txindex, 4).reverse());\n\t}\n\n\tif (annex !== undefined) {\n\t\t// If an annex has been set, include it here.\n\t\tpreimage.push(annex);\n\t}\n\n\tif ((sigflag & 0x03) === 0x03) {\n\t\t// If the SINGLE flag is set, then include a\n\t\t// commitment to the output which is adjacent\n\t\t// to the input that we are signing for.\n\t\tAssert.ok(\n\t\t\ttypeof txindex === \"number\",\n\t\t\t\"txindex required for SIGHASH_SINGLE\",\n\t\t);\n\t\tAssert.ok(\n\t\t\ttxindex >= 0 && txindex < output.length,\n\t\t\t`txindex ${txindex} out of bounds for ${output.length} outputs`,\n\t\t);\n\t\tpreimage.push(bip341_hash_output(output[txindex]));\n\t}\n\n\tif (extension !== undefined) {\n\t\t// If we are extending this signature to include\n\t\t// other commitments (such as a tapleaf), then we\n\t\t// will add it to the preimage here.\n\t\tpreimage.push(\n\t\t\tBuff.bytes(extension), // Extention data (in bytes).\n\t\t\tBuff.num(key_version), // Key version (reserved for future upgrades).\n\t\t\tBuff.num(separator_pos, 4, \"le\"), // If OP_CODESEPARATOR is used, this must be set.\n\t\t);\n\t}\n\n\treturn Buff.join(preimage);\n}\n\n/**\n * Compute SHA256 hash of all input outpoints (txid:vout pairs).\n *\n * Used when ANYONECANPAY flag is NOT set to commit to all inputs.\n *\n * @internal\n * @param vin - Array of transaction inputs\n * @returns SHA256 hash of concatenated outpoints\n */\nexport function bip341_hash_outpoints(vin: TxInput[]): Buff {\n\tconst stack = [];\n\tfor (const { txid, vout } of vin) {\n\t\tstack.push(encode_txin_txid(txid));\n\t\tstack.push(encode_txin_vout(vout));\n\t}\n\treturn sha256(Buff.join(stack));\n}\n\n/**\n * Compute SHA256 hash of all input sequence numbers.\n *\n * Used when ANYONECANPAY flag is NOT set to commit to all sequences.\n *\n * @internal\n * @param vin - Array of transaction inputs\n * @returns SHA256 hash of concatenated sequence values\n */\nexport function bip341_hash_sequence(vin: TxInput[]): Buff {\n\treturn sha256(...vin.map((vin) => encode_txin_sequence(vin.sequence)));\n}\n\n/**\n * Compute SHA256 hash of all prevout amounts.\n *\n * Used when ANYONECANPAY flag is NOT set to commit to all input values.\n *\n * @internal\n * @param prevouts - Array of prevout data (value and scriptPubKey)\n * @returns SHA256 hash of concatenated amounts\n */\nexport function bip341_hash_amounts(prevouts: TxOutput[]): Buff {\n\treturn sha256(...prevouts.map((prevout) => encode_vout_value(prevout.value)));\n}\n\n/**\n * Compute SHA256 hash of all prevout scriptPubKeys.\n *\n * Used when ANYONECANPAY flag is NOT set to commit to all input scripts.\n *\n * @internal\n * @param prevouts - Array of prevout data (value and scriptPubKey)\n * @returns SHA256 hash of concatenated scripts (with length prefixes)\n */\nexport function bip341_hash_scripts(prevouts: TxOutput[]): Buff {\n\treturn sha256(\n\t\t...prevouts.map((prevout) => encode_script_data(prevout.script_pk)),\n\t);\n}\n\n/**\n * Compute SHA256 hash of all transaction outputs.\n *\n * Used when SIGHASH_SINGLE and SIGHASH_NONE flags are NOT set.\n *\n * @internal\n * @param vout - Array of transaction outputs\n * @returns SHA256 hash of serialized outputs (value + scriptPubKey)\n */\nexport function bip341_hash_outputs(vout: TxOutput[]): Buff {\n\tconst stack = [];\n\tfor (const { value, script_pk } of vout) {\n\t\tstack.push(encode_vout_value(value));\n\t\tstack.push(encode_script_data(script_pk));\n\t}\n\treturn sha256(...stack);\n}\n\n/**\n * Compute SHA256 hash of a single transaction output.\n *\n * Used with SIGHASH_SINGLE to commit only to the corresponding output.\n *\n * @internal\n * @param vout - Single transaction output\n * @returns SHA256 hash of serialized output (value + scriptPubKey)\n */\nexport function bip341_hash_output(vout: TxOutput): Buff {\n\treturn sha256(\n\t\tencode_vout_value(vout.value),\n\t\tencode_script_data(vout.script_pk),\n\t);\n}\n","import { Buff } from \"@vbyte/buff\";\nimport { ECC } from \"@vbyte/crypto\";\nimport { SIGHASH_DEFAULT, SIGHASH_SEGWIT, SIGHASH_TAPROOT } from \"@/const.js\";\nimport { ConfigError, ValidationError } from \"@/error.js\";\nimport { hash_segwit_tx } from \"@/lib/sighash/segwit.js\";\nimport { hash_taproot_tx } from \"@/lib/sighash/taproot.js\";\nimport { parse_tx } from \"@/lib/tx/parse.js\";\n\nimport type { SigHashOptions, TxData } from \"@/types/index.js\";\n\n/**\n * Regex pattern for valid 32-byte hex string (64 hex characters).\n * Used for secret key validation.\n */\nconst SECKEY_REGEX = /^[0-9a-fA-F]{64}$/;\n\n/**\n * Validate a secret key format.\n * @param seckey - The secret key to validate\n * @throws {ValidationError} If the secret key is invalid\n */\nfunction validate_seckey(seckey: string): void {\n\tif (typeof seckey !== \"string\") {\n\t\tthrow new ValidationError(\"Secret key must be a string\", \"seckey\");\n\t}\n\tif (!SECKEY_REGEX.test(seckey)) {\n\t\tthrow new ValidationError(\n\t\t\t\"Invalid secret key format: expected 32-byte hex string (64 characters)\",\n\t\t\t\"seckey\",\n\t\t);\n\t}\n}\n\n/**\n * Validate sighash options.\n * @param options - The sighash options to validate\n * @param validFlags - Array of valid sighash flags\n * @throws {ValidationError} If txindex is invalid\n * @throws {ConfigError} If sigflag is invalid\n */\nfunction validate_sighash_options(\n\toptions: SigHashOptions,\n\tvalidFlags: number[],\n): void {\n\tconst { sigflag, txindex } = options;\n\n\tif (sigflag !== undefined) {\n\t\tif (typeof sigflag !== \"number\" || !Number.isInteger(sigflag)) {\n\t\t\tthrow new ConfigError(\"sigflag must be an integer\");\n\t\t}\n\t\t// Normalize sigflag for validation (remove ANYONECANPAY bit)\n\t\tconst normalizedFlag = sigflag & 0x7f;\n\t\tconst isAnypay = (sigflag & 0x80) === 0x80;\n\t\tconst baseFlag = isAnypay ? normalizedFlag | 0x80 : normalizedFlag;\n\n\t\tif (\n\t\t\t!validFlags.includes(baseFlag) &&\n\t\t\t!validFlags.includes(normalizedFlag)\n\t\t) {\n\t\t\tthrow new ConfigError(`Invalid sigflag: ${sigflag}`);\n\t\t}\n\t}\n\n\tif (txindex !== undefined) {\n\t\tif (\n\t\t\ttypeof txindex !== \"number\" ||\n\t\t\t!Number.isInteger(txindex) ||\n\t\t\ttxindex < 0\n\t\t) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t\"txindex must be a non-negative integer\",\n\t\t\t\t\"txindex\",\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Sign a transaction input using segwit (BIP143) signature hashing.\n * @param seckey - 32-byte secret key as hex string (64 characters)\n * @param txdata - Transaction data\n * @param options - Sighash options including txindex, sigflag, pubkey/script\n * @returns ECDSA signature with sighash flag appended\n * @throws {ValidationError} If secret key format is invalid\n * @throws {ConfigError} If sigflag is invalid\n */\nexport function sign_segwit_tx(\n\tseckey: string,\n\ttxdata: TxData,\n\toptions: SigHashOptions,\n) {\n\tvalidate_seckey(seckey);\n\tvalidate_sighash_options(options, SIGHASH_SEGWIT);\n\n\tconst tx = parse_tx(txdata);\n\tconst msg = hash_segwit_tx(tx, options);\n\tconst sig = ECC.sign_ecdsa(seckey, msg).hex;\n\tconst flag = format_sigflag(options.sigflag ?? SIGHASH_DEFAULT);\n\treturn sig + flag;\n}\n\n/**\n * Sign a transaction input using taproot (BIP341) signature hashing.\n * @param seckey - 32-byte secret key as hex string (64 characters)\n * @param txdata - Transaction data\n * @param options - Sighash options including txindex, sigflag, extension\n * @returns Schnorr signature with optional sighash flag appended\n * @throws {ValidationError} If secret key format is invalid\n * @throws {ConfigError} If sigflag is invalid\n */\nexport function sign_taproot_tx(\n\tseckey: string,\n\ttxdata: TxData,\n\toptions: SigHashOptions,\n) {\n\tvalidate_seckey(seckey);\n\tvalidate_sighash_options(options, SIGHASH_TAPROOT);\n\n\tconst tx = parse_tx(txdata);\n\tconst msg = hash_taproot_tx(tx, options);\n\tconst sig = ECC.sign_bip340(seckey, msg).hex;\n\tconst flag = format_sigflag(options.sigflag ?? 0);\n\treturn sig + flag;\n}\n\nfunction format_sigflag(flag: number) {\n\treturn flag !== 0 ? Buff.num(flag, 1).hex : \"\";\n}\n","/**\n * Witness data parsing utilities.\n *\n * Functions for analyzing and parsing SegWit witness data to determine\n * spend type (P2WPKH, P2WSH, P2TR, P2TS) and extract relevant components.\n *\n * @module\n */\n\nimport { Buff, type Bytes } from \"@vbyte/buff\";\nimport { TAPLEAF_VERSIONS } from \"@/const.js\";\nimport { is_valid_script } from \"@/lib/script/decode.js\";\n\nimport type {\n\tSpendScriptType,\n\tWitnessData,\n\tWitnessVersion,\n} from \"@/types/index.js\";\n\n/**\n * Parse witness data to determine spend type and extract components.\n *\n * Analyzes witness stack to identify:\n * - P2WPKH: 2 elements (signature + pubkey)\n * - P2WSH: Multiple elements with witness script\n * - P2TR: Single Schnorr signature (key-path spend)\n * - P2TS: Taproot script-path spend (with control block)\n *\n * Also extracts annex data (BIP-341) and control block if present.\n *\n * @param witness - Array of witness elements as bytes\n * @returns Parsed witness data with type, version, params, script, etc.\n *\n * @example\n * ```typescript\n * const witnessData = parse_witness([signature, pubkey])\n * console.log(witnessData.type) // 'p2wpkh'\n * console.log(witnessData.version) // 0\n * ```\n */\nexport function parse_witness(witness: Bytes[]): WitnessData {\n\t// Parse the witness data.\n\tconst elems = witness.map((e) => Buff.bytes(e));\n\tconst stack = witness.map((e) => Buff.bytes(e).hex);\n\tconst annex = parse_annex_data(elems);\n\tif (annex !== null) elems.pop();\n\tconst cblock = parse_cblock_data(elems);\n\tif (cblock !== null) elems.pop();\n\tconst type = parse_witness_type(elems, cblock);\n\tconst version = parse_witness_version(type);\n\tconst script = parse_witness_script(elems, type);\n\tif (script !== null) elems.pop();\n\tconst params = elems.map((e) => e.hex);\n\treturn { annex, cblock, params, script, stack, type, version };\n}\n\nfunction parse_annex_data(data: Uint8Array[]): string | null {\n\t// Get the last element of the array.\n\tconst elem = data.at(-1);\n\t// Check if the element fits the annex format.\n\tif (data.length > 1 && elem instanceof Uint8Array && elem[0] === 0x50) {\n\t\t// Return the element.\n\t\treturn new Buff(elem).hex;\n\t} else {\n\t\t// Return null.\n\t\treturn null;\n\t}\n}\n\nfunction parse_cblock_data(data: Uint8Array[]): string | null {\n\tconst elem = data.at(-1);\n\tif (\n\t\tdata.length > 1 &&\n\t\telem instanceof Uint8Array &&\n\t\telem.length > 32 &&\n\t\tTAPLEAF_VERSIONS.includes(elem[0] & 0xfe)\n\t) {\n\t\t// Return the element.\n\t\treturn new Buff(elem).hex;\n\t} else {\n\t\t// Return null.\n\t\treturn null;\n\t}\n}\n\nfunction parse_witness_script(\n\telems: Uint8Array[],\n\ttype: SpendScriptType | null,\n) {\n\tlet script: Uint8Array | undefined;\n\tswitch (type) {\n\t\tcase \"p2ts\":\n\t\t\tscript = elems.at(-1);\n\t\t\tbreak;\n\t\tcase \"p2wsh\":\n\t\t\tscript = elems.at(-1);\n\t\t\tbreak;\n\t}\n\treturn script !== undefined ? new Buff(script).hex : null;\n}\n\nfunction parse_witness_type(\n\telems: Uint8Array[],\n\tcblock: string | null,\n): SpendScriptType | null {\n\t// Get the important elements of the witness.\n\tconst param_0 = elems.at(0),\n\t\tparam_1 = elems.at(1),\n\t\tparam_x = elems.at(-1);\n\t// If the cblock is present and the last element exists:\n\tif (cblock !== null && param_x !== undefined) {\n\t\treturn \"p2ts\";\n\t\t// If the witness elements match the profile of a p2w-pkh:\n\t\t// ECDSA signatures are 71-73 bytes (DER-encoded), Schnorr are 64-65 bytes\n\t} else if (\n\t\telems.length === 2 &&\n\t\tparam_0 !== undefined &&\n\t\tparam_1 !== undefined &&\n\t\tparam_0.length >= 71 &&\n\t\tparam_0.length <= 73 &&\n\t\tparam_1.length === 33\n\t) {\n\t\treturn \"p2wpkh\";\n\t\t// If the witness elements match the profile of a p2tr-pk (Schnorr 64 or 65 bytes):\n\t} else if (\n\t\telems.length === 1 &&\n\t\tparam_0 !== undefined &&\n\t\t(param_0.length === 64 || param_0.length === 65)\n\t) {\n\t\treturn \"p2tr\";\n\t\t// If there is at least two witness elements:\n\t} else if (\n\t\telems.length > 1 &&\n\t\tparam_x !== undefined &&\n\t\tis_valid_script(param_x)\n\t) {\n\t\treturn \"p2wsh\";\n\t\t// If the witness elements don't match any known profile:\n\t} else {\n\t\treturn null;\n\t}\n}\n\nfunction parse_witness_version(\n\ttype: SpendScriptType | null,\n): WitnessVersion | null {\n\tif (type === null) return null;\n\tif (type.startsWith(\"p2w\")) return 0;\n\tif (type.startsWith(\"p2t\")) return 1;\n\treturn null;\n}\n","import { Buff, Stream } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/util\";\nimport { ECC } from \"@vbyte/crypto\";\nimport { DecodingError, ValidationError } from \"@/error.js\";\nimport { parse_witness } from \"@/lib/witness/parse.js\";\nimport type { ControlBlock } from \"@/types/index.js\";\nimport {\n\tencode_tapbranch,\n\tencode_tapscript,\n\tencode_taptweak,\n} from \"./encode.js\";\n\n/**\n * Parse a taproot script-path witness and extract spending data.\n * Computes the tapkey from the control block and verifies the merkle proof.\n *\n * @param witness - Array of witness stack elements (hex strings)\n * @returns Parsed taproot spending data including cblock, params, script, tapkey, and tweak\n * @throws Error if control block or script is missing\n *\n * @example\n * ```typescript\n * const witness = [signature, tapscript, controlBlock]\n * const { tapkey, script, params } = parse_taproot_witness(witness)\n * ```\n */\nexport function parse_taproot_witness(witness: string[]) {\n\tconst { cblock, params, script } = parse_witness(witness);\n\n\tAssert.exists(cblock, \"cblock is null\");\n\tAssert.exists(script, \"script is null\");\n\n\tconst cblk = parse_cblock(cblock);\n\tconst target = encode_tapscript(script, cblk.version);\n\n\tlet branch = target.hex;\n\n\tfor (const leaf of cblk.path) {\n\t\tbranch = encode_tapbranch(branch, leaf).hex;\n\t}\n\n\tconst tweak = encode_taptweak(cblk.int_key, branch);\n\tconst tapkey = ECC.tweak_pubkey(cblk.int_key, tweak, \"bip340\");\n\n\tconst hexParams = params.map((e) => Buff.bytes(e).hex);\n\n\treturn { cblock: cblk, params: hexParams, script, tapkey: tapkey.hex, tweak: tweak.hex };\n}\n\n/**\n * Parse a taproot control block into its components.\n * Extracts version, parity, internal pubkey, and merkle path.\n *\n * @param cblock - Control block data (hex string or bytes)\n * @returns Parsed control block with int_key, path, parity, and version\n * @throws Error if control block has invalid format or non-empty remainder\n *\n * @example\n * ```typescript\n * const cblock = 'c0' + internalPubkey + merkleProof\n * const { int_key, path, version, parity } = parse_cblock(cblock)\n * ```\n */\nexport function parse_cblock(cblock: string | Uint8Array): ControlBlock {\n\tconst buffer = new Stream(cblock);\n\tconst cbyte = buffer.read(1).num;\n\tconst int_key = buffer.read(32).hex;\n\tconst [version, parity] = parse_cblock_parity(cbyte);\n\tconst path = [];\n\twhile (buffer.size >= 32) {\n\t\tpath.push(buffer.read(32).hex);\n\t}\n\tif (buffer.size !== 0) {\n\t\tthrow new DecodingError(\n\t\t\t`control block has ${buffer.size} extra bytes. Expected: 33 + (32 * path_length) bytes`\n\t\t);\n\t}\n\treturn { int_key, path, parity, version };\n}\n\n/**\n * Parse the control block version byte to extract version and parity.\n * Even bytes indicate even parity (0x02), odd bytes indicate odd parity (0x03).\n *\n * @param cbits - Control block version byte\n * @returns Tuple of [version, parity] where version has parity bit cleared\n *\n * @example\n * ```typescript\n * parse_cblock_parity(0xc0) // [0xc0, 0x02] - even\n * parse_cblock_parity(0xc1) // [0xc0, 0x03] - odd\n * ```\n */\nexport function parse_cblock_parity(cbits: number) {\n\treturn cbits % 2 === 0 ? [cbits, 0x02] : [cbits - 1, 0x03];\n}\n\n/**\n * Parse a compressed public key to extract its parity bit.\n * Returns 0 for even y-coordinate (0x02 prefix), 1 for odd (0x03 prefix).\n *\n * @param pubkey - 33-byte compressed public key (hex string or bytes)\n * @returns Parity bit: 0 for even, 1 for odd\n * @throws Error if pubkey is not 33 bytes or has invalid prefix\n *\n * @example\n * ```typescript\n * parse_pubkey_parity('02' + x_coordinate) // 0 (even)\n * parse_pubkey_parity('03' + x_coordinate) // 1 (odd)\n * ```\n */\nexport function parse_pubkey_parity(pubkey: string | Uint8Array): number {\n\tAssert.ok(Buff.bytes(pubkey).length === 33, \"invalid pubkey size\");\n\tconst [parity] = Buff.bytes(pubkey);\n\tif (parity === 0x02) return 0;\n\tif (parity === 0x03) return 1;\n\tthrow new ValidationError(\n\t\t`invalid pubkey parity prefix: 0x${parity.toString(16)}. Expected 0x02 (even) or 0x03 (odd)`\n\t);\n}\n","import { Buff } from \"@vbyte/buff\";\nimport { ValidationError } from \"@/error.js\";\nimport type { MerkleProof, TapTree } from \"@/types/index.js\";\nimport { encode_tapbranch } from \"./encode.js\";\n\n/** Maximum taproot tree depth (BIP-341 limit) */\nconst MAX_TAPROOT_DEPTH = 128;\n\n/**\n * Get the root of a taproot tree.\n * @param leaves - The leaves of the tree.\n * @returns The root of the tree.\n */\nexport function get_merkle_root(leaves: TapTree) {\n\t// Process the merkle tree, and return the root.\n\treturn merkleize(leaves)[0];\n}\n\n/**\n * Process a taproot tree into a merkle proof.\n * @param taptree - The leaves of the tree.\n * @param target - The target leaf of the tree.\n * @param path - The recursive path of the tree.\n * @param depth - Current recursion depth (for limit checking).\n * @returns The root of the tree.\n * @throws Error if tree depth exceeds MAX_TAPROOT_DEPTH (128).\n */\nexport function merkleize(\n\ttaptree: TapTree,\n\ttarget?: string,\n\tpath: string[] = [],\n\tdepth: number = 0,\n): MerkleProof {\n\t// Check depth limit to prevent stack overflow attacks\n\tif (depth > MAX_TAPROOT_DEPTH) {\n\t\tthrow new ValidationError(\n\t\t\t`Taproot tree depth ${depth} exceeds maximum ${MAX_TAPROOT_DEPTH}`,\n\t\t\t\"depth\",\n\t\t);\n\t}\n\n\t// Initialize the leaves and tree arrays.\n\tconst leaves: string[] = [];\n\tconst tree: string[] = [];\n\t// If there are no leaves, throw an error.\n\tif (taptree.length < 1) {\n\t\tthrow new ValidationError(\"Taproot tree cannot be empty\", \"taptree\");\n\t}\n\t// Crawl through the tree, and find each leaf.\n\tfor (let i = 0; i < taptree.length; i++) {\n\t\t// Get the current leaf as bytes.\n\t\tconst bytes = taptree[i];\n\t\t// If the leaf is an array,\n\t\tif (Array.isArray(bytes)) {\n\t\t\t// Recursively process the nested tree (with incremented depth).\n\t\t\tconst [tapleaf, new_target, branches] = merkleize(\n\t\t\t\tbytes,\n\t\t\t\ttarget,\n\t\t\t\t[],\n\t\t\t\tdepth + 1,\n\t\t\t);\n\t\t\t// Update the target leaf.\n\t\t\ttarget = new_target;\n\t\t\t// Add the nested tapleaf to the leaves array.\n\t\t\tleaves.push(tapleaf);\n\t\t\t// For each branch node,\n\t\t\tfor (const branch of branches) {\n\t\t\t\t// Add the branch to the path.\n\t\t\t\tpath.push(branch);\n\t\t\t}\n\t\t} else {\n\t\t\t// Convert the leaf to a hex string.\n\t\t\tconst leaf = Buff.bytes(bytes).hex;\n\t\t\t// Add the leaf to the leaves array.\n\t\t\tleaves.push(leaf);\n\t\t}\n\t}\n\n\t// If there is only one leaf,\n\tif (leaves.length === 1) {\n\t\t// Return the leaf as the root.\n\t\treturn [leaves[0], target, path];\n\t}\n\t// Ensure the tree is sorted at this point.\n\tleaves.sort();\n\t// Ensure the tree is balanced evenly.\n\tif (leaves.length % 2 !== 0) {\n\t\t// If uneven, duplicate the last leaf.\n\t\tleaves.push(leaves[leaves.length - 1]);\n\t}\n\t// Sort through the leaves (two at a time).\n\tfor (let i = 0; i < leaves.length - 1; i += 2) {\n\t\t// Compute two leaves into a branch.\n\t\tconst branch = encode_tapbranch(leaves[i], leaves[i + 1]).hex;\n\t\t// Push our branch to the tree.\n\t\ttree.push(branch);\n\t\t// Check if a proof target is specified.\n\t\tif (typeof target === \"string\") {\n\t\t\t// Check if this branch is part of our proofs.\n\t\t\tif (target === leaves[i]) {\n\t\t\t\t// If so, include right-side of branch.\n\t\t\t\tpath.push(leaves[i + 1]);\n\t\t\t\ttarget = branch;\n\t\t\t} else if (target === leaves[i + 1]) {\n\t\t\t\t// If so, include left-side of branch.\n\t\t\t\tpath.push(leaves[i]);\n\t\t\t\ttarget = branch;\n\t\t\t}\n\t\t}\n\t}\n\t// Recursively process the tree (with incremented depth).\n\treturn merkleize(tree, target, path, depth + 1);\n}\n","/**\n * Taproot control block utilities.\n *\n * Functions for creating and verifying taproot control blocks,\n * which are used for script-path spending in BIP-341.\n *\n * @see https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki\n * @module\n */\n\nimport { Buff, type Bytes } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/util\";\nimport { ECC } from \"@vbyte/crypto\";\nimport { TAPLEAF_DEFAULT_VERSION } from \"@/const.js\";\nimport * as Schema from \"@/schema/index.js\";\nimport type { TaprootConfig, TaprootContext } from \"@/types/index.js\";\n\nimport { encode_tapbranch, encode_taptweak } from \"./encode.js\";\n\nimport { parse_cblock, parse_pubkey_parity } from \"./parse.js\";\nimport { merkleize } from \"./tree.js\";\n\nconst DEFAULT_VERSION = TAPLEAF_DEFAULT_VERSION;\n\n/**\n * Create a taproot output with optional script tree.\n *\n * Computes the tweaked public key (tapkey) and control block for\n * spending via key-path or script-path.\n *\n * @param config - Taproot configuration with internal key and optional leaves\n * @returns Taproot context with tapkey, control block, and merkle path\n *\n * @example\n * ```typescript\n * // Key-path only (no scripts)\n * const ctx = create_taproot({ pubkey: internalKey })\n *\n * // With script tree\n * const ctx = create_taproot({\n * pubkey: internalKey,\n * leaves: [leaf1, leaf2],\n * target: targetLeafHash\n * })\n * ```\n */\nexport function create_taproot(config: TaprootConfig): TaprootContext {\n\tSchema.taproot.config.parse(config);\n\n\tconst { pubkey, version = DEFAULT_VERSION } = config;\n\n\tconst leaves = config.leaves ?? [];\n\n\tconst target =\n\t\tconfig.target !== undefined ? Buff.bytes(config.target).hex : undefined;\n\n\tlet path: string[] = [],\n\t\ttaproot: string | undefined;\n\n\tif (leaves.length > 0) {\n\t\t// Merkelize the leaves into a root hash (with proof).\n\t\tconst [root, _, proofs] = merkleize(leaves, target);\n\t\t// Get the control path from the merkelized output.\n\t\tpath = proofs;\n\t\t// Get the tapped key from the internal key.\n\t\ttaproot = root;\n\t} else {\n\t\t// Get the tapped key from the single tapleaf.\n\t\ttaproot = target;\n\t}\n\n\tconst taptweak = encode_taptweak(pubkey, taproot);\n\tconst twk_key = ECC.tweak_pubkey(pubkey, taptweak, \"ecdsa\");\n\tconst parity = parse_pubkey_parity(twk_key);\n\tconst tapkey = ECC.serialize_pubkey(twk_key, \"bip340\");\n\t// Get the block version / parity bit.\n\tconst cbit = Buff.num(version + parity);\n\t// Stack the initial control block data.\n\tconst block: Bytes[] = [cbit, Buff.bytes(pubkey)];\n\t// If there is more than one path, add to block.\n\tif (path.length > 0) {\n\t\tblock.push(...path);\n\t}\n\t// Merge the data together into one array.\n\tconst cblock = Buff.join(block);\n\n\treturn {\n\t\tint_key: Buff.bytes(pubkey).hex,\n\t\tpath,\n\t\tparity,\n\t\ttaproot: taproot ?? null,\n\t\tcblock: cblock.hex,\n\t\ttapkey: tapkey.hex,\n\t\ttaptweak: taptweak.hex,\n\t};\n}\n\n/**\n * Verify a taproot control block against a tapkey and target leaf.\n *\n * Reconstructs the tapkey from the control block's internal key,\n * merkle path, and target leaf hash, then compares to the expected tapkey.\n *\n * @param tapkey - Expected taproot output key (32 bytes, x-only)\n * @param target - Target leaf hash being verified\n * @param cblock - Control block containing parity, internal key, and path\n * @returns True if the control block is valid for this tapkey and target\n *\n * @example\n * ```typescript\n * const isValid = verify_taproot(tapkey, leafHash, controlBlock)\n * if (!isValid) {\n * throw new Error('Control block verification failed')\n * }\n * ```\n */\nexport function verify_taproot(\n\ttapkey: string,\n\ttarget: string,\n\tcblock: string,\n): boolean {\n\tAssert.ok(Buff.bytes(tapkey).length === 32, \"tapkey must be 32 bytes\");\n\tconst { parity, path, int_key } = parse_cblock(cblock);\n\n\tconst ext_key = Buff.join([parity, tapkey]);\n\n\tlet branch = Buff.bytes(target).hex;\n\n\tfor (const leaf of path) {\n\t\tbranch = encode_tapbranch(branch, leaf).hex;\n\t}\n\n\tconst tap_tweak = encode_taptweak(int_key, branch);\n\tconst tweaked_key = ECC.tweak_pubkey(int_key, tap_tweak, \"ecdsa\");\n\n\treturn ext_key.hex === tweaked_key.hex;\n}\n","import { Buff, type Bytes } from \"@vbyte/buff\";\nimport { ECC } from \"@vbyte/crypto\";\nimport { hash160 } from \"@vbyte/crypto/hash\";\nimport { ValidationError } from \"@/error.js\";\nimport { hash_segwit_tx } from \"@/lib/sighash/segwit.js\";\nimport { hash_taproot_tx } from \"@/lib/sighash/taproot.js\";\nimport { verify_taproot } from \"@/lib/taproot/cblock.js\";\nimport { encode_tapscript } from \"@/lib/taproot/encode.js\";\nimport { parse_tx } from \"@/lib/tx/index.js\";\nimport { parse_witness } from \"@/lib/witness/parse.js\";\n\nimport type {\n\tSigHashOptions,\n\tTxData,\n\tTxInput,\n\tWitnessData,\n} from \"@/types/index.js\";\n\nexport interface VerifyOptions extends SigHashOptions {\n\t/** Throw an error on verification failure (default: false) */\n\tthrows?: boolean;\n}\n\nexport interface VerifyResult {\n\t/** Whether all signatures are valid */\n\tvalid: boolean;\n\t/** Per-input verification results */\n\tinputs: InputVerifyResult[];\n\t/** Error message if verification failed */\n\terror?: string;\n}\n\nexport interface InputVerifyResult {\n\t/** Input index */\n\tindex: number;\n\t/** Whether the signature is valid */\n\tvalid: boolean;\n\t/** Spend type detected */\n\ttype?: string | null;\n\t/** Error message if verification failed */\n\terror?: string;\n}\n\n/**\n * Verify all signatures in a transaction.\n * @param txdata - Transaction data (hex, bytes, or TxData object)\n * @param options - Verification options\n * @returns Verification result with per-input details\n */\nexport function verify_tx(\n\ttxdata: TxData | Bytes,\n\toptions: VerifyOptions = {},\n): VerifyResult {\n\tconst { throws = false } = options;\n\n\tconst tx = parse_tx(txdata);\n\tconst inputs: InputVerifyResult[] = [];\n\tlet allValid = true;\n\n\tfor (let i = 0; i < tx.vin.length; i++) {\n\t\tconst vin = tx.vin[i];\n\n\t\t// Skip coinbase inputs\n\t\tif (vin.coinbase !== null) {\n\t\t\tinputs.push({ index: i, valid: true, type: \"coinbase\" });\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst result = verify_input(tx, vin, i, options);\n\t\tinputs.push(result);\n\n\t\tif (!result.valid) {\n\t\t\tallValid = false;\n\t\t\tif (throws) {\n\t\t\t\tthrow new ValidationError(`Input ${i} verification failed: ${result.error}`, `vin[${i}]`);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tvalid: allValid,\n\t\tinputs,\n\t\terror: allValid ? undefined : \"One or more inputs failed verification\",\n\t};\n}\n\n/**\n * Verify a single input signature.\n */\nfunction verify_input(\n\ttx: TxData,\n\tvin: TxInput,\n\tindex: number,\n\toptions: VerifyOptions,\n): InputVerifyResult {\n\ttry {\n\t\tconst { witness = [] } = vin;\n\n\t\t// No witness means no signature to verify\n\t\tif (witness.length === 0) {\n\t\t\treturn { index, valid: true, type: null };\n\t\t}\n\n\t\t// Parse the witness data\n\t\tconst witnessData = parse_witness(witness.map((e) => Buff.hex(e)));\n\t\tconst { type, version } = witnessData;\n\n\t\t// No recognizable type means we can't verify\n\t\tif (type === null || version === null) {\n\t\t\treturn { index, valid: false, type, error: \"Unknown witness type\" };\n\t\t}\n\n\t\t// Get the prevout script\n\t\tconst prevout = vin.prevout;\n\t\tif (prevout === null || prevout === undefined) {\n\t\t\treturn { index, valid: false, type, error: \"Missing prevout data\" };\n\t\t}\n\n\t\t// Dispatch to the appropriate verification method\n\t\tif (version === 0) {\n\t\t\treturn verify_segwit_input(tx, vin, index, witnessData, options);\n\t\t} else if (version === 1) {\n\t\t\treturn verify_taproot_input(tx, vin, index, witnessData, options);\n\t\t}\n\n\t\treturn {\n\t\t\tindex,\n\t\t\tvalid: false,\n\t\t\ttype,\n\t\t\terror: `Unsupported witness version: ${version}`,\n\t\t};\n\t} catch (err) {\n\t\tconst error = err instanceof Error ? err.message : String(err);\n\t\treturn { index, valid: false, error };\n\t}\n}\n\n/**\n * Verify a segwit (v0) input signature using ECDSA.\n */\nfunction verify_segwit_input(\n\ttx: TxData,\n\tvin: TxInput,\n\tindex: number,\n\twitnessData: WitnessData,\n\toptions: VerifyOptions,\n): InputVerifyResult {\n\tconst { type, params, script } = witnessData;\n\n\tif (params.length < 1) {\n\t\treturn { index, valid: false, type, error: \"Missing signature in witness\" };\n\t}\n\n\t// Extract signature and sighash flag\n\tconst sigHex = params[0];\n\tconst { signature, sigflag } = parse_ecdsa_signature(sigHex);\n\n\t// Get pubkey and script for hash calculation\n\tlet pubkey: string;\n\tlet hashScript: string;\n\n\tif (type === \"p2wpkh\") {\n\t\t// P2WPKH: pubkey is second witness element\n\t\tif (params.length < 2) {\n\t\t\treturn {\n\t\t\t\tindex,\n\t\t\t\tvalid: false,\n\t\t\t\ttype,\n\t\t\t\terror: \"Missing pubkey in P2WPKH witness\",\n\t\t\t};\n\t\t}\n\t\tpubkey = params[1];\n\n\t\t// P2WPKH script is derived from pubkey hash\n\t\tconst pkh = hash160(pubkey).hex;\n\t\thashScript = `76a914${pkh}88ac`;\n\t} else if (type === \"p2wsh\") {\n\t\t// P2WSH: script is witness script, need to find pubkey in params\n\t\tif (script === null) {\n\t\t\treturn {\n\t\t\t\tindex,\n\t\t\t\tvalid: false,\n\t\t\t\ttype,\n\t\t\t\terror: \"Missing script in P2WSH witness\",\n\t\t\t};\n\t\t}\n\t\thashScript = script;\n\n\t\t// For P2WSH, we need to extract the pubkey from the script or params\n\t\t// This is a simplified approach - in practice the pubkey needs to be specified\n\t\tif (params.length >= 2) {\n\t\t\tpubkey = params[1];\n\t\t} else {\n\t\t\treturn {\n\t\t\t\tindex,\n\t\t\t\tvalid: false,\n\t\t\t\ttype,\n\t\t\t\terror: \"Missing pubkey in P2WSH witness\",\n\t\t\t};\n\t\t}\n\t} else {\n\t\treturn {\n\t\t\tindex,\n\t\t\tvalid: false,\n\t\t\ttype,\n\t\t\terror: `Unexpected segwit type: ${type}`,\n\t\t};\n\t}\n\n\t// Calculate the sighash\n\tconst sighashOptions: SigHashOptions = {\n\t\t...options,\n\t\ttxindex: index,\n\t\ttxinput: vin,\n\t\tpubkey: type === \"p2wpkh\" ? pubkey : undefined,\n\t\tscript: type === \"p2wsh\" ? hashScript : undefined,\n\t\tsigflag,\n\t};\n\n\tconst hash = hash_segwit_tx(tx, sighashOptions);\n\n\t// Verify the ECDSA signature\n\tconst isValid = ECC.verify_ecdsa(signature, hash, pubkey);\n\n\treturn {\n\t\tindex,\n\t\tvalid: isValid,\n\t\ttype,\n\t\terror: isValid ? undefined : \"Invalid ECDSA signature\",\n\t};\n}\n\n/**\n * Verify a taproot (v1) input signature using Schnorr.\n */\nfunction verify_taproot_input(\n\ttx: TxData,\n\tvin: TxInput,\n\tindex: number,\n\twitnessData: WitnessData,\n\toptions: VerifyOptions,\n): InputVerifyResult {\n\tconst { type, params, script, cblock } = witnessData;\n\n\tif (vin.prevout == null) {\n\t\treturn {\n\t\t\tindex,\n\t\t\tvalid: false,\n\t\t\ttype,\n\t\t\terror: \"Missing prevout for taproot verification\",\n\t\t};\n\t}\n\tconst prevout = vin.prevout;\n\n\tif (params.length < 1) {\n\t\treturn { index, valid: false, type, error: \"Missing signature in witness\" };\n\t}\n\n\t// Extract signature and sighash flag\n\tconst sigHex = params[0];\n\tconst { signature, sigflag } = parse_schnorr_signature(sigHex);\n\n\t// Get the tapkey from the prevout script (remove 5120 prefix)\n\tconst tapkey = prevout.script_pk.slice(4);\n\n\tlet pubkey: string;\n\tlet extension: string | undefined;\n\n\tif (type === \"p2tr\") {\n\t\t// Key-path spend: pubkey is the tapkey\n\t\tpubkey = tapkey;\n\t} else if (type === \"p2ts\") {\n\t\t// Script-path spend: verify control block and get internal key\n\t\tif (cblock === null || script === null) {\n\t\t\treturn {\n\t\t\t\tindex,\n\t\t\t\tvalid: false,\n\t\t\t\ttype,\n\t\t\t\terror: \"Missing cblock or script in script-path spend\",\n\t\t\t};\n\t\t}\n\n\t\t// Verify the control block path\n\t\tconst target = encode_tapscript(script).hex;\n\t\tconst pathValid = verify_taproot(tapkey, target, cblock);\n\n\t\tif (!pathValid) {\n\t\t\treturn {\n\t\t\t\tindex,\n\t\t\t\tvalid: false,\n\t\t\t\ttype,\n\t\t\t\terror: \"Control block verification failed\",\n\t\t\t};\n\t\t}\n\n\t\t// For script-path, we need a pubkey from the script or additional witness elements\n\t\t// The pubkey for signing is usually in the additional params\n\t\tif (params.length >= 2 && params[1].length === 64) {\n\t\t\tpubkey = params[1];\n\t\t} else {\n\t\t\t// Fallback to tapkey for verification\n\t\t\tpubkey = tapkey;\n\t\t}\n\n\t\t// Set the extension (tapleaf hash)\n\t\textension = target;\n\t} else {\n\t\treturn {\n\t\t\tindex,\n\t\t\tvalid: false,\n\t\t\ttype,\n\t\t\terror: `Unexpected taproot type: ${type}`,\n\t\t};\n\t}\n\n\t// Calculate the sighash\n\tconst sighashOptions: SigHashOptions = {\n\t\t...options,\n\t\ttxindex: index,\n\t\ttxinput: vin,\n\t\tsigflag,\n\t\textension: extension,\n\t\tscript: type === \"p2ts\" ? (script ?? undefined) : undefined,\n\t};\n\n\tconst hash = hash_taproot_tx(tx, sighashOptions);\n\n\t// Verify the Schnorr signature\n\tconst isValid = ECC.verify_bip340(signature, hash, pubkey);\n\n\treturn {\n\t\tindex,\n\t\tvalid: isValid,\n\t\ttype,\n\t\terror: isValid ? undefined : \"Invalid Schnorr signature\",\n\t};\n}\n\n/**\n * Parse an ECDSA DER-encoded signature and extract sighash flag.\n */\nfunction parse_ecdsa_signature(sigHex: string): {\n\tsignature: string;\n\tsigflag: number;\n} {\n\t// ECDSA sigs are DER-encoded, last byte is sighash flag\n\tconst sigBytes = Buff.hex(sigHex);\n\tconst sigflag = sigBytes.at(-1) ?? 0x01;\n\tconst signature = sigBytes.slice(0, -1).hex;\n\treturn { signature, sigflag };\n}\n\n/**\n * Parse a Schnorr signature and extract sighash flag.\n */\nfunction parse_schnorr_signature(sigHex: string): {\n\tsignature: string;\n\tsigflag: number;\n} {\n\t// Schnorr sigs are 64 bytes, optional sighash byte appended\n\tconst sigBytes = Buff.hex(sigHex);\n\n\tif (sigBytes.length === 64) {\n\t\t// No sighash appended, default to SIGHASH_DEFAULT (0x00)\n\t\treturn { signature: sigHex, sigflag: 0x00 };\n\t} else if (sigBytes.length === 65) {\n\t\t// Sighash byte appended\n\t\tconst sigflag = sigBytes.at(-1) ?? 0x00;\n\t\tif (sigflag === 0x00) {\n\t\t\tthrow new ValidationError(\"0x00 is not a valid appended sigflag (use 64-byte signature for SIGHASH_DEFAULT)\", \"sigflag\");\n\t\t}\n\t\tconst signature = sigBytes.slice(0, 64).hex;\n\t\treturn { signature, sigflag };\n\t}\n\n\tthrow new ValidationError(`Invalid Schnorr signature length: ${sigBytes.length} (expected 64 or 65 bytes)`, \"signature\");\n}\n","/**\n * Witness utility functions.\n *\n * Helper functions for working with transaction witness data,\n * including size calculation and validation.\n *\n * @module\n */\n\nimport { Buff, type Bytes } from \"@vbyte/buff\";\nimport { Assert } from \"@vbyte/util\";\n\nimport type { WitnessSize } from \"@/types/index.js\";\n\n/** Overhead for witness element count varint */\nconst WIT_LENGTH_BYTE = 1;\n\n/**\n * Calculate the size of witness data.\n *\n * Returns both the total byte size and the virtual size (vsize).\n * Witness data is weighted at 1/4 for virtual size calculation.\n *\n * @param witness - Array of witness stack elements\n * @returns Object with total bytes and virtual size\n *\n * @example\n * ```typescript\n * const size = get_witness_size(['304402...', '02abc...'])\n * // { total: 107, vsize: 28 }\n * ```\n */\nexport function get_witness_size(witness: Bytes[]): WitnessSize {\n\tconst stack = witness.map((e) => Buff.bytes(e));\n\tconst size = stack.reduce((prev, next) => prev + next.length, 0);\n\tconst vsize = Math.ceil(WIT_LENGTH_BYTE + size / 4);\n\treturn { total: size, vsize };\n}\n\n/**\n * Assert that a value is a valid witness array.\n *\n * A valid witness is an array of byte-like elements (hex strings or Uint8Array).\n * Throws if the validation fails.\n *\n * @param witness - Value to validate\n * @throws Error if witness is not an array of bytes\n *\n * @example\n * ```typescript\n * assert_witness(['304402...', '02abc...']) // passes\n * assert_witness('not an array') // throws\n * assert_witness([123]) // throws (numbers not allowed)\n * ```\n */\nexport function assert_witness(witness: unknown): asserts witness is Bytes[] {\n\tAssert.ok(Array.isArray(witness), \"witness must be an array\");\n\tAssert.ok(\n\t\twitness.every((e) => Buff.is_bytes(e)),\n\t\t\"witness must be an array of strings or bytes\",\n\t);\n}\n"],"names":["COINBASE","TXID","repeat","VOUT","DEFAULT","LOCKTIME","SEQUENCE","VERSION","TAPLEAF_VERSIONS","LOCK_SCRIPT_TYPE","P2PKH","P2SH","P2WPKH","P2WSH","P2TR","OPRETURN","LOCK_SCRIPT_REGEX","SIGHASH_SEGWIT","SIGHASH_TAPROOT","MAX_SCRIPT_SIZE","MAX_VARINT_SIZE","Check","P2TS","GLOBAL_BASE","GLOBAL_WIT","TXIN_BASE","TXOUT_BASE","is_hex","input","match","length","is_bytes","Uint8Array","Array","isArray","every","e","Number","isInteger","Error","constructor","message","super","this","name","HexValidationError","ValidationError","ByteRangeError","IntegerBoundsError","SizeError","Assert","within_size","data","size","hex","bytes","String","is_json","str","JSON","parse","is_safe_int","num","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","_0n","BigInt","_255n","_256n","big_to_bytes","big","endian","undefined","TypeError","get_big_size","use_le","buffer","ArrayBuffer","dataView","DataView","offset","byte","setUint8","bigint_replacer","_","v","bigint_reviver","test","slice","num_to_bytes","get_num_size","hex_to_bytes","hexstr","len","get_hex_size","use_be","i","char","substring","parseInt","fill","set","create_bytes","ec","TextEncoder","dc","TextDecoder","str_to_bytes","encode","bytes_to_str","decode","MAX_RANDOM_LENGTH","Buff","number","bigint","bin","uint","binary","bins","split","map","ct","j","Lib.bin_to_bytes","u8a","Lib.str_to_bytes","json","replacer","Lib.bigint_replacer","stringify","chunk","payload","chunk_size","total_size","chunks","data_blob","count","idx","subarray","Lib.split_bytes","Lib.buffer","is_equal","a","b","buf_a","buf_b","random","RangeError","crypto","getRandomValues","pcrypto","randomBytes","Lib.get_random_bytes","now","stamp","Math","floor","Date","arr","to_arr","to_big","to_bin","to_hex","to_num","to_str","to_u8a","Lib.bytes_to_big","reverse","chars","toString","padStart","Lib.bytes_to_hex","to_json","reviver","Lib.bigint_reviver","Lib.bytes_to_str","Lib.bytes_to_num","join","Lib.bytes_to_bin","append","equals","other","prepend","prefix_varint","varint","create_varint","array","start","end","begin","toJSON","from","of","args","joined","reduce","buff","Lib.join_bytes","sort","Stream","peek","read","read_varint","field","DecodingError","position","ConfigError","get_lock_script_type","script","type","regex","Object","entries","get_lock_script_version","at","is_p2pkh_script","p2pkh","is_p2sh_script","p2sh","is_p2wpkh_script","p2wpkh","is_p2wsh_script","p2wsh","is_p2tr_script","p2tr","obj","Map","Set","keys","filter","key","sorted","Test","isBytes","isView","anumber","n","title","isSafeInteger","abytes","value","needsLen","ahash","h","create","outputLen","blockLen","aexists","instance","checkFinished","destroyed","finished","clean","arrays","createView","byteOffset","byteLength","rotr","word","shift","rotl","is_object","is_string","is_integer","is_function","exists","is_deep_equal","has_items","is_number","isFinite","is_bigint","is_uchar","is_ushort","is_uint","is_u8a","is_base58","is_base64","is_b64url","is_bech32","is_hash","is_null","is_undefined","is_array","is_error","is_promise","Promise","then","catch","ok","msg","is_empty","is_instance","err_msg","hasHexBuiltin","toHex","fromHex","hexes","bytesToHex","asciis","asciiToBase16","ch","hexToBytes","hl","al","ai","hi","n1","charCodeAt","n2","concatBytes","sum","res","pad","createHasher","hashCons","info","hashC","opts","update","digest","tmp","assign","freeze","bytesLength","cr","globalThis","oidNist","suffix","oid","_HMAC","oHash","iHash","hash","buf","digestInto","out","destroy","_cloneInto","to","getPrototypeOf","clone","hmac","Chi","c","Maj","HashMD","padOffset","isLE","view","pos","take","min","process","roundClean","aoutput","setBigUint64","oview","outLen","state","get","setUint32","SHA256_IV","Uint32Array","Rho160","Id160","Pi160","idxLR","push","k","idxL","idxR","shifts160","shiftsL160","shiftsR160","Kl160","Kr160","ripemd_f","group","x","y","z","BUF_160","_RIPEMD160","h0","h1","h2","h3","h4","getUint32","ar","bl","br","cl","dl","dr","el","er","rGroup","hbl","hbr","rl","rr","sl","sr","tl","tr","ripemd160","SHA256_K","SHA256_W","SHA2_32B","A","B","C","D","E","F","G","H","W15","W2","s0","s1","T1","T2","_SHA256","sha256","hash160","noble_r160","noble_s256","hash256","hash340","tag","htag","hashtag","_1n","abool","abignumber","isPosBig","numberToHexUnpadded","hexToNumber","bytesToNumberBE","bytesToHex_","bytesToNumberLE","copyBytes","abytes_","numberToBytesBE","hexToBytes_","numberToBytesLE","aInRange","max","inRange","bitMask","validateObject","object","fields","optFields","iter","f","isOpt","forEach","fieldName","expectedType","val","current","checkField","memoized","fn","WeakMap","arg","computed","_2n","_3n","_4n","_5n","_7n","_8n","_9n","_16n","mod","result","pow2","power","modulo","invert","u","r","m","assertIsSquare","Fp","root","eql","sqr","sqrt3mod4","p1div4","ORDER","pow","sqrt5mod8","p5div8","mul","nv","sub","ONE","tonelliShanks","P","Q","S","Z","_Fp","Field","FpLegendre","cc","Q1div2","is0","M","t","R","ZERO","t_tmp","exponent","FpSqrt","Fp_","tn","c1","neg","c2","c3","c4","tv1","tv2","tv3","tv4","e1","e2","cmov","e3","sqrt9mod16","FIELD_FIELDS","FpInvertBatch","nums","passZero","inverted","multipliedAcc","acc","invertedAcc","inv","reduceRight","p1mod2","powered","yes","zero","no","_Field","BITS","BYTES","_lengths","_sqrt","_mod","_nbitLength","sqrt","allowedLengths","modFromBytes","nBitLength","nByteLength","_nBitLength","ceil","nLength","preventExtensions","isValid","isValidNot0","isOdd","lhs","rhs","add","p","d","FpPow","div","sqrN","addN","subN","mulN","toBytes","fromBytes","skipValidation","includes","padded","scalar","invertBatch","lst","condition","getFieldBytesLength","fieldOrder","bitLength","getMinHashLength","mapHashToField","fieldLen","minLen","reduced","negateCt","item","negate","normalizeZ","points","invertedZs","fromAffine","toAffine","validateW","W","bits","calcWOpts","scalarBits","maxNumber","windows","windowSize","mask","shiftBy","calcOffsets","window","wOpts","wbits","nextN","offsetStart","abs","isZero","isNeg","isNegF","offsetF","pointPrecomputes","pointWindowSizes","getW","assert0","wNAF","BASE","Fn","Point","_unsafeLadder","elm","double","precomputeWindow","point","base","precomputes","wo","wNAFUnsafe","getPrecomputes","transform","comp","cached","unsafe","prev","createCache","delete","hasCache","createField","order","validateField","createKeygen","randomSecretKey","getPublicKey","seed","secretKey","publicKey","divNearest","den","_splitEndoScalar","basis","a1","b1","a2","b2","k1","k2","k1neg","k2neg","MAX_NUM","bitLen","validateSigFormat","format","validateSigOpts","def","optsn","optName","lowS","prehash","DERErr","DER","Err","_tlv","dataLen","lenLen","first","lengthBytes","l","_int","toSig","int","tlv","seqBytes","seqLeftBytes","rBytes","rLeftBytes","sBytes","sLeftBytes","s","hexFromSig","sig","seq","weierstrass","params","extraOpts","validated","CURVE","curveOpts","FpFnLE","createCurveFields","cofactor","CURVE_ORDER","allowInfinityPoint","clearCofactor","isTorsionFree","endo","beta","basises","lengths","getWLengths","assertCompressionIsSupported","encodePoint","_c","isCompressed","bx","pprefix","decodePoint","publicKeyUncompressed","uncomp","head","tail","L","isValidXY","y2","weierstrassEquation","sqrtError","err","x2","x3","left","right","Gx","Gy","_4a3","_27b2","acoord","banZero","aprjpoint","splitEndoScalarN","toAffineMemo","iz","X","Y","zz","assertValidMemo","finishEndo","endoBeta","k1p","k2p","static","assertValidity","precompute","isLazy","wnaf","multiply","hasEvenY","X1","Y1","Z1","X2","Y2","Z2","U1","U2","b3","X3","Y3","Z3","t0","t1","t2","t3","t4","t5","subtract","fake","k1f","k2f","multiplyUnsafe","sc","p1","p2","mulEndoUnsafe","invertedZ","isSmallOrder","publicKeyHasPrefix","signature","ecdsa","ecdsaOpts","bits2int","bits2int_modN","wcRandomBytes","nobleHmac","fnBits","keygen","getSharedSecret","utils","ecdhOpts","randomBytes_","isProbPub","isValidSecretKey","error","isValidPublicKey","secretKeyA","publicKeyB","ecdh","defaultSigOpts","extraEntropy","hasLargeCofactor","isBiggerThanHalfOrder","validateRS","assertSmallCofactor","validateSigLength","Signature","recovery","recid","assertRecovery","addRecoveryBit","recoverPublicKey","messageHash","radj","ir","u1","u2","hasHighS","rb","sb","delta","ORDER_MASK","int2octets","validateMsgAndHash","sign","k2sig","h1int","seedArgs","kBytes","ik","q","normS","prepSig","hashLen","qByteLen","hmacFn","u8n","NULL","byte0","byte1","reset","msgs","concatBytes_","reseed","gen","pred","createHmacDrbg","drbg","verify","is","secp256k1_CURVE","secp256k1_ENDO","Fpk1","_6n","_11n","_22n","_23n","_44n","_88n","b6","b9","b11","b22","b44","b88","b176","b220","b223","Pointk1","secp256k1","TAGGED_HASH_PREFIXES","taggedHash","messages","tagP","tagH","ascii","charCode","pointToBytes","hasEven","schnorrGetExtPubKey","priv","d_","lift_x","xx","challenge","schnorrGetPublicKey","schnorrSign","auxRand","px","rand","rx","schnorrVerify","pub","schnorr","GP","tweak_pubkey","pubkey","tweak","even_y","twk_big","serialize_bytes","pub_pt","pk","serialize_pubkey","lift_point","tweak_pt","tweaked_pt","prefix","isArrayOf","isString","afn","astr","label","aArr","astrArr","anumArr","chain","id","wrap","alphabet","letters","lettersA","indexes","digits","letter","separator","convertRadix","dlen","carry","done","digit","fromCarry","digitBase","rounded","gcd","radix2carry","powers","convertRadix2","padding","radix2","revPadding","unsafeWrapper","apply","base64","toBase64","fromBase64","lastChunkHandling","decodeBase64Builtin","chr","base64urlnopad","base58","abc","radix","createBase58check","oldChecksum","newChecksum","BECH_ALPHABET","POLYMOD_GENERATORS","bech32Polymod","pre","chk","bechChecksum","words","encodingConst","genBech32","encoding","ENCODING_CONST","_words","fromWords","toWords","fromWordsUnsafe","limit","plen","actualLength","lowered","toLowerCase","slen","toUpperCase","sepIndex","lastIndexOf","endsWith","encodeFromBytes","decodeToBytes","decodeUnsafe","bech32","bech32m","B58chk","Base64","B64url","Bech32","Bech32m","assert_prefix","assert_words","to_words","to_bytes","ENCODING_REGEX","decode_address","address","get_address_format","encoded","version","base58_decode","rest","bech32_decode","bech32m_decode","encode_address","config","base58_encode","bech32_encode","bech32m_encode","get_address_script","script_key","script_type","asm","get_p2pkh_script","get_p2sh_script","get_p2w_pkh_script","get_p2w_sh_script","get_p2tr_script","CONFIG_TABLE","get_address_config","address_network","address_type","network","get_address_info","dec","startsWith","ADDRESS_TYPE","create_p2pkh_address","encode_p2pkh_address","create_p2pkh_script","encode_p2pkh_script","pk_hash","decode_p2pkh_script","decode_p2pkh_address","parsed","create_address","create_script","encode_script","decode_script","create_p2sh_address","encode_p2sh_address","encode_p2sh_script","create_p2sh_script","script_hash","script_pk","decode_p2sh_script","decode_p2sh_address","create_p2tr_address","encode_p2tr_address","create_p2tr_script","encode_p2tr_script","decode_p2tr_script","decode_p2tr_address","create_p2wpkh_address","encode_p2wpkh_address","create_p2wpkh_script","encode_p2wpkh_script","decode_p2wpkh_script","decode_p2wpkh_address","create_p2wsh_address","encode_p2wsh_address","create_p2wsh_script","encode_p2wsh_script","decode_p2wsh_script","decode_p2wsh_address","LOCKTIME_THRESHOLD","LocktimeField","RefPointer","encode_locktime","locktime","height","decode_locktime","isNaN","encode_inscription_id","txid","decode_inscription_id","inscription_id","assert_inscription_id","verify_inscription_id","encode_rune_id","block_height","block_index","decode_rune_id","rune_id","assert_rune_id","verify_rune_id","encode_outpoint","vout","decode_outpoint","outpoint","assert_outpoint","verify_outpoint","assert","record_id","OPCODE_MAP","OP_0","OP_PUSHDATA1","OP_PUSHDATA2","OP_PUSHDATA4","OP_1NEGATE","OP_SUCCESS80","OP_1","OP_2","OP_3","OP_4","OP_5","OP_6","OP_7","OP_8","OP_9","OP_10","OP_11","OP_12","OP_13","OP_14","OP_15","OP_16","OP_NOP","OP_SUCCESS98","OP_IF","OP_NOTIF","OP_ELSE","OP_ENDIF","OP_VERIFY","OP_RETURN","OP_TOALTSTACK","OP_FROMALTSTACK","OP_2DROP","OP_2DUP","OP_3DUP","OP_2OVER","OP_2ROT","OP_2SWAP","OP_IFDUP","OP_DEPTH","OP_DROP","OP_DUP","OP_NIP","OP_OVER","OP_PICK","OP_ROLL","OP_ROT","OP_SWAP","OP_TUCK","OP_SUCCESS126","OP_SUCCESS127","OP_SUCCESS128","OP_SUCCESS129","OP_SIZE","OP_SUCCESS131","OP_SUCCESS132","OP_SUCCESS133","OP_SUCCESS134","OP_EQUAL","OP_EQUALVERIFY","OP_SUCCESS137","OP_SUCCESS138","OP_1ADD","OP_1SUB","OP_SUCCESS141","OP_SUCCESS142","OP_NEGATE","OP_ABS","OP_NOT","OP_0NOTEQUAL","OP_ADD","OP_SUB","OP_SUCCESS149","OP_SUCCESS150","OP_SUCCESS151","OP_SUCCESS152","OP_SUCCESS153","OP_BOOLAND","OP_BOOLOR","OP_NUMEQUAL","OP_NUMEQUALVERIFY","OP_NUMNOTEQUAL","OP_LESSTHAN","OP_GREATERTHAN","OP_LESSTHANOREQUAL","OP_GREATERTHANOREQUAL","OP_MIN","OP_MAX","OP_WITHIN","OP_RIPEMD160","OP_SHA1","OP_SHA256","OP_HASH160","OP_HASH256","OP_CODESEPARATOR","OP_CHECKSIG","OP_CHECKSIGVERIFY","OP_CHECKMULTISIG","OP_CHECKMULTISIGVERIFY","OP_NOP1","OP_CHECKLOCKTIMEVERIFY","OP_CHECKSEQUENCEVERIFY","OP_NOP4","OP_NOP5","OP_NOP6","OP_NOP7","OP_NOP8","OP_NOP9","OP_NOP10","OP_CHECKSIGADD","get_op_code","get_asm_code","string","get_op_type","is_valid_op","stream","stack","stack_size","word_type","word_size","is_valid_script","MAX_WORD_SIZE","encode_script_word","asm_code","split_script_word","prefix_word_size","get_size_varint","_26n","InscriptionUtil","decode_inscription","envelopes","start_idx","indexOf","stop_idx","env","parse_envelopes","parse_record","encode_inscription","create_envelope","delegate","encode_id","ref","parent","opcode","code","encode_pointer","pointer","ptr","rune","encode_rune_label","mimetype","encode_label","content","encode_content","envelope","record","decode_label","decode_pointer","decode_id","decode_rune_label","decode_bytes","decode_content","normalize_script_word","identifier","parts","normalized","fromCharCode","TIMELOCK_TYPE","TIMELOCK_VALUE_MASK","TIMELOCK_VALUE_MAX","SequenceField","encode_sequence","mode","parse_height","ts","parse_stamp","decode_sequence","sequence","parse_sequence","prefix_script_size","opreturn","matchAll","MAX_TX_SIZE","MAX_TX_ELEMENTS","decode_tx","txdata","use_segwit","txSize","read_version","has_witness","marker","flag","check_witness_flag","vin","inputs","vinCount","txinput","read_vin","read_inputs","outputs","vcount","read_vout","read_outputs","txin","witness","read_witness","read_locktime","script_sig","read_payload","coinbase","prevout","element","$constructor","initializer","init","inst","_zod","defineProperty","constr","traits","enumerable","has","proto","prototype","bind","Parent","Definition","_a","deferred","Symbol","hasInstance","$ZodAsyncError","$ZodEncodeError","globalConfig","newConfig","getEnumValues","numericValues","values","jsonStringifyReplacer","getter","nullish","cleanRegex","source","EVALUATING","defineLazy","configurable","assignProp","target","prop","writable","mergeDefs","defs","mergedDescriptors","descriptors","getOwnPropertyDescriptors","defineProperties","esc","captureStackTrace","_args","isObject","allowsEval","navigator","userAgent","Function","isPlainObject","o","ctor","prot","hasOwnProperty","call","shallowClone","propertyKeyTypes","escapeRegex","replace","normalizeParams","_params","NUMBER_FORMAT_RANGES","safeint","int32","uint32","float32","float64","MAX_VALUE","aborted","startIndex","issues","continue","prefixIssues","path","iss","unshift","unwrapMessage","finalizeIssue","ctx","full","customError","localeError","reportInput","getLengthableOrigin","issue","util.jsonStringifyReplacer","$ZodError","$ZodRealError","_parse","_Err","schema","_ctx","async","run","core.$ZodAsyncError","util.finalizeIssue","core.config","util.captureStackTrace","callee","_parseAsync","_safeParse","success","errors.$ZodError","safeParse","errors.$ZodRealError","_safeParseAsync","safeParseAsync","_encode","direction","_decode","_encodeAsync","_decodeAsync","_safeEncode","_safeDecode","_safeEncodeAsync","_safeDecodeAsync","cuid","cuid2","ulid","xid","ksuid","nanoid","duration","guid","uuid","RegExp","email","ipv4","ipv6","cidrv4","cidrv6","base64url","e164","dateSource","date","timeSource","hhmm","precision","integer","boolean","_null","lowercase","uppercase","$ZodCheck","core.$constructor","onattach","numericOriginMap","$ZodCheckLessThan","origin","bag","curr","inclusive","maximum","exclusiveMaximum","POSITIVE_INFINITY","check","getTime","abort","$ZodCheckGreaterThan","minimum","exclusiveMinimum","NEGATIVE_INFINITY","$ZodCheckMultipleOf","multipleOf","step","valDecCount","stepString","stepDecCount","decCount","toFixed","util.floatSafeRemainder","divisor","$ZodCheckNumberFormat","isInt","util.NUMBER_FORMAT_RANGES","pattern","regexes.integer","expected","note","$ZodCheckMaxLength","when","util.nullish","util.getLengthableOrigin","$ZodCheckMinLength","$ZodCheckLengthEquals","tooBig","exact","$ZodCheckStringFormat","_b","patterns","lastIndex","$ZodCheckRegex","$ZodCheckLowerCase","regexes.lowercase","$ZodCheckUpperCase","regexes.uppercase","$ZodCheckIncludes","escapedRegex","util.escapeRegex","$ZodCheckStartsWith","$ZodCheckEndsWith","$ZodCheckOverwrite","tx","Doc","indent","indented","write","execution","lines","minIndent","trimStart","dedented","line","compile","major","minor","patch","$ZodType","checks","runChecks","asyncResult","isAborted","util.aborted","currLen","resolve","handleCanaryResult","canary","checkResult","skipChecks","util.defineLazy","validate","vendor","$ZodString","pop","coerce","$ZodStringFormat","checks.$ZodCheckStringFormat","$ZodGUID","regexes.guid","$ZodUUID","v1","v2","v3","v4","v5","v6","v7","v8","regexes.uuid","$ZodEmail","regexes.email","$ZodURL","trimmed","trim","url","URL","hostname","protocol","normalize","href","$ZodEmoji","$ZodNanoID","regexes.nanoid","$ZodCUID","regexes.cuid","$ZodCUID2","regexes.cuid2","$ZodULID","regexes.ulid","$ZodXID","regexes.xid","$ZodKSUID","regexes.ksuid","$ZodISODateTime","time","local","timeRegex","regexes.datetime","$ZodISODate","regexes.date","$ZodISOTime","$ZodISODuration","regexes.duration","$ZodIPv4","regexes.ipv4","$ZodIPv6","regexes.ipv6","$ZodCIDRv4","regexes.cidrv4","$ZodCIDRv6","regexes.cidrv6","prefixNum","isValidBase64","atob","$ZodBase64","regexes.base64","contentEncoding","$ZodBase64URL","regexes.base64url","padEnd","isValidBase64URL","$ZodE164","regexes.e164","$ZodJWT","token","algorithm","tokensParts","header","parsedHeader","typ","alg","isValidJWT","$ZodNumber","regexes.number","received","$ZodNumberFormat","checks.$ZodCheckNumberFormat","$ZodBoolean","regexes.boolean","Boolean","$ZodBigInt","regexes.bigint","$ZodNull","regexes.null","$ZodUnknown","$ZodNever","handleArrayResult","final","index","util.prefixIssues","$ZodArray","proms","all","handlePropertyResult","isOptionalOut","normalizeDef","shape","okeys","optin","optout","keySet","numKeys","optionalKeys","handleCatchall","unrecognized","_catchall","catchall","$ZodObject","desc","getOwnPropertyDescriptor","sh","newSh","_normalized","util.cached","propValues","util.isObject","$ZodObjectJIT","superParse","fastpass","jit","core.globalConfig","jitless","fastEnabled","util.allowsEval","doc","parseStr","util.esc","ids","counter","generateFastpass","handleUnionResults","results","nonaborted","errors","$ZodUnion","options","some","flatMap","option","util.cleanRegex","single","$ZodIntersection","handleIntersectionResults","mergeValues","valid","util.isPlainObject","bKeys","sharedKeys","newObj","sharedValue","mergeErrorPath","newArray","unrecKeys","unrecIssue","bothKeys","merged","$ZodRecord","keyType","recordKeys","valueType","Reflect","ownKeys","keyResult","retryResult","$ZodEnum","util.getEnumValues","valuesSet","util.propertyKeyTypes","$ZodTransform","core.$ZodEncodeError","_out","output","handleOptionalResult","$ZodOptional","innerType","$ZodExactOptional","$ZodNullable","$ZodDefault","defaultValue","handleDefaultResult","$ZodPrefault","$ZodNonOptional","handleNonOptionalResult","$ZodCatch","catchValue","$ZodPipe","in","handlePipeResult","next","$ZodReadonly","handleReadonlyResult","$ZodLazy","$ZodCustom","checks.$ZodCheck","handleRefineResult","_iss","util.issue","$ZodRegistry","_map","_idmap","_meta","meta","clear","remove","pm","__zod_globalRegistry","globalRegistry","_guid","Class","util.normalizeParams","_lt","checks.$ZodCheckLessThan","_lte","_gt","checks.$ZodCheckGreaterThan","_gte","_multipleOf","checks.$ZodCheckMultipleOf","_maxLength","checks.$ZodCheckMaxLength","_minLength","checks.$ZodCheckMinLength","_length","checks.$ZodCheckLengthEquals","_overwrite","checks.$ZodCheckOverwrite","_superRefine","_check","addIssue","_issue","fatal","initializeContext","processors","metadataRegistry","metadata","unrepresentable","override","io","seen","cycles","reused","external","schemaPath","cycle","overrideSchema","toJSONSchema","processJSONSchema","_json","processor","isParent","isTransforming","examples","default","_prefault","extractDefs","idToSchema","entry","existing","extractToDef","$ref","defId","defsSegment","externalId","registry","uriGenerator","uri","defUriPrefix","makeURI","ext","finalize","flattenRef","zodSchema","_cached","refSeen","refSchema","allOf","parentSeen","jsonSchema","$schema","$id","$defs","definitions","finalized","createStandardJSONSchemaMethod","_err","_schema","items","libraryOptions","formatMap","datetime","json_string","optionalProcessor","ZodISODateTime","core.$ZodISODateTime","schemas.ZodStringFormat","core._isoDateTime","ZodISODate","core.$ZodISODate","core._isoDate","ZodISOTime","core.$ZodISOTime","core._isoTime","ZodISODuration","core.$ZodISODuration","core._isoDuration","ZodRealError","mapper","fieldErrors","_errors","processError","core.formatError","flatten","formErrors","core.flattenError","addIssues","isEmpty","core._parse","parseAsync","core._parseAsync","core._safeParse","core._safeParseAsync","core._encode","core._decode","encodeAsync","core._encodeAsync","decodeAsync","core._decodeAsync","safeEncode","core._safeEncode","safeDecode","core._safeDecode","safeEncodeAsync","core._safeEncodeAsync","safeDecodeAsync","core._safeDecodeAsync","ZodType","core.$ZodType","createToJSONSchemaMethod","util.mergeDefs","with","core.clone","brand","register","reg","parse.parse","parse.safeParse","parse.parseAsync","parse.safeParseAsync","spa","parse.encode","parse.decode","parse.encodeAsync","parse.decodeAsync","parse.safeEncode","parse.safeDecode","parse.safeEncodeAsync","parse.safeDecodeAsync","refine","core._refine","ZodCustom","superRefine","refinement","core._superRefine","overwrite","checks.overwrite","optional","exactOptional","ZodExactOptional","nullable","nonoptional","ZodNonOptional","or","union","and","ZodIntersection","pipe","ZodTransform","_default","ZodDefault","util.shallowClone","prefault","ZodPrefault","_catch","ZodCatch","readonly","ZodReadonly","describe","description","core.globalRegistry","isOptional","isNullable","_ZodString","core.$ZodString","minLength","maxLength","regexes","processors.stringProcessor","checks.$ZodCheckRegex","checks.regex","checks.$ZodCheckIncludes","checks.includes","checks.$ZodCheckStartsWith","checks.startsWith","checks.$ZodCheckEndsWith","checks.endsWith","checks.minLength","checks.maxLength","checks.length","nonempty","checks.$ZodCheckLowerCase","checks.lowercase","checks.$ZodCheckUpperCase","checks.uppercase","form","checks.normalize","slugify","util.slugify","ZodString","core._email","ZodEmail","core._url","ZodURL","jwt","core._jwt","ZodJWT","emoji","core._emoji","ZodEmoji","core._guid","ZodGUID","core._uuid","ZodUUID","uuidv4","core._uuidv4","uuidv6","core._uuidv6","uuidv7","core._uuidv7","core._nanoid","ZodNanoID","core._cuid","ZodCUID","core._cuid2","ZodCUID2","core._ulid","ZodULID","core._base64","ZodBase64","core._base64url","ZodBase64URL","core._xid","ZodXID","core._ksuid","ZodKSUID","core._ipv4","ZodIPv4","core._ipv6","ZodIPv6","core._cidrv4","ZodCIDRv4","core._cidrv6","ZodCIDRv6","core._e164","ZodE164","iso.datetime","iso.date","iso.time","iso.duration","core._string","ZodStringFormat","core.$ZodStringFormat","core.$ZodEmail","core.$ZodGUID","core.$ZodUUID","core.$ZodURL","core.$ZodEmoji","core.$ZodNanoID","core.$ZodCUID","core.$ZodCUID2","core.$ZodULID","core.$ZodXID","core.$ZodKSUID","core.$ZodIPv4","core.$ZodIPv6","core.$ZodCIDRv4","core.$ZodCIDRv6","core.$ZodBase64","core.$ZodBase64URL","core.$ZodE164","core.$ZodJWT","ZodNumber","core.$ZodNumber","processors.numberProcessor","gt","checks.gt","gte","checks.gte","lt","checks.lt","lte","checks.lte","safe","positive","nonnegative","negative","nonpositive","checks.multipleOf","finite","minValue","maxValue","core._number","ZodNumberFormat","core.$ZodNumberFormat","core._int","ZodBoolean","core.$ZodBoolean","processors.booleanProcessor","ZodBigInt","core.$ZodBigInt","processors.bigintProcessor","ZodNull","core.$ZodNull","enum","processors.nullProcessor","ZodUnknown","core.$ZodUnknown","unknown","ZodNever","core.$ZodNever","not","processors.neverProcessor","never","core._never","ZodArray","core.$ZodArray","minItems","maxItems","processors.arrayProcessor","unwrap","core._array","ZodObject","core.$ZodObjectJIT","properties","allKeys","requiredKeys","required","additionalProperties","processors.objectProcessor","keyof","fromEntries","ZodEnum","_enum","passthrough","loose","strict","strip","extend","incoming","existingShape","_shape","util.extend","safeExtend","util.safeExtend","merge","util.merge","pick","currDef","newShape","util.pick","omit","util.omit","partial","oldShape","util.partial","ZodOptional","util.required","ZodUnion","core.$ZodUnion","isExclusive","oneOf","anyOf","processors.unionProcessor","core.$ZodIntersection","isSimpleIntersection","processors.intersectionProcessor","ZodRecord","core.$ZodRecord","keyBag","valueSchema","patternProperties","propertyNames","keyValues","validKeyValues","processors.recordProcessor","core.$ZodEnum","processors.enumProcessor","extract","newEntries","exclude","core.$ZodTransform","processors.transformProcessor","core.$ZodOptional","processors.optionalProcessor","core.$ZodExactOptional","ZodNullable","core.$ZodNullable","inner","processors.nullableProcessor","core.$ZodDefault","processors.defaultProcessor","removeDefault","core.$ZodPrefault","processors.prefaultProcessor","core.$ZodNonOptional","processors.nonoptionalProcessor","core.$ZodCatch","processors.catchProcessor","removeCatch","ZodPipe","core.$ZodPipe","processors.pipeProcessor","in_","core.$ZodReadonly","readOnly","processors.readonlyProcessor","ZodLazy","core.$ZodLazy","processors.lazyProcessor","core.$ZodCustom","processors.customProcessor","z\n .number","cls","z.instanceof","z.string","z.number","z\n .string","literal","z.union","core._boolean","core._null","z.null","z.array","z.record","u8a32","u8a33","u8a64","hex32","hex33","hex64","byte32","taptree","z.object","leaves","sats","core._bigint","z.bigint","tx_output","tx_input","tx_data","vout_template","vin_template","tx_template","format_zod_error","assert_tx_template","Schema.tx.tx_template","assert_has_prevouts","missingIdx","findIndex","assert_tx_data","Schema.tx.tx_data","assert_vin_template","Schema.tx.vin_template","assert_vout_template","Schema.tx.vout_template","encode_tx","encode_tx_version","encode_tx_inputs","encode_tx_outputs","encode_vin_witness","encode_tx_locktime","encode_txin_txid","encode_txin_vout","encode_txin_sequence","raw","encode_vin","encode_script_data","encode_vout_value","encode_tx_vout","txout","param","parse_tx","prevouts","create_tx","create_tx_output","transcode_tx","normalize_sequence","normalize_value","normalize_prevout","create_coinbase_input","create_virtual_input","create_spend_input","create_tx_input","Schema.tx.tx_input","Schema.tx.tx_output","txinputs","fees","txoutput","total","weight","vsize","get_prevout","parse_txinput","txindex","get_annex_data","annex","hash_segwit_tx","sigflag","is_anypay","CONST.SIGHASH_SEGWIT","prevIdx","pkhash","sighash","bip143_hash_prevouts","bip143_hash_sequence","bip143_hash_outputs","isAnypay","isAnyPay","encode_tapscript","encode_tapleaf","encode_leaf_version","encode_tapbranch","leaf_a","leaf_b","encode_taptweak","hash_taproot_tx","template","get_taproot_tx_preimage","extflag","key_version","separator_pos","CONST.SIGHASH_TAPROOT","extension","spendType","preimage","bip341_hash_outpoints","bip341_hash_amounts","bip341_hash_scripts","bip341_hash_sequence","bip341_hash_outputs","bip341_hash_output","SECKEY_REGEX","validate_seckey","seckey","validate_sighash_options","validFlags","normalizedFlag","baseFlag","format_sigflag","parse_witness","elems","elem","parse_annex_data","cblock","parse_cblock_data","param_0","param_1","param_x","parse_witness_type","parse_witness_version","parse_witness_script","parse_cblock","cbyte","int_key","parity","parse_cblock_parity","cbits","parse_pubkey_parity","merkleize","depth","tree","tapleaf","new_target","branches","branch","leaf","DEFAULT_VERSION","verify_taproot","tapkey","ext_key","tweaked_key","ECC.tweak_pubkey","verify_input","witnessData","sigHex","sigBytes","parse_ecdsa_signature","hashScript","sighashOptions","ECC.verify_ecdsa","verify_segwit_input","parse_schnorr_signature","ECC.verify_bip340","verify_taproot_input","sk","ECC.sign_ecdsa","ECC.sign_bip340","throws","allValid","Schema.taproot.config","taproot","proofs","taptweak","twk_key","ECC.serialize_pubkey","block","cblk"],"mappings":"qCAAO,MAAMA,EAAW,CACvBC,KAAM,KAAKC,OAAO,IAClBC,KAAM,YAGMC,EAAU,CACtBC,SAAU,EACVC,SAAU,WACVC,QAAS,GAGGC,EAAmB,CAC/B,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IACxE,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IACxE,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IACxE,IAAM,KAKMC,EAAmB,CAC/BC,MAAO,QACPC,KAAM,OACNC,OAAQ,SACRC,MAAO,QACPC,KAAM,OACNC,SAAU,YAYEC,EAA4C,CACxD,CAACP,EAAiBC,OAAQ,4BAC1B,CAACD,EAAiBE,MAAO,wBACzB,CAACF,EAAiBG,QAAS,s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