@darkbio/crypto 0.19.1 → 0.20.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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["textEncoder","uint.readUint8","uint.readUint16","uint.readUint32","neg1b","pos1b","uint.readUint64","uint.uintBoundaries","toToken","uint.readUint8","uint.readUint16","uint.readUint32","uint.readUint64","toToken","uint.readUint8","uint.readUint16","uint.readUint32","uint.readUint64","toToken","uint.readUint8","uint.readUint16","uint.readUint32","uint.readUint64","uint.readUint8","uint.readUint16","uint.readUint32","uint.readUint64","uint.readUint8","uint.readUint16","uint.readUint32","uint.readUint64","uint.decodeUint8","uint.decodeUint16","uint.decodeUint32","uint.decodeUint64","negint.decodeNegint8","negint.decodeNegint16","negint.decodeNegint32","negint.decodeNegint64","bytes.decodeBytesCompact","bytes.decodeBytes8","bytes.decodeBytes16","bytes.decodeBytes32","bytes.decodeBytes64","string.decodeStringCompact","string.decodeString8","string.decodeString16","string.decodeString32","string.decodeString64","array.decodeArrayCompact","array.decodeArray8","array.decodeArray16","array.decodeArray32","array.decodeArray64","array.decodeArrayIndefinite","map.decodeMapCompact","map.decodeMap8","map.decodeMap16","map.decodeMap32","map.decodeMap64","map.decodeMapIndefinite","tag.decodeTagCompact","tag.decodeTag8","tag.decodeTag16","tag.decodeTag32","tag.decodeTag64","float.decodeUndefined","float.decodeFloat16","float.decodeFloat32","float.decodeFloat64","float.decodeBreak","decode"],"sources":["../src/wasm/darkbio_crypto_wasm.js","../src/internal/init.ts","../src/internal/limits.ts","../src/rand.ts","../src/hkdf.ts","../src/argon2.ts","../node_modules/cborg/lib/is.js","../node_modules/cborg/lib/token.js","../node_modules/cborg/lib/byte-utils.js","../node_modules/cborg/lib/bl.js","../node_modules/cborg/lib/common.js","../node_modules/cborg/lib/0uint.js","../node_modules/cborg/lib/1negint.js","../node_modules/cborg/lib/2bytes.js","../node_modules/cborg/lib/3string.js","../node_modules/cborg/lib/4array.js","../node_modules/cborg/lib/5map.js","../node_modules/cborg/lib/6tag.js","../node_modules/cborg/lib/7float.js","../node_modules/cborg/lib/jump.js","../node_modules/cborg/lib/encode.js","../node_modules/cborg/lib/decode.js","../node_modules/cborg/lib/tagged.js","../src/internal/cborg.ts","../src/cbor.ts","../src/internal/bytes.ts","../src/xdsa.ts","../src/xhpke.ts","../src/cose.ts","../src/cwt.ts"],"sourcesContent":["/* @ts-self-types=\"./darkbio_crypto_wasm.d.ts\" */\n\n/**\n * Opaque xDSA fingerprint.\n */\nexport class XdsaFingerprint {\n static __wrap(ptr) {\n const obj = Object.create(XdsaFingerprint.prototype);\n obj.__wbg_ptr = ptr;\n XdsaFingerprintFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XdsaFingerprintFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xdsafingerprint_free(ptr, 0);\n }\n /**\n * Creates a fingerprint from a 32-byte array.\n * @param {Uint8Array} bytes\n * @returns {XdsaFingerprint}\n */\n static from_bytes(bytes) {\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xdsafingerprint_from_bytes(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XdsaFingerprint.__wrap(ret[0]);\n }\n /**\n * Serializes the fingerprint to a 32-byte array.\n * @returns {Uint8Array}\n */\n to_bytes() {\n const ret = wasm.xdsafingerprint_to_bytes(this.__wbg_ptr);\n var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v1;\n }\n}\nif (Symbol.dispose) XdsaFingerprint.prototype[Symbol.dispose] = XdsaFingerprint.prototype.free;\n\n/**\n * Opaque xDSA public key. Key material stays inside WASM memory.\n */\nexport class XdsaPublicKey {\n static __wrap(ptr) {\n const obj = Object.create(XdsaPublicKey.prototype);\n obj.__wbg_ptr = ptr;\n XdsaPublicKeyFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XdsaPublicKeyFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xdsapublickey_free(ptr, 0);\n }\n /**\n * Returns a 32-byte fingerprint uniquely identifying this key.\n * @returns {XdsaFingerprint}\n */\n fingerprint() {\n const ret = wasm.xdsapublickey_fingerprint(this.__wbg_ptr);\n return XdsaFingerprint.__wrap(ret);\n }\n /**\n * Creates a public key from a 1984-byte array.\n * @param {Uint8Array} bytes\n * @returns {XdsaPublicKey}\n */\n static from_bytes(bytes) {\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xdsapublickey_from_bytes(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XdsaPublicKey.__wrap(ret[0]);\n }\n /**\n * Parses a public key from PEM format.\n * @param {string} pem\n * @returns {XdsaPublicKey}\n */\n static from_pem(pem) {\n const ptr0 = passStringToWasm0(pem, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xdsapublickey_from_pem(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XdsaPublicKey.__wrap(ret[0]);\n }\n /**\n * Serializes the public key to a 1984-byte array.\n * @returns {Uint8Array}\n */\n to_bytes() {\n const ret = wasm.xdsapublickey_to_bytes(this.__wbg_ptr);\n var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v1;\n }\n /**\n * Serializes the public key to PEM format.\n * @returns {string}\n */\n to_pem() {\n let deferred1_0;\n let deferred1_1;\n try {\n const ret = wasm.xdsapublickey_to_pem(this.__wbg_ptr);\n deferred1_0 = ret[0];\n deferred1_1 = ret[1];\n return getStringFromWasm0(ret[0], ret[1]);\n } finally {\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n }\n /**\n * Verifies a signature on a message.\n * @param {Uint8Array} message\n * @param {XdsaSignature} signature\n * @returns {boolean}\n */\n verify(message, signature) {\n const ptr0 = passArray8ToWasm0(message, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n _assertClass(signature, XdsaSignature);\n const ret = wasm.xdsapublickey_verify(this.__wbg_ptr, ptr0, len0, signature.__wbg_ptr);\n return ret !== 0;\n }\n}\nif (Symbol.dispose) XdsaPublicKey.prototype[Symbol.dispose] = XdsaPublicKey.prototype.free;\n\n/**\n * Opaque xDSA secret key. Key material stays inside WASM memory.\n */\nexport class XdsaSecretKey {\n static __wrap(ptr) {\n const obj = Object.create(XdsaSecretKey.prototype);\n obj.__wbg_ptr = ptr;\n XdsaSecretKeyFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XdsaSecretKeyFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xdsasecretkey_free(ptr, 0);\n }\n /**\n * Returns a 32-byte fingerprint uniquely identifying this key.\n * @returns {XdsaFingerprint}\n */\n fingerprint() {\n const ret = wasm.xdsasecretkey_fingerprint(this.__wbg_ptr);\n return XdsaFingerprint.__wrap(ret);\n }\n /**\n * Creates a private key from a 64-byte seed, wiping the seed from WASM\n * memory before return.\n * @param {Uint8Array} bytes\n * @returns {XdsaSecretKey}\n */\n static from_bytes(bytes) {\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xdsasecretkey_from_bytes(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XdsaSecretKey.__wrap(ret[0]);\n }\n /**\n * Parses a secret key from PEM format, wiping the PEM from WASM memory\n * before return.\n * @param {string} pem\n * @returns {XdsaSecretKey}\n */\n static from_pem(pem) {\n const ptr0 = passStringToWasm0(pem, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xdsasecretkey_from_pem(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XdsaSecretKey.__wrap(ret[0]);\n }\n /**\n * Generates a new random private key.\n * @returns {XdsaSecretKey}\n */\n static generate() {\n const ret = wasm.xdsasecretkey_generate();\n return XdsaSecretKey.__wrap(ret);\n }\n /**\n * Returns the public key corresponding to this private key.\n * @returns {XdsaPublicKey}\n */\n public_key() {\n const ret = wasm.xdsasecretkey_public_key(this.__wbg_ptr);\n return XdsaPublicKey.__wrap(ret);\n }\n /**\n * Signs a message with this secret key.\n * @param {Uint8Array} message\n * @returns {XdsaSignature}\n */\n sign(message) {\n const ptr0 = passArray8ToWasm0(message, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xdsasecretkey_sign(this.__wbg_ptr, ptr0, len0);\n return XdsaSignature.__wrap(ret);\n }\n /**\n * Serializes the secret key to a 64-byte seed, copied straight into JS\n * memory so no unwiped copy is left in WASM memory.\n * @returns {Uint8Array}\n */\n to_bytes() {\n const ret = wasm.xdsasecretkey_to_bytes(this.__wbg_ptr);\n return ret;\n }\n /**\n * Serializes the secret key to PEM format, copied straight into a JS\n * string so no unwiped copy is left in WASM memory.\n * @returns {string}\n */\n to_pem() {\n const ret = wasm.xdsasecretkey_to_pem(this.__wbg_ptr);\n return ret;\n }\n}\nif (Symbol.dispose) XdsaSecretKey.prototype[Symbol.dispose] = XdsaSecretKey.prototype.free;\n\n/**\n * Opaque xDSA signature.\n */\nexport class XdsaSignature {\n static __wrap(ptr) {\n const obj = Object.create(XdsaSignature.prototype);\n obj.__wbg_ptr = ptr;\n XdsaSignatureFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XdsaSignatureFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xdsasignature_free(ptr, 0);\n }\n /**\n * Creates a signature from a 3373-byte array.\n * @param {Uint8Array} bytes\n * @returns {XdsaSignature}\n */\n static from_bytes(bytes) {\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xdsasignature_from_bytes(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XdsaSignature.__wrap(ret[0]);\n }\n /**\n * Serializes the signature to a 3373-byte array.\n * @returns {Uint8Array}\n */\n to_bytes() {\n const ret = wasm.xdsasignature_to_bytes(this.__wbg_ptr);\n var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v1;\n }\n}\nif (Symbol.dispose) XdsaSignature.prototype[Symbol.dispose] = XdsaSignature.prototype.free;\n\n/**\n * Opaque xHPKE fingerprint.\n */\nexport class XhpkeFingerprint {\n static __wrap(ptr) {\n const obj = Object.create(XhpkeFingerprint.prototype);\n obj.__wbg_ptr = ptr;\n XhpkeFingerprintFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XhpkeFingerprintFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xhpkefingerprint_free(ptr, 0);\n }\n /**\n * Creates a fingerprint from a 32-byte array.\n * @param {Uint8Array} bytes\n * @returns {XhpkeFingerprint}\n */\n static from_bytes(bytes) {\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkefingerprint_from_bytes(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XhpkeFingerprint.__wrap(ret[0]);\n }\n /**\n * Serializes the fingerprint to a 32-byte array.\n * @returns {Uint8Array}\n */\n to_bytes() {\n const ret = wasm.xhpkefingerprint_to_bytes(this.__wbg_ptr);\n var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v1;\n }\n}\nif (Symbol.dispose) XhpkeFingerprint.prototype[Symbol.dispose] = XhpkeFingerprint.prototype.free;\n\n/**\n * Opaque xHPKE public key. Key material stays inside WASM memory.\n */\nexport class XhpkePublicKey {\n static __wrap(ptr) {\n const obj = Object.create(XhpkePublicKey.prototype);\n obj.__wbg_ptr = ptr;\n XhpkePublicKeyFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XhpkePublicKeyFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xhpkepublickey_free(ptr, 0);\n }\n /**\n * Returns a 32-byte fingerprint uniquely identifying this key.\n * @returns {XhpkeFingerprint}\n */\n fingerprint() {\n const ret = wasm.xhpkepublickey_fingerprint(this.__wbg_ptr);\n return XhpkeFingerprint.__wrap(ret);\n }\n /**\n * Creates a public key from a 1216-byte array.\n * @param {Uint8Array} bytes\n * @returns {XhpkePublicKey}\n */\n static from_bytes(bytes) {\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkepublickey_from_bytes(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XhpkePublicKey.__wrap(ret[0]);\n }\n /**\n * Parses a public key from PEM format.\n * @param {string} pem\n * @returns {XhpkePublicKey}\n */\n static from_pem(pem) {\n const ptr0 = passStringToWasm0(pem, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkepublickey_from_pem(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XhpkePublicKey.__wrap(ret[0]);\n }\n /**\n * Creates an HPKE sender context for multi-message encryption.\n * @param {Uint8Array} domain\n * @returns {XhpkeSender}\n */\n new_sender(domain) {\n const ptr0 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkepublickey_new_sender(this.__wbg_ptr, ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XhpkeSender.__wrap(ret[0]);\n }\n /**\n * Encrypts a single-shot message to this public key, wiping the plaintext\n * from WASM memory before return.\n * Returns: encapsulated key (1120 bytes) || ciphertext\n * @param {Uint8Array} msg_to_seal\n * @param {Uint8Array} msg_to_auth\n * @param {Uint8Array} domain\n * @returns {Uint8Array}\n */\n seal(msg_to_seal, msg_to_auth, domain) {\n const ptr0 = passArray8ToWasm0(msg_to_seal, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkepublickey_seal(this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v4 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v4;\n }\n /**\n * Serializes the public key to a 1216-byte array.\n * @returns {Uint8Array}\n */\n to_bytes() {\n const ret = wasm.xhpkepublickey_to_bytes(this.__wbg_ptr);\n var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v1;\n }\n /**\n * Serializes the public key to PEM format.\n * @returns {string}\n */\n to_pem() {\n let deferred1_0;\n let deferred1_1;\n try {\n const ret = wasm.xhpkepublickey_to_pem(this.__wbg_ptr);\n deferred1_0 = ret[0];\n deferred1_1 = ret[1];\n return getStringFromWasm0(ret[0], ret[1]);\n } finally {\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n }\n}\nif (Symbol.dispose) XhpkePublicKey.prototype[Symbol.dispose] = XhpkePublicKey.prototype.free;\n\n/**\n * Stateful HPKE receiver for multi-message decryption.\n */\nexport class XhpkeReceiver {\n static __wrap(ptr) {\n const obj = Object.create(XhpkeReceiver.prototype);\n obj.__wbg_ptr = ptr;\n XhpkeReceiverFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XhpkeReceiverFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xhpkereceiver_free(ptr, 0);\n }\n /**\n * Decrypts a message using the next nonce in the sequence. The plaintext\n * is copied straight into JS memory so no unwiped copy is left in WASM\n * memory.\n * @param {Uint8Array} msg_to_open\n * @param {Uint8Array} msg_to_auth\n * @returns {Uint8Array}\n */\n open(msg_to_open, msg_to_auth) {\n const ptr0 = passArray8ToWasm0(msg_to_open, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkereceiver_open(this.__wbg_ptr, ptr0, len0, ptr1, len1);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n}\nif (Symbol.dispose) XhpkeReceiver.prototype[Symbol.dispose] = XhpkeReceiver.prototype.free;\n\n/**\n * Opaque xHPKE secret key. Key material stays inside WASM memory.\n */\nexport class XhpkeSecretKey {\n static __wrap(ptr) {\n const obj = Object.create(XhpkeSecretKey.prototype);\n obj.__wbg_ptr = ptr;\n XhpkeSecretKeyFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XhpkeSecretKeyFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xhpkesecretkey_free(ptr, 0);\n }\n /**\n * Returns a 32-byte fingerprint uniquely identifying this key.\n * @returns {XhpkeFingerprint}\n */\n fingerprint() {\n const ret = wasm.xhpkesecretkey_fingerprint(this.__wbg_ptr);\n return XhpkeFingerprint.__wrap(ret);\n }\n /**\n * Creates a private key from a 32-byte seed, wiping the seed from WASM\n * memory before return.\n * @param {Uint8Array} bytes\n * @returns {XhpkeSecretKey}\n */\n static from_bytes(bytes) {\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkesecretkey_from_bytes(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XhpkeSecretKey.__wrap(ret[0]);\n }\n /**\n * Parses a secret key from PEM format, wiping the PEM from WASM memory\n * before return.\n * @param {string} pem\n * @returns {XhpkeSecretKey}\n */\n static from_pem(pem) {\n const ptr0 = passStringToWasm0(pem, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkesecretkey_from_pem(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XhpkeSecretKey.__wrap(ret[0]);\n }\n /**\n * Generates a new random private key.\n * @returns {XhpkeSecretKey}\n */\n static generate() {\n const ret = wasm.xhpkesecretkey_generate();\n return XhpkeSecretKey.__wrap(ret);\n }\n /**\n * Creates an HPKE receiver context for multi-message decryption.\n * @param {Uint8Array} encap_key\n * @param {Uint8Array} domain\n * @returns {XhpkeReceiver}\n */\n new_receiver(encap_key, domain) {\n const ptr0 = passArray8ToWasm0(encap_key, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkesecretkey_new_receiver(this.__wbg_ptr, ptr0, len0, ptr1, len1);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XhpkeReceiver.__wrap(ret[0]);\n }\n /**\n * Decrypts a single-shot sealed message. The plaintext is copied straight\n * into JS memory so no unwiped copy is left in WASM memory.\n * Input: encapsulated key (1120 bytes) || ciphertext\n * @param {Uint8Array} sealed\n * @param {Uint8Array} msg_to_auth\n * @param {Uint8Array} domain\n * @returns {Uint8Array}\n */\n open(sealed, msg_to_auth, domain) {\n const ptr0 = passArray8ToWasm0(sealed, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkesecretkey_open(this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * Returns the public key corresponding to this private key.\n * @returns {XhpkePublicKey}\n */\n public_key() {\n const ret = wasm.xhpkesecretkey_public_key(this.__wbg_ptr);\n return XhpkePublicKey.__wrap(ret);\n }\n /**\n * Serializes the secret key to a 32-byte seed, copied straight into JS\n * memory so no unwiped copy is left in WASM memory.\n * @returns {Uint8Array}\n */\n to_bytes() {\n const ret = wasm.xhpkesecretkey_to_bytes(this.__wbg_ptr);\n return ret;\n }\n /**\n * Serializes the secret key to PEM format, copied straight into a JS\n * string so no unwiped copy is left in WASM memory.\n * @returns {string}\n */\n to_pem() {\n const ret = wasm.xhpkesecretkey_to_pem(this.__wbg_ptr);\n return ret;\n }\n}\nif (Symbol.dispose) XhpkeSecretKey.prototype[Symbol.dispose] = XhpkeSecretKey.prototype.free;\n\n/**\n * Stateful HPKE sender for multi-message encryption.\n */\nexport class XhpkeSender {\n static __wrap(ptr) {\n const obj = Object.create(XhpkeSender.prototype);\n obj.__wbg_ptr = ptr;\n XhpkeSenderFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XhpkeSenderFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xhpkesender_free(ptr, 0);\n }\n /**\n * Returns the 1120-byte encapsulated key.\n * @returns {Uint8Array}\n */\n encap_key() {\n const ret = wasm.xhpkesender_encap_key(this.__wbg_ptr);\n var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v1;\n }\n /**\n * Encrypts a message using the next nonce in the sequence, wiping the\n * plaintext from WASM memory before return.\n * @param {Uint8Array} msg_to_seal\n * @param {Uint8Array} msg_to_auth\n * @returns {Uint8Array}\n */\n seal(msg_to_seal, msg_to_auth) {\n const ptr0 = passArray8ToWasm0(msg_to_seal, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkesender_seal(this.__wbg_ptr, ptr0, len0, ptr1, len1);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v3;\n }\n}\nif (Symbol.dispose) XhpkeSender.prototype[Symbol.dispose] = XhpkeSender.prototype.free;\n\n/**\n * Derives a key from the password, salt, and cost parameters using Argon2id,\n * returning a byte array that can be used as a cryptographic key.\n *\n * RFC 9106 Section 4 recommends time=1, memory=2 GiB and threads=4, or, where\n * that much memory is not available, time=3, memory=64 MiB and threads=4. The\n * first profile needs exactly 2 GiB, which is past what this binding can\n * allocate. The threads parameter is Argon2's lane count, which changes the\n * derived key; it does not select how many threads compute it.\n *\n * All parameters are validated up front: the underlying implementation panics\n * on invalid inputs, which inside WASM would trap and poison the instance.\n * The password and the derived key are wiped from WASM memory before return.\n * @param {Uint8Array} password\n * @param {Uint8Array} salt\n * @param {number} time\n * @param {number} memory\n * @param {number} threads\n * @param {number} out_len\n * @returns {Uint8Array}\n */\nexport function argon2_key(password, salt, time, memory, threads, out_len) {\n const ptr0 = passArray8ToWasm0(password, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(salt, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.argon2_key(ptr0, len0, ptr1, len1, time, memory, threads, out_len);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * Verifies that data is valid CBOR using the restricted type system.\n * @param {Uint8Array} data\n */\nexport function cbor_verify(data) {\n const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.cbor_verify(ptr0, len0);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n}\n\n/**\n * Decrypts a sealed message without verifying the signature. The decrypted\n * COSE_Sign1 is copied straight into JS memory and the binding's own copy is\n * wiped; copies made inside crypto-rs are outside its reach.\n * @param {Uint8Array} msg_to_open\n * @param {Uint8Array} msg_to_auth\n * @param {XhpkeSecretKey} recipient\n * @param {Uint8Array} domain\n * @returns {Uint8Array}\n */\nexport function cose_decrypt(msg_to_open, msg_to_auth, recipient, domain) {\n const ptr0 = passArray8ToWasm0(msg_to_open, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n _assertClass(recipient, XhpkeSecretKey);\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.cose_decrypt(ptr0, len0, ptr1, len1, recipient.__wbg_ptr, ptr2, len2);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * Encrypts an already-signed COSE_Sign1 to a recipient. The binding's own copy\n * of the signed message is wiped before return.\n * @param {Uint8Array} sign1\n * @param {Uint8Array} msg_to_auth\n * @param {XhpkePublicKey} recipient\n * @param {Uint8Array} domain\n * @returns {Uint8Array}\n */\nexport function cose_encrypt(sign1, msg_to_auth, recipient, domain) {\n const ptr0 = passArray8ToWasm0(sign1, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n _assertClass(recipient, XhpkePublicKey);\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.cose_encrypt(ptr0, len0, ptr1, len1, recipient.__wbg_ptr, ptr2, len2);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v4 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v4;\n}\n\n/**\n * Decrypts and verifies a sealed message. The plaintext is copied straight\n * into JS memory and the binding's own copy is wiped; copies made inside\n * crypto-rs are outside its reach.\n * @param {Uint8Array} msg_to_open\n * @param {Uint8Array} msg_to_auth\n * @param {XhpkeSecretKey} recipient\n * @param {XdsaPublicKey} sender\n * @param {Uint8Array} domain\n * @param {bigint | null} [max_drift_secs]\n * @returns {Uint8Array}\n */\nexport function cose_open(msg_to_open, msg_to_auth, recipient, sender, domain, max_drift_secs) {\n const ptr0 = passArray8ToWasm0(msg_to_open, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n _assertClass(recipient, XhpkeSecretKey);\n _assertClass(sender, XdsaPublicKey);\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.cose_open(ptr0, len0, ptr1, len1, recipient.__wbg_ptr, sender.__wbg_ptr, ptr2, len2, !isLikeNone(max_drift_secs), isLikeNone(max_drift_secs) ? BigInt(0) : max_drift_secs);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * Extracts the embedded payload from a COSE_Sign1 without verifying.\n * @param {Uint8Array} signature\n * @returns {Uint8Array}\n */\nexport function cose_peek(signature) {\n const ptr0 = passArray8ToWasm0(signature, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.cose_peek(ptr0, len0);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v2;\n}\n\n/**\n * Extracts the recipient's fingerprint from a COSE_Encrypt0 without decrypting.\n * @param {Uint8Array} ciphertext\n * @returns {XhpkeFingerprint}\n */\nexport function cose_recipient(ciphertext) {\n const ptr0 = passArray8ToWasm0(ciphertext, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.cose_recipient(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XhpkeFingerprint.__wrap(ret[0]);\n}\n\n/**\n * Signs a message then encrypts it to a recipient (sign-then-encrypt). The\n * binding's own copy of the plaintext is wiped before return; copies made\n * inside crypto-rs are outside its reach.\n * @param {Uint8Array} msg_to_seal\n * @param {Uint8Array} msg_to_auth\n * @param {XdsaSecretKey} signer\n * @param {XhpkePublicKey} recipient\n * @param {Uint8Array} domain\n * @returns {Uint8Array}\n */\nexport function cose_seal(msg_to_seal, msg_to_auth, signer, recipient, domain) {\n const ptr0 = passArray8ToWasm0(msg_to_seal, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n _assertClass(signer, XdsaSecretKey);\n _assertClass(recipient, XhpkePublicKey);\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.cose_seal(ptr0, len0, ptr1, len1, signer.__wbg_ptr, recipient.__wbg_ptr, ptr2, len2);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v4 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v4;\n}\n\n/**\n * Creates a COSE_Sign1 signature with an embedded payload.\n * @param {Uint8Array} msg_to_embed\n * @param {Uint8Array} msg_to_auth\n * @param {XdsaSecretKey} signer\n * @param {Uint8Array} domain\n * @returns {Uint8Array}\n */\nexport function cose_sign(msg_to_embed, msg_to_auth, signer, domain) {\n const ptr0 = passArray8ToWasm0(msg_to_embed, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n _assertClass(signer, XdsaSecretKey);\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.cose_sign(ptr0, len0, ptr1, len1, signer.__wbg_ptr, ptr2, len2);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v4 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v4;\n}\n\n/**\n * Creates a COSE_Sign1 signature without an embedded payload (detached mode).\n * @param {Uint8Array} msg_to_auth\n * @param {XdsaSecretKey} signer\n * @param {Uint8Array} domain\n * @returns {Uint8Array}\n */\nexport function cose_sign_detached(msg_to_auth, signer, domain) {\n const ptr0 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n _assertClass(signer, XdsaSecretKey);\n const ptr1 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.cose_sign_detached(ptr0, len0, signer.__wbg_ptr, ptr1, len1);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v3;\n}\n\n/**\n * Extracts the signer's fingerprint from a COSE_Sign1 without verifying.\n * @param {Uint8Array} signature\n * @returns {XdsaFingerprint}\n */\nexport function cose_signer(signature) {\n const ptr0 = passArray8ToWasm0(signature, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.cose_signer(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XdsaFingerprint.__wrap(ret[0]);\n}\n\n/**\n * Verifies a COSE_Sign1 signature and returns the embedded payload.\n * @param {Uint8Array} msg_to_check\n * @param {Uint8Array} msg_to_auth\n * @param {XdsaPublicKey} verifier\n * @param {Uint8Array} domain\n * @param {bigint | null} [max_drift_secs]\n * @returns {Uint8Array}\n */\nexport function cose_verify(msg_to_check, msg_to_auth, verifier, domain, max_drift_secs) {\n const ptr0 = passArray8ToWasm0(msg_to_check, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n _assertClass(verifier, XdsaPublicKey);\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.cose_verify(ptr0, len0, ptr1, len1, verifier.__wbg_ptr, ptr2, len2, !isLikeNone(max_drift_secs), isLikeNone(max_drift_secs) ? BigInt(0) : max_drift_secs);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v4 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v4;\n}\n\n/**\n * Verifies a COSE_Sign1 signature with a detached payload.\n * @param {Uint8Array} msg_to_check\n * @param {Uint8Array} msg_to_auth\n * @param {XdsaPublicKey} verifier\n * @param {Uint8Array} domain\n * @param {bigint | null} [max_drift_secs]\n */\nexport function cose_verify_detached(msg_to_check, msg_to_auth, verifier, domain, max_drift_secs) {\n const ptr0 = passArray8ToWasm0(msg_to_check, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n _assertClass(verifier, XdsaPublicKey);\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.cose_verify_detached(ptr0, len0, ptr1, len1, verifier.__wbg_ptr, ptr2, len2, !isLikeNone(max_drift_secs), isLikeNone(max_drift_secs) ? BigInt(0) : max_drift_secs);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n}\n\n/**\n * Issues a CWT by signing pre-encoded CBOR claims with COSE Sign1.\n * @param {Uint8Array} claims_cbor\n * @param {XdsaSecretKey} signer\n * @param {Uint8Array} domain\n * @returns {Uint8Array}\n */\nexport function cwt_issue(claims_cbor, signer, domain) {\n const ptr0 = passArray8ToWasm0(claims_cbor, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n _assertClass(signer, XdsaSecretKey);\n const ptr1 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.cwt_issue(ptr0, len0, signer.__wbg_ptr, ptr1, len1);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v3;\n}\n\n/**\n * Extracts and decodes claims from a CWT without verifying the signature.\n * @param {Uint8Array} token\n * @returns {Uint8Array}\n */\nexport function cwt_peek(token) {\n const ptr0 = passArray8ToWasm0(token, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.cwt_peek(ptr0, len0);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v2;\n}\n\n/**\n * Extracts the signer's fingerprint from a CWT without verifying.\n * @param {Uint8Array} token\n * @returns {XdsaFingerprint}\n */\nexport function cwt_signer(token) {\n const ptr0 = passArray8ToWasm0(token, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.cwt_signer(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XdsaFingerprint.__wrap(ret[0]);\n}\n\n/**\n * Verifies a CWT's COSE signature and temporal validity, returning\n * the raw CBOR-encoded claims.\n * @param {Uint8Array} token\n * @param {XdsaPublicKey} verifier\n * @param {Uint8Array} domain\n * @param {bigint | null} [now]\n * @returns {Uint8Array}\n */\nexport function cwt_verify(token, verifier, domain, now) {\n const ptr0 = passArray8ToWasm0(token, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n _assertClass(verifier, XdsaPublicKey);\n const ptr1 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.cwt_verify(ptr0, len0, verifier.__wbg_ptr, ptr1, len1, !isLikeNone(now), isLikeNone(now) ? BigInt(0) : now);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v3;\n}\n\n/**\n * Derives a key using the given pseudorandom key and optional context info,\n * skipping the extraction step.\n *\n * The pseudorandom key should have been generated by hkdf_extract, or be a\n * uniformly random or pseudorandom cryptographically strong key. See RFC 5869,\n * Section 3.3. Most common scenarios will want to use hkdf_key instead. The\n * pseudorandom key and the derived key are wiped from WASM memory before\n * return.\n * @param {Uint8Array} prk\n * @param {Uint8Array} info\n * @param {number} out_len\n * @returns {Uint8Array}\n */\nexport function hkdf_expand(prk, info, out_len) {\n const ptr0 = passArray8ToWasm0(prk, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(info, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.hkdf_expand(ptr0, len0, ptr1, len1, out_len);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * Generates a pseudorandom key for use with hkdf_expand from an input secret\n * and an optional independent salt.\n *\n * Only use this function if you need to reuse the extracted key with multiple\n * expand invocations and different context values. Most common scenarios,\n * including the generation of multiple keys, should use hkdf_key instead.\n * The secret and the key are wiped from WASM memory before return.\n * @param {Uint8Array} secret\n * @param {Uint8Array} salt\n * @returns {Uint8Array}\n */\nexport function hkdf_extract(secret, salt) {\n const ptr0 = passArray8ToWasm0(secret, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(salt, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.hkdf_extract(ptr0, len0, ptr1, len1);\n return ret;\n}\n\n/**\n * Derives a key from the secret, salt, and info using HKDF-SHA256, returning a\n * byte array that can be used as a cryptographic key.\n *\n * The out_len may not exceed the maximum output length for SHA-256 HKDF, which\n * is 255 * 32 = 8160 bytes. The secret and the key are wiped from WASM memory\n * before return.\n * @param {Uint8Array} secret\n * @param {Uint8Array} salt\n * @param {Uint8Array} info\n * @param {number} out_len\n * @returns {Uint8Array}\n */\nexport function hkdf_key(secret, salt, info, out_len) {\n const ptr0 = passArray8ToWasm0(secret, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(salt, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ptr2 = passArray8ToWasm0(info, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.hkdf_key(ptr0, len0, ptr1, len1, ptr2, len2, out_len);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * Generates a buffer of up to 64 MiB filled with randomness. The bytes are\n * wiped from WASM memory before return, since they often become key material.\n * @param {number} bytes\n * @returns {Uint8Array}\n */\nexport function rand_generate(bytes) {\n const ret = wasm.rand_generate(bytes);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * Size of a key fingerprint in bytes.\n * @returns {number}\n */\nexport function xdsa_fingerprint_size() {\n const ret = wasm.xdsa_fingerprint_size();\n return ret >>> 0;\n}\n\n/**\n * Size of the public key in bytes.\n * @returns {number}\n */\nexport function xdsa_public_key_size() {\n const ret = wasm.xdsa_public_key_size();\n return ret >>> 0;\n}\n\n/**\n * Size of the secret key in bytes.\n * @returns {number}\n */\nexport function xdsa_secret_key_size() {\n const ret = wasm.xdsa_secret_key_size();\n return ret >>> 0;\n}\n\n/**\n * Size of a composite signature in bytes.\n * @returns {number}\n */\nexport function xdsa_signature_size() {\n const ret = wasm.xdsa_signature_size();\n return ret >>> 0;\n}\n\n/**\n * Size of the encapsulated key in bytes.\n * @returns {number}\n */\nexport function xhpke_encap_key_size() {\n const ret = wasm.xhpke_encap_key_size();\n return ret >>> 0;\n}\n\n/**\n * Size of the fingerprint in bytes.\n * @returns {number}\n */\nexport function xhpke_fingerprint_size() {\n const ret = wasm.xhpke_fingerprint_size();\n return ret >>> 0;\n}\n\n/**\n * Size of the public key in bytes.\n * @returns {number}\n */\nexport function xhpke_public_key_size() {\n const ret = wasm.xhpke_public_key_size();\n return ret >>> 0;\n}\n\n/**\n * Size of the secret key seed in bytes.\n * @returns {number}\n */\nexport function xhpke_secret_key_size() {\n const ret = wasm.xhpke_secret_key_size();\n return ret >>> 0;\n}\nfunction __wbg_get_imports() {\n const import0 = {\n __proto__: null,\n __wbg_Error_67e7344beaa85059: function(arg0, arg1) {\n const ret = Error(getStringFromWasm0(arg0, arg1));\n return ret;\n },\n __wbg___wbindgen_throw_5d9e815e6fdf150f: function(arg0, arg1) {\n throw new Error(getStringFromWasm0(arg0, arg1));\n },\n __wbg_getRandomValues_436a51d0629d84e1: function() { return handleError(function (arg0, arg1) {\n globalThis.crypto.getRandomValues(getArrayU8FromWasm0(arg0, arg1));\n }, arguments); },\n __wbg_new_from_slice_4ee02165f9de919e: function(arg0, arg1) {\n const ret = new Uint8Array(getArrayU8FromWasm0(arg0, arg1));\n return ret;\n },\n __wbg_now_d1fb6650485d7f3e: function() {\n const ret = Date.now();\n return ret;\n },\n __wbindgen_generic_0000000000000001: function(arg0, arg1) {\n // Cast intrinsic for `Ref(String) -> Externref`.\n const ret = getStringFromWasm0(arg0, arg1);\n return ret;\n },\n __wbindgen_init_externref_table: function() {\n const table = wasm.__wbindgen_externrefs;\n const offset = table.grow(4);\n table.set(0, undefined);\n table.set(offset + 0, undefined);\n table.set(offset + 1, null);\n table.set(offset + 2, true);\n table.set(offset + 3, false);\n },\n };\n return {\n __proto__: null,\n \"./darkbio_crypto_wasm_bg.js\": import0,\n };\n}\n\nconst XdsaFingerprintFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xdsafingerprint_free(ptr, 1));\nconst XdsaPublicKeyFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xdsapublickey_free(ptr, 1));\nconst XdsaSecretKeyFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xdsasecretkey_free(ptr, 1));\nconst XdsaSignatureFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xdsasignature_free(ptr, 1));\nconst XhpkeFingerprintFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xhpkefingerprint_free(ptr, 1));\nconst XhpkePublicKeyFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xhpkepublickey_free(ptr, 1));\nconst XhpkeReceiverFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xhpkereceiver_free(ptr, 1));\nconst XhpkeSecretKeyFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xhpkesecretkey_free(ptr, 1));\nconst XhpkeSenderFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xhpkesender_free(ptr, 1));\n\nfunction addToExternrefTable0(obj) {\n const idx = wasm.__externref_table_alloc();\n wasm.__wbindgen_externrefs.set(idx, obj);\n return idx;\n}\n\nfunction _assertClass(instance, klass) {\n if (!(instance instanceof klass)) {\n throw new Error(`expected instance of ${klass.name}`);\n }\n}\n\nfunction getArrayU8FromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);\n}\n\nfunction getStringFromWasm0(ptr, len) {\n return decodeText(ptr >>> 0, len);\n}\n\nlet cachedUint8ArrayMemory0 = null;\nfunction getUint8ArrayMemory0() {\n if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {\n cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);\n }\n return cachedUint8ArrayMemory0;\n}\n\nfunction handleError(f, args) {\n try {\n return f.apply(this, args);\n } catch (e) {\n const idx = addToExternrefTable0(e);\n wasm.__wbindgen_exn_store(idx);\n }\n}\n\nfunction isLikeNone(x) {\n return x === undefined || x === null;\n}\n\nfunction passArray8ToWasm0(arg, malloc) {\n const ptr = malloc(arg.length * 1, 1) >>> 0;\n getUint8ArrayMemory0().set(arg, ptr / 1);\n WASM_VECTOR_LEN = arg.length;\n return ptr;\n}\n\nfunction passStringToWasm0(arg, malloc, realloc) {\n if (realloc === undefined) {\n const buf = cachedTextEncoder.encode(arg);\n const ptr = malloc(buf.length, 1) >>> 0;\n getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);\n WASM_VECTOR_LEN = buf.length;\n return ptr;\n }\n\n let len = arg.length;\n let ptr = malloc(len, 1) >>> 0;\n\n const mem = getUint8ArrayMemory0();\n\n let offset = 0;\n\n for (; offset < len; offset++) {\n const code = arg.charCodeAt(offset);\n if (code > 0x7F) break;\n mem[ptr + offset] = code;\n }\n if (offset !== len) {\n if (offset !== 0) {\n arg = arg.slice(offset);\n }\n ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;\n const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);\n const ret = cachedTextEncoder.encodeInto(arg, view);\n\n offset += ret.written;\n ptr = realloc(ptr, len, offset, 1) >>> 0;\n }\n\n WASM_VECTOR_LEN = offset;\n return ptr;\n}\n\nfunction takeFromExternrefTable0(idx) {\n const value = wasm.__wbindgen_externrefs.get(idx);\n wasm.__externref_table_dealloc(idx);\n return value;\n}\n\nlet cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\ncachedTextDecoder.decode();\nconst MAX_SAFARI_DECODE_BYTES = 2146435072;\nlet numBytesDecoded = 0;\nfunction decodeText(ptr, len) {\n numBytesDecoded += len;\n if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {\n cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\n cachedTextDecoder.decode();\n numBytesDecoded = len;\n }\n return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));\n}\n\nconst cachedTextEncoder = new TextEncoder();\n\nif (!('encodeInto' in cachedTextEncoder)) {\n cachedTextEncoder.encodeInto = function (arg, view) {\n const buf = cachedTextEncoder.encode(arg);\n view.set(buf);\n return {\n read: arg.length,\n written: buf.length\n };\n };\n}\n\nlet WASM_VECTOR_LEN = 0;\n\nlet wasmModule, wasmInstance, wasm;\nfunction __wbg_finalize_init(instance, module) {\n wasmInstance = instance;\n wasm = instance.exports;\n wasmModule = module;\n cachedUint8ArrayMemory0 = null;\n wasm.__wbindgen_start();\n return wasm;\n}\n\nasync function __wbg_load(module, imports) {\n if (typeof Response === 'function' && module instanceof Response) {\n if (!module.ok) {\n throw new Error(`failed to fetch Wasm: ${module.status} ${module.statusText} fetching '${module.url}'`);\n }\n\n if (typeof WebAssembly.instantiateStreaming === 'function') {\n try {\n return await WebAssembly.instantiateStreaming(module, imports);\n } catch (e) {\n const validResponse = expectedResponseType(module.type);\n\n if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {\n console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n } else { throw e; }\n }\n }\n\n const bytes = await module.arrayBuffer();\n return await WebAssembly.instantiate(bytes, imports);\n } else {\n const instance = await WebAssembly.instantiate(module, imports);\n\n if (instance instanceof WebAssembly.Instance) {\n return { instance, module };\n } else {\n return instance;\n }\n }\n\n function expectedResponseType(type) {\n switch (type) {\n case 'basic': case 'cors': case 'default': return true;\n }\n return false;\n }\n}\n\nfunction initSync(module) {\n if (wasm !== undefined) return wasm;\n\n\n if (module !== undefined) {\n if (Object.getPrototypeOf(module) === Object.prototype) {\n ({module} = module)\n } else {\n console.warn('using deprecated parameters for `initSync()`; pass a single object instead')\n }\n }\n\n const imports = __wbg_get_imports();\n if (!(module instanceof WebAssembly.Module)) {\n module = new WebAssembly.Module(module);\n }\n const instance = new WebAssembly.Instance(module, imports);\n return __wbg_finalize_init(instance, module);\n}\n\nasync function __wbg_init(module_or_path) {\n if (wasm !== undefined) return wasm;\n\n\n if (module_or_path !== undefined) {\n if (Object.getPrototypeOf(module_or_path) === Object.prototype) {\n ({module_or_path} = module_or_path)\n } else {\n console.warn('using deprecated parameters for the initialization function; pass a single object instead')\n }\n }\n\n if (module_or_path === undefined) {\n module_or_path = new URL('darkbio_crypto_wasm_bg.wasm', import.meta.url);\n }\n const imports = __wbg_get_imports();\n\n if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {\n module_or_path = fetch(module_or_path);\n }\n\n const { instance, module } = await __wbg_load(await module_or_path, imports);\n\n return __wbg_finalize_init(instance, module);\n}\n\nexport { initSync, __wbg_init as default };\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\nimport init from \"../wasm/darkbio_crypto_wasm.js\";\n\nlet initPromise: Promise<unknown> | undefined;\nlet initComplete = false;\n\n/**\n * Ensures the WASM module is instantiated exactly once. Concurrent callers\n * share the single in-flight initialization; a failed attempt is cleared so\n * the next call can retry.\n *\n * @internal\n */\nexport function ensureInit(): Promise<unknown> {\n if (initPromise === undefined) {\n initPromise = init()\n .then((module) => {\n initComplete = true;\n return module;\n })\n .catch((err: unknown) => {\n initPromise = undefined;\n throw err;\n });\n }\n return initPromise;\n}\n\n/**\n * Fails unless the WASM module is instantiated, for the synchronous paths a\n * codec takes when it constructs a key. Every async entry point of the\n * package initialises the module, so a codec run after any of them is fine.\n *\n * @internal\n */\nexport function requireInit(): void {\n if (!initComplete) {\n throw new Error(\n \"crypto module not initialised, await any entry point first\",\n );\n }\n}\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/** Largest 32 bit unsigned integer, the size type of the WASM module. */\nexport const U32_MAX = 0xffffffff;\n\n/** Largest 64 bit unsigned integer. */\nexport const U64_MAX = (1n << 64n) - 1n;\n\n/**\n * Checks a count or size fits the 32 bit unsigned integers of the WASM\n * module, which would otherwise wrap it.\n *\n * @internal\n */\nexport function u32(value: number, name: string): number {\n if (!Number.isInteger(value) || value < 0 || value > U32_MAX) {\n throw new Error(`${name} must be a non-negative 32 bit integer`);\n }\n return value;\n}\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * Random bytes from the runtime's secure random source.\n *\n * @example\n * ```ts\n * import { rand } from \"@darkbio/crypto\";\n *\n * const nonce = await rand.generate(32);\n * console.log(nonce.length); // 32\n * ```\n *\n * @module\n */\n\nimport { rand_generate } from \"./wasm/darkbio_crypto_wasm.js\";\nimport { ensureInit } from \"./internal/init.js\";\nimport { u32 } from \"./internal/limits.js\";\n\n/**\n * Generates cryptographically secure random bytes.\n *\n * @param bytes - Number of random bytes to generate, at most 64 MiB\n * @returns A new array filled with random bytes\n * @throws If `bytes` is not a whole number between 0 and 64 MiB\n */\nexport async function generate(bytes: number): Promise<Uint8Array> {\n await ensureInit();\n return rand_generate(u32(bytes, \"bytes\"));\n}\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * HKDF-SHA256 key derivation.\n *\n * https://datatracker.ietf.org/doc/html/rfc5869\n *\n * Stretches a secret that is already high entropy, a shared secret or a file\n * key, into one or more keys bound to a context string. It is not a password\n * hash; the `argon2` module is the one for that.\n *\n * @example\n * ```ts\n * import { hkdf } from \"@darkbio/crypto\";\n *\n * const secret = new Uint8Array(32).fill(42);\n * const salt = new Uint8Array();\n * const text = new TextEncoder();\n *\n * // Distinct contexts derive independent keys from the same secret\n * const encryption = await hkdf.key(secret, salt, text.encode(\"example encryption key\"), 32);\n * const authentication = await hkdf.key(secret, salt, text.encode(\"example authentication key\"), 32);\n * ```\n *\n * @module\n */\n\nimport {\n hkdf_key,\n hkdf_extract,\n hkdf_expand,\n} from \"./wasm/darkbio_crypto_wasm.js\";\nimport { ensureInit } from \"./internal/init.js\";\nimport { u32 } from \"./internal/limits.js\";\n\n/**\n * Derives a key from the secret, salt and info using HKDF-SHA256.\n *\n * @param secret - The input keying material, already high entropy\n * @param salt - Optional salt, empty for none\n * @param info - Context the key is bound to, empty for none\n * @param outLen - Length of the key in bytes, at most 8160\n * @returns The derived key\n * @throws If `outLen` is not a whole number between 0 and 8160\n */\nexport async function key(\n secret: Uint8Array,\n salt: Uint8Array,\n info: Uint8Array,\n outLen: number,\n): Promise<Uint8Array> {\n await ensureInit();\n return hkdf_key(secret, salt, info, u32(outLen, \"outLen\"));\n}\n\n/**\n * Extracts a 32-byte pseudorandom key from the secret and salt, for use with\n * {@link expand}.\n *\n * Only use this to reuse the extracted key with multiple {@link expand} calls\n * and different contexts. Most scenarios, including the derivation of multiple\n * keys, should use {@link key} instead.\n *\n * @param secret - The input keying material, already high entropy\n * @param salt - Optional salt, empty for none\n * @returns A 32-byte pseudorandom key\n */\nexport async function extract(\n secret: Uint8Array,\n salt: Uint8Array,\n): Promise<Uint8Array> {\n await ensureInit();\n return hkdf_extract(secret, salt);\n}\n\n/**\n * Derives a key from a pseudorandom key and context info, skipping the\n * extraction step.\n *\n * The pseudorandom key should come from {@link extract}, or be a uniformly\n * random or pseudorandom cryptographically strong key. See RFC 5869 Section\n * 3.3. Most scenarios should use {@link key} instead.\n *\n * @param prk - A 32-byte pseudorandom key\n * @param info - Context the key is bound to, empty for none\n * @param outLen - Length of the key in bytes, at most 8160\n * @returns The derived key\n * @throws If `prk` is not 32 bytes, or `outLen` is not a whole number between\n * 0 and 8160\n */\nexport async function expand(\n prk: Uint8Array,\n info: Uint8Array,\n outLen: number,\n): Promise<Uint8Array> {\n await ensureInit();\n return hkdf_expand(prk, info, u32(outLen, \"outLen\"));\n}\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * Argon2id key derivation.\n *\n * https://datatracker.ietf.org/doc/html/rfc9106\n *\n * Turns a password and a salt into key material, made deliberately slow and\n * memory hungry so guessing passwords is expensive. For stretching a secret\n * that is already random, see the `hkdf` module instead.\n *\n * @module\n */\n\nimport { argon2_key } from \"./wasm/darkbio_crypto_wasm.js\";\nimport { ensureInit } from \"./internal/init.js\";\nimport { u32 } from \"./internal/limits.js\";\n\n/**\n * Derives a key from the password, salt and cost parameters using Argon2id.\n *\n * RFC 9106 Section 4 recommends `time = 1`, `memory = 2 * 1024 * 1024`\n * (2 GiB) and `threads = 4`. Its second recommendation uses `time = 3`,\n * `memory = 64 * 1024` (64 MiB) and `threads = 4`. Both use a random 16-byte\n * salt and a 32-byte output. A single WASM allocation stays below 2 GiB, so\n * only the second profile fits within the memory limit below.\n *\n * `time` is the number of passes and `memory` is the total working memory in\n * KiB. `threads` is Argon2's lane count, an algorithm parameter that changes\n * the derived key. It does not select how many threads compute the key. Store\n * the salt and all cost parameters so the same key can be reproduced on other\n * devices.\n *\n * The parameters must stay within these limits:\n *\n * - `time` must be at least 1.\n * - `threads` must be at least 1.\n * - `memory` must be at least `8 * threads` KiB and at most 2097151 KiB, one\n * KiB short of 2 GiB.\n * - `salt` must be at least 8 bytes.\n * - `outLen` must be at least 4 bytes and at most 2147483647 bytes.\n *\n * @example\n * ```ts\n * import { argon2 } from \"@darkbio/crypto\";\n *\n * // Example salt only; generate and store a fresh random 16-byte salt in real code\n * const salt = new TextEncoder().encode(\"example salt1234\");\n * const password = new TextEncoder().encode(\"password\");\n *\n * // RFC 9106's recommended profile for memory-constrained environments\n * const key = await argon2.key(password, salt, 3, 64 * 1024, 4, 32);\n * console.log(key.length); // 32\n * ```\n *\n * @param password - The password to derive from\n * @param salt - A random salt, at least 8 bytes and 16 bytes recommended\n * @param time - Number of passes over the memory\n * @param memory - Size of the working memory in KiB\n * @param threads - Argon2's lane count\n * @param outLen - Length of the key in bytes\n * @returns The derived key\n * @throws If a parameter is outside the limits above, or the working memory\n * cannot be allocated\n */\nexport async function key(\n password: Uint8Array,\n salt: Uint8Array,\n time: number,\n memory: number,\n threads: number,\n outLen: number,\n): Promise<Uint8Array> {\n await ensureInit();\n return argon2_key(\n password,\n salt,\n u32(time, \"time\"),\n u32(memory, \"memory\"),\n u32(threads, \"threads\"),\n u32(outLen, \"outLen\"),\n );\n}\n","// This is an unfortunate replacement for @sindresorhus/is that we need to\n// re-implement for performance purposes. In particular the is.observable()\n// check is expensive, and unnecessary for our purposes. The values returned\n// are compatible with @sindresorhus/is, however.\n\n// Types that reach getObjectType() - excludes types with fast-paths above:\n// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)\nconst objectTypeNames = [\n 'Object', // for Object.create(null) and other non-plain objects\n 'RegExp',\n 'Date',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'ArrayBuffer',\n 'SharedArrayBuffer',\n 'DataView',\n 'Promise',\n 'URL',\n 'HTMLElement',\n 'Int8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array',\n 'Tagged'\n]\n\n/**\n * @param {any} value\n * @returns {string}\n */\nexport function is (value) {\n if (value === null) {\n return 'null'\n }\n if (value === undefined) {\n return 'undefined'\n }\n if (value === true || value === false) {\n return 'boolean'\n }\n const typeOf = typeof value\n if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {\n return typeOf\n }\n if (typeOf === 'function') {\n return 'Function'\n }\n if (Array.isArray(value)) {\n return 'Array'\n }\n // Also catches Node.js Buffer which extends Uint8Array\n if (value instanceof Uint8Array) {\n return 'Uint8Array'\n }\n // Fast path for plain objects (most common case after primitives/arrays/bytes)\n if (value.constructor === Object) {\n return 'Object'\n }\n const objectType = getObjectType(value)\n if (objectType) {\n return objectType\n }\n return 'Object'\n}\n\n/**\n * @param {any} value\n * @returns {string|undefined}\n */\nfunction getObjectType (value) {\n const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)\n if (objectTypeNames.includes(objectTypeName)) {\n return objectTypeName\n }\n return undefined\n}\n","class Type {\n /**\n * @param {number} major\n * @param {string} name\n * @param {boolean} terminal\n */\n constructor (major, name, terminal) {\n this.major = major\n this.majorEncoded = major << 5\n this.name = name\n this.terminal = terminal\n }\n\n toString () {\n return `Type[${this.major}].${this.name}`\n }\n\n /**\n * @param {Type} typ\n * @returns {number}\n */\n compare (typ) {\n return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0\n }\n\n /**\n * Check equality between two Type instances. Safe to use across different\n * copies of the Type class (e.g., when bundlers duplicate the module).\n * (major, name) uniquely identifies a Type; terminal is implied by these.\n * @param {Type} a\n * @param {Type} b\n * @returns {boolean}\n */\n static equals (a, b) {\n return a === b || (a.major === b.major && a.name === b.name)\n }\n}\n\n// convert to static fields when better supported\nType.uint = new Type(0, 'uint', true)\nType.negint = new Type(1, 'negint', true)\nType.bytes = new Type(2, 'bytes', true)\nType.string = new Type(3, 'string', true)\nType.array = new Type(4, 'array', false)\nType.map = new Type(5, 'map', false)\nType.tag = new Type(6, 'tag', false) // terminal?\nType.float = new Type(7, 'float', true)\nType.false = new Type(7, 'false', true)\nType.true = new Type(7, 'true', true)\nType.null = new Type(7, 'null', true)\nType.undefined = new Type(7, 'undefined', true)\nType.break = new Type(7, 'break', true)\n// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)\n\nclass Token {\n /**\n * @param {Type} type\n * @param {any} [value]\n * @param {number} [encodedLength]\n */\n constructor (type, value, encodedLength) {\n this.type = type\n this.value = value\n this.encodedLength = encodedLength\n /** @type {Uint8Array|undefined} */\n this.encodedBytes = undefined\n /** @type {Uint8Array|undefined} */\n this.byteValue = undefined\n }\n\n toString () {\n return `Token[${this.type}].${this.value}`\n }\n}\n\nexport { Type, Token }\n","// Use Uint8Array directly in the browser, use Buffer in Node.js but don't\n// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill\n\n// @ts-ignore\nexport const useBuffer = globalThis.process &&\n // @ts-ignore\n !globalThis.process.browser &&\n // @ts-ignore\n globalThis.Buffer &&\n // @ts-ignore\n typeof globalThis.Buffer.isBuffer === 'function'\n\nconst textEncoder = new TextEncoder()\n\n/**\n * @typedef {import('../interface.js').ByteView} ByteView\n * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView\n */\n\n/**\n * @param {Uint8Array} buf\n * @returns {boolean}\n */\nfunction isBuffer (buf) {\n // @ts-ignore\n return useBuffer && globalThis.Buffer.isBuffer(buf)\n}\n\n/**\n * @param {ByteView|number[]} buf\n * @returns {ByteView}\n */\nexport function asU8A (buf) {\n if (!(buf instanceof Uint8Array)) {\n return Uint8Array.from(buf)\n }\n return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf\n}\n\n// Threshold for manual UTF-8 encoding vs native methods.\n// Node.js Buffer.from: crossover ~24 chars\n// Browser TextEncoder: crossover ~200 chars\nconst FROM_STRING_THRESHOLD_BUFFER = 24\nconst FROM_STRING_THRESHOLD_TEXTENCODER = 200\n\nexport const fromString = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length >= FROM_STRING_THRESHOLD_BUFFER\n ? // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(string)\n : utf8ToBytes(string)\n }\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)\n }\n\n/**\n * Buffer variant not fast enough for what we need\n * @param {number[]} arr\n * @returns {AllocatedByteView}\n */\nexport const fromArray = (arr) => {\n return Uint8Array.from(arr)\n}\n\nexport const slice = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n // Buffer.slice() returns a view, not a copy, so we need special handling\n (bytes, start, end) => {\n if (isBuffer(bytes)) {\n return new Uint8Array(bytes.subarray(start, end))\n }\n return bytes.slice(start, end)\n }\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return bytes.slice(start, end)\n }\n\nexport const concat = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {ByteView[]} chunks\n * @param {number} length\n * @returns {AllocatedByteView}\n */\n (chunks, length) => {\n // might get a stray plain Array here\n chunks = chunks.map((c) => c instanceof Uint8Array\n ? c\n : // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(c))\n // @ts-ignore\n return /** @type {AllocatedByteView} */ (asU8A(globalThis.Buffer.concat(chunks, length)))\n }\n : // eslint-disable-line operator-linebreak\n /**\n * @param {ByteView[]} chunks\n * @param {number} length\n * @returns {AllocatedByteView}\n */\n (chunks, length) => {\n const out = new Uint8Array(length)\n let off = 0\n for (let b of chunks) {\n if (off + b.length > out.length) {\n // final chunk that's bigger than we need\n b = b.subarray(0, out.length - off)\n }\n out.set(b, off)\n off += b.length\n }\n return out\n }\n\nexport const alloc = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {AllocatedByteView}\n */\n (size) => {\n // we always write over the contents we expose so this should be safe\n // @ts-ignore\n return globalThis.Buffer.allocUnsafe(size)\n }\n : // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {AllocatedByteView}\n */\n (size) => {\n return new Uint8Array(size)\n }\n\nexport const toHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore\n return globalThis.Buffer.from(toBytes(d)).toString('hex')\n }\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore not smart enough to figure this out\n return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')\n }\n\nexport const fromHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string|ByteView} hex\n * @returns {ByteView}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n // @ts-ignore\n return globalThis.Buffer.from(hex, 'hex')\n }\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string|ByteView} hex\n * @returns {ByteView}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n if (!hex.length) {\n return new Uint8Array(0)\n }\n return new Uint8Array(hex.split('')\n .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')\n .filter(Boolean)\n .map((/** @type {string} */ e) => parseInt(e, 16)))\n }\n\n/**\n * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj\n * @returns {Uint8Array}\n */\nfunction toBytes (obj) {\n if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {\n return obj\n }\n if (obj instanceof ArrayBuffer) {\n return new Uint8Array(obj)\n }\n if (ArrayBuffer.isView(obj)) {\n return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compare (b1, b2) {\n if (isBuffer(b1) && isBuffer(b2)) {\n // probably not possible to get here in the current API\n // @ts-ignore Buffer\n return b1.compare(b2)\n }\n for (let i = 0; i < b1.length; i++) {\n if (b1[i] === b2[i]) {\n continue\n }\n return b1[i] < b2[i] ? -1 : 1\n }\n return 0\n}\n\n// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143\n// Licensed Apache-2.0.\n\n/**\n * @param {string} str\n * @returns {number[]}\n */\nfunction utf8ToBytes (str) {\n const out = []\n let p = 0\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i)\n if (c < 128) {\n out[p++] = c\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192\n out[p++] = (c & 63) | 128\n } else if (\n ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&\n ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)\n out[p++] = (c >> 18) | 240\n out[p++] = ((c >> 12) & 63) | 128\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n } else {\n if ((c >= 0xD800) && (c <= 0xDFFF)) {\n c = 0xFFFD // Unpaired Surrogate\n }\n out[p++] = (c >> 12) | 224\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n }\n }\n return out\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\n/**\n * @param {number[]} codePoints\n * @returns {string}\n */\nexport function decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n","/**\n * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for\n * writing rather than reading.\n * A Bl object accepts set() operations for individual bytes and copyTo() for\n * inserting byte arrays. These write operations don't automatically increment\n * the internal cursor so its \"length\" won't be changed. Instead, increment()\n * must be called to extend its length to cover the inserted data.\n * The toBytes() call will convert all internal memory to a single Uint8Array of\n * the correct length, truncating any data that is stored but hasn't been\n * included by an increment().\n * get() can retrieve a single byte.\n * All operations (except toBytes()) take an \"offset\" argument that will perform\n * the write at the offset _from the current cursor_. For most operations this\n * will be `0` to write at the current cursor position but it can be ahead of\n * the current cursor. Negative offsets probably work but are untested.\n */\n\n// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39\nimport { alloc, concat, slice } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface.js').ByteView} ByteView\n * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView\n */\n\n// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists\n// for perf reasons. Consider better approaches to this or removing it entirely, it is quite\n// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.\n\nconst defaultChunkSize = 256\n\nexport class Bl {\n /**\n * @param {number} [chunkSize]\n */\n constructor (chunkSize = defaultChunkSize) {\n this.chunkSize = chunkSize\n /** @type {number} */\n this.cursor = 0\n /** @type {number} */\n this.maxCursor = -1\n /** @type {(ByteView|number[])[]} */\n this.chunks = []\n // keep the first chunk around if we can to save allocations for future encodes\n /** @type {ByteView|number[]|null} */\n this._initReuseChunk = null\n }\n\n reset () {\n this.cursor = 0\n this.maxCursor = -1\n if (this.chunks.length) {\n this.chunks = []\n }\n if (this._initReuseChunk !== null) {\n this.chunks.push(this._initReuseChunk)\n this.maxCursor = this._initReuseChunk.length - 1\n }\n }\n\n /**\n * @param {number} byte\n */\n pushByte (byte) {\n let topChunk = this.chunks[this.chunks.length - 1]\n if (this.cursor > this.maxCursor) {\n topChunk = alloc(this.chunkSize)\n this.chunks.push(topChunk)\n this.maxCursor += topChunk.length\n if (this._initReuseChunk === null) {\n this._initReuseChunk = topChunk\n }\n }\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n topChunk[chunkPos] = byte\n this.cursor++\n }\n\n /**\n * @param {ByteView|number[]} bytes\n */\n push (bytes) {\n let topChunk = this.chunks[this.chunks.length - 1]\n const newMax = this.cursor + bytes.length\n if (newMax <= this.maxCursor + 1) {\n // we have at least one chunk and we can fit these bytes into that chunk\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n // @ts-ignore\n topChunk.set(bytes, chunkPos)\n } else {\n // can't fit it in\n if (topChunk) {\n // trip the last chunk to `cursor` if we need to\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n if (chunkPos < topChunk.length) {\n // @ts-ignore\n this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)\n this.maxCursor = this.cursor - 1\n }\n }\n if (bytes.length < 64 && bytes.length < this.chunkSize) {\n // make a new chunk and copy the new one into it\n topChunk = alloc(this.chunkSize)\n this.chunks.push(topChunk)\n this.maxCursor += topChunk.length\n if (this._initReuseChunk === null) {\n this._initReuseChunk = topChunk\n }\n // @ts-ignore\n topChunk.set(bytes, 0)\n } else {\n // push the new bytes in as its own chunk\n this.chunks.push(bytes)\n this.maxCursor += bytes.length\n }\n }\n this.cursor += bytes.length\n }\n\n /**\n * @param {boolean} [reset]\n * @returns {AllocatedByteView}\n */\n toBytes (reset = false) {\n let byts\n if (this.chunks.length === 1) {\n const chunk = this.chunks[0]\n if (reset && this.cursor > chunk.length / 2) {\n // @ts-ignore\n byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)\n this._initReuseChunk = null\n this.chunks = []\n } else {\n // @ts-ignore\n byts = slice(chunk, 0, this.cursor)\n }\n } else {\n // @ts-ignore\n byts = concat(this.chunks, this.cursor)\n }\n if (reset) {\n this.reset()\n }\n return byts\n }\n}\n\n/**\n * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.\n * It provides the same interface as Bl but writes to a fixed destination.\n * @template {ArrayBufferLike} T\n */\nexport class U8Bl {\n /**\n * @param {Uint8Array<T>} dest\n */\n constructor (dest) {\n this.dest = dest\n /** @type {number} */\n this.cursor = 0\n // chunks is for interface compatibility with Bl - encode.js checks chunks.length\n // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].\n /** @type {Array<Uint8Array<T>>} */\n this.chunks = [dest]\n }\n\n reset () {\n this.cursor = 0\n }\n\n /**\n * @param {number} byte\n */\n pushByte (byte) {\n if (this.cursor >= this.dest.length) {\n throw new Error('write out of bounds, destination buffer is too small')\n }\n this.dest[this.cursor++] = byte\n }\n\n /**\n * @param {ByteView|number[]} bytes\n */\n push (bytes) {\n if (this.cursor + bytes.length > this.dest.length) {\n throw new Error('write out of bounds, destination buffer is too small')\n }\n this.dest.set(bytes, this.cursor)\n this.cursor += bytes.length\n }\n\n /**\n * @param {boolean} [reset]\n * @returns {Uint8Array<T>}\n */\n toBytes (reset = false) {\n const byts = this.dest.subarray(0, this.cursor)\n if (reset) {\n this.reset()\n }\n return byts\n }\n}\n","const decodeErrPrefix = 'CBOR decode error:'\nconst encodeErrPrefix = 'CBOR encode error:'\n\nconst uintMinorPrefixBytes = []\nuintMinorPrefixBytes[23] = 1\nuintMinorPrefixBytes[24] = 2\nuintMinorPrefixBytes[25] = 3\nuintMinorPrefixBytes[26] = 5\nuintMinorPrefixBytes[27] = 9\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} need\n */\nfunction assertEnoughData (data, pos, need) {\n if (data.length - pos < need) {\n throw new Error(`${decodeErrPrefix} not enough data for type`)\n }\n}\n\nexport {\n decodeErrPrefix,\n encodeErrPrefix,\n uintMinorPrefixBytes,\n assertEnoughData\n}\n","/* globals BigInt */\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix, assertEnoughData } from './common.js'\n\nexport const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint8 (data, offset, options) {\n assertEnoughData(data, offset, 1)\n const value = data[offset]\n if (options.strict === true && value < uintBoundaries[0]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint16 (data, offset, options) {\n assertEnoughData(data, offset, 2)\n const value = (data[offset] << 8) | data[offset + 1]\n if (options.strict === true && value < uintBoundaries[1]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint32 (data, offset, options) {\n assertEnoughData(data, offset, 4)\n const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n if (options.strict === true && value < uintBoundaries[2]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number|bigint}\n */\nexport function readUint64 (data, offset, options) {\n // assume BigInt, convert back to Number if within safe range\n assertEnoughData(data, offset, 8)\n const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]\n const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)\n if (options.strict === true && value < uintBoundaries[3]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n if (value <= Number.MAX_SAFE_INTEGER) {\n return Number(value)\n }\n if (options.allowBigInt === true) {\n return value\n }\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n}\n\n/* not required thanks to quick[] list\nconst oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))\nexport function decodeUintCompact (data, pos, minor, options) {\n return oneByteTokens[minor]\n}\n*/\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint8 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint16 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint32 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint64 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeUint (writer, token) {\n return encodeUintValue(writer, 0, token.value)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {number} major\n * @param {number|bigint} uint\n */\nexport function encodeUintValue (writer, major, uint) {\n if (uint < uintBoundaries[0]) {\n const nuint = Number(uint)\n // pack into one byte, minor=0, additional=value\n writer.pushByte(major | nuint)\n } else if (uint < uintBoundaries[1]) {\n const nuint = Number(uint)\n // pack into two byte, minor=0, additional=24\n writer.push([major | 24, nuint])\n } else if (uint < uintBoundaries[2]) {\n const nuint = Number(uint)\n // pack into three byte, minor=0, additional=25\n writer.push([major | 25, nuint >>> 8, nuint & 0xff])\n } else if (uint < uintBoundaries[3]) {\n const nuint = Number(uint)\n // pack into five byte, minor=0, additional=26\n writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])\n } else {\n const buint = BigInt(uint)\n if (buint < uintBoundaries[4]) {\n // pack into nine byte, minor=0, additional=27\n const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]\n // simulate bitwise above 32 bits\n let lo = Number(buint & BigInt(0xffffffff))\n let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))\n set[8] = lo & 0xff\n lo = lo >> 8\n set[7] = lo & 0xff\n lo = lo >> 8\n set[6] = lo & 0xff\n lo = lo >> 8\n set[5] = lo & 0xff\n set[4] = hi & 0xff\n hi = hi >> 8\n set[3] = hi & 0xff\n hi = hi >> 8\n set[2] = hi & 0xff\n hi = hi >> 8\n set[1] = hi & 0xff\n writer.push(set)\n } else {\n throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)\n }\n }\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeUint.encodedSize = function encodedSize (token) {\n return encodeUintValue.encodedSize(token.value)\n}\n\n/**\n * @param {number} uint\n * @returns {number}\n */\nencodeUintValue.encodedSize = function encodedSize (uint) {\n if (uint < uintBoundaries[0]) {\n return 1\n }\n if (uint < uintBoundaries[1]) {\n return 2\n }\n if (uint < uintBoundaries[2]) {\n return 3\n }\n if (uint < uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeUint.compareTokens = function compareTokens (tok1, tok2) {\n return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0\n}\n","/* eslint-env es2020 */\n\nimport { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint8 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint16 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint32 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)\n}\n\nconst neg1b = BigInt(-1)\nconst pos1b = BigInt(1)\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint64 (data, pos, _minor, options) {\n const int = uint.readUint64(data, pos + 1, options)\n if (typeof int !== 'bigint') {\n const value = -1 - int\n if (value >= Number.MIN_SAFE_INTEGER) {\n return new Token(Type.negint, value, 9)\n }\n }\n if (options.allowBigInt !== true) {\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n }\n return new Token(Type.negint, neg1b - BigInt(int), 9)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeNegint (writer, token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeNegint.encodedSize = function encodedSize (token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n // handled by quickEncode, we shouldn't get here but it's included for completeness\n if (unsigned < uint.uintBoundaries[0]) {\n return 1\n }\n if (unsigned < uint.uintBoundaries[1]) {\n return 2\n }\n if (unsigned < uint.uintBoundaries[2]) {\n return 3\n }\n if (unsigned < uint.uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeNegint.compareTokens = function compareTokens (tok1, tok2) {\n // opposite of the uint comparison since we store the uint version in bytes\n return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0\n}\n","import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { compare, fromString } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length) {\n assertEnoughData(data, pos, prefix + length)\n const buf = data.slice(pos + prefix, pos + prefix + length)\n return new Token(Type.bytes, buf, prefix + length)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeBytesCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * `encodedBytes` allows for caching when we do a byte version of a string\n * for key sorting purposes\n * @param {Token} token\n * @returns {Uint8Array}\n */\nfunction tokenBytes (token) {\n if (token.encodedBytes === undefined) {\n token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value\n }\n // @ts-ignore c'mon\n return token.encodedBytes\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeBytes (writer, token) {\n const bytes = tokenBytes(token)\n uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)\n writer.push(bytes)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeBytes.encodedSize = function encodedSize (token) {\n const bytes = tokenBytes(token)\n return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeBytes.compareTokens = function compareTokens (tok1, tok2) {\n return compareBytes(tokenBytes(tok1), tokenBytes(tok2))\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compareBytes (b1, b2) {\n return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)\n}\n","import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { encodeBytes } from './2bytes.js'\n\nconst textDecoder = new TextDecoder()\n\n// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for\n// map keys) are faster to decode with a simple loop than TextDecoder overhead.\nconst ASCII_THRESHOLD = 32\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n */\n\n/**\n * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),\n * a simple loop is faster than TextDecoder.\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n * @returns {string}\n */\nfunction toStr (bytes, start, end) {\n const len = end - start\n if (len < ASCII_THRESHOLD) {\n let str = ''\n for (let i = start; i < end; i++) {\n const c = bytes[i]\n if (c & 0x80) { // non-ASCII, fall back to TextDecoder\n return textDecoder.decode(bytes.subarray(start, end))\n }\n str += String.fromCharCode(c)\n }\n return str\n }\n return textDecoder.decode(bytes.subarray(start, end))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length, options) {\n const totLength = prefix + length\n assertEnoughData(data, pos, totLength)\n const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)\n if (options.retainStringBytes === true) {\n tok.byteValue = data.slice(pos + prefix, pos + totLength)\n }\n return tok\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeStringCompact (data, pos, minor, options) {\n return toToken(data, pos, 1, minor, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)\n }\n return toToken(data, pos, 9, l, options)\n}\n\nexport const encodeString = encodeBytes\n","import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.array, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeArrayCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArrayIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeArray (writer, token) {\n uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)\n}\n\n// using an array as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeArray.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeArray.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n","import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.map, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeMapCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMapIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeMap (writer, token) {\n uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)\n}\n\n// using a map as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeMap.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeMap.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n","import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeTagCompact (_data, _pos, minor, _options) {\n return new Token(Type.tag, minor, 1)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag8 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag16 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag32 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag64 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeTag (writer, token) {\n uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)\n}\n\nencodeTag.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeTag.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n","// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer\n// where possible\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix } from './common.js'\nimport { compare } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n * @typedef {import('../interface.js').EncodeOptions} EncodeOptions\n */\n\nexport const MINOR_FALSE = 20\nexport const MINOR_TRUE = 21\nexport const MINOR_NULL = 22\nexport const MINOR_UNDEFINED = 23\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUndefined (_data, _pos, _minor, options) {\n if (options.allowUndefined === false) {\n throw new Error(`${decodeErrPrefix} undefined values are not supported`)\n } else if (options.coerceUndefinedToNull === true) {\n return new Token(Type.null, null, 1)\n }\n return new Token(Type.undefined, undefined, 1)\n}\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBreak (_data, _pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return new Token(Type.break, undefined, 1)\n}\n\n/**\n * @param {number} value\n * @param {number} bytes\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction createToken (value, bytes, options) {\n if (options) {\n if (options.allowNaN === false && Number.isNaN(value)) {\n throw new Error(`${decodeErrPrefix} NaN values are not supported`)\n }\n if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {\n throw new Error(`${decodeErrPrefix} Infinity values are not supported`)\n }\n }\n return new Token(Type.float, value, bytes)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat16 (data, pos, _minor, options) {\n return createToken(readFloat16(data, pos + 1), 3, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat32 (data, pos, _minor, options) {\n return createToken(readFloat32(data, pos + 1), 5, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat64 (data, pos, _minor, options) {\n return createToken(readFloat64(data, pos + 1), 9, options)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n * @param {EncodeOptions} options\n */\nexport function encodeFloat (writer, token, options) {\n const float = token.value\n\n if (float === false) {\n writer.pushByte(Type.float.majorEncoded | MINOR_FALSE)\n } else if (float === true) {\n writer.pushByte(Type.float.majorEncoded | MINOR_TRUE)\n } else if (float === null) {\n writer.pushByte(Type.float.majorEncoded | MINOR_NULL)\n } else if (float === undefined) {\n writer.pushByte(Type.float.majorEncoded | MINOR_UNDEFINED)\n } else {\n let decoded\n let success = false\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n ui8a[0] = 0xf9\n writer.push(ui8a.slice(0, 3))\n success = true\n } else {\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n ui8a[0] = 0xfa\n writer.push(ui8a.slice(0, 5))\n success = true\n }\n }\n }\n if (!success) {\n encodeFloat64(float)\n decoded = readFloat64(ui8a, 1)\n ui8a[0] = 0xfb\n writer.push(ui8a.slice(0, 9))\n }\n }\n}\n\n/**\n * @param {Token} token\n * @param {EncodeOptions} options\n * @returns {number}\n */\nencodeFloat.encodedSize = function encodedSize (token, options) {\n const float = token.value\n\n if (float === false || float === true || float === null || float === undefined) {\n return 1\n }\n\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n let decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n return 3\n }\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n return 5\n }\n }\n return 9\n}\n\nconst buffer = new ArrayBuffer(9)\nconst dataView = new DataView(buffer, 1)\nconst ui8a = new Uint8Array(buffer, 0)\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat16 (inp) {\n if (inp === Infinity) {\n dataView.setUint16(0, 0x7c00, false)\n } else if (inp === -Infinity) {\n dataView.setUint16(0, 0xfc00, false)\n } else if (Number.isNaN(inp)) {\n dataView.setUint16(0, 0x7e00, false)\n } else {\n dataView.setFloat32(0, inp)\n const valu32 = dataView.getUint32(0)\n const exponent = (valu32 & 0x7f800000) >> 23\n const mantissa = valu32 & 0x7fffff\n\n if (exponent === 0xff) {\n // too big, Infinity, but this should be hard (impossible?) to trigger\n dataView.setUint16(0, 0x7c00, false)\n } else if (exponent === 0x00) {\n // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int\n // Use valu32 for sign bit since bitwise ops on floats lose -0 sign\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)\n } else { // standard numbers\n // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127\n const logicalExponent = exponent - 127\n // Now we know that 2^exponent <= 0 logically\n if (logicalExponent < -24) {\n /* No unambiguous representation exists, this float is not a half float\n and is too small to be represented using a half, round off to zero.\n Consistent with the reference implementation. */\n // should be difficult (impossible?) to get here in JS\n dataView.setUint16(0, 0)\n } else if (logicalExponent < -14) {\n /* Offset the remaining decimal places by shifting the significand, the\n value is lost. This is an implementation decision that works around the\n absence of standard half-float in the language. */\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)\n } else {\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)\n }\n }\n }\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat16 (ui8a, pos) {\n if (ui8a.length - pos < 2) {\n throw new Error(`${decodeErrPrefix} not enough data for float16`)\n }\n\n const half = (ui8a[pos] << 8) + ui8a[pos + 1]\n if (half === 0x7c00) {\n return Infinity\n }\n if (half === 0xfc00) {\n return -Infinity\n }\n if (half === 0x7e00) {\n return NaN\n }\n const exp = (half >> 10) & 0x1f\n const mant = half & 0x3ff\n let val\n if (exp === 0) {\n val = mant * (2 ** -24)\n } else if (exp !== 31) {\n val = (mant + 1024) * (2 ** (exp - 25))\n } else {\n // may not be possible to get here\n val = mant === 0 ? Infinity : NaN\n }\n return (half & 0x8000) ? -val : val\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat32 (inp) {\n dataView.setFloat32(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat32 (ui8a, pos) {\n if (ui8a.length - pos < 4) {\n throw new Error(`${decodeErrPrefix} not enough data for float32`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat64 (inp) {\n dataView.setFloat64(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat64 (ui8a, pos) {\n if (ui8a.length - pos < 8) {\n throw new Error(`${decodeErrPrefix} not enough data for float64`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)\n}\n\n/**\n * @typedef {Token & {\n * _keyBytes?: Uint8Array,\n * _keyBytesFloat64?: Uint8Array\n * }} TokenEx\n */\n\n/**\n * The canonical CBOR bytes for a major 7 map key. The four simple values encode\n * to a single byte and every float to its 3, 5 or 9 byte form, exactly as\n * {@link encodeFloat} writes them. This mirrors the width selection in\n * `encodeFloat` because the sorter needs the bytes in hand to compare.\n * @param {Token} token\n * @param {boolean} float64\n * @returns {Uint8Array}\n */\nfunction encodeMajorSevenBytes (token, float64) {\n const float = token.value\n if (float === false) {\n return Uint8Array.of(Type.float.majorEncoded | MINOR_FALSE)\n }\n if (float === true) {\n return Uint8Array.of(Type.float.majorEncoded | MINOR_TRUE)\n }\n if (float === null) {\n return Uint8Array.of(Type.float.majorEncoded | MINOR_NULL)\n }\n if (float === undefined) {\n return Uint8Array.of(Type.float.majorEncoded | MINOR_UNDEFINED)\n }\n if (!float64) {\n encodeFloat16(float)\n if (float === readFloat16(ui8a, 1) || Number.isNaN(float)) {\n ui8a[0] = 0xf9\n return ui8a.slice(0, 3)\n }\n encodeFloat32(float)\n if (float === readFloat32(ui8a, 1)) {\n ui8a[0] = 0xfa\n return ui8a.slice(0, 5)\n }\n }\n encodeFloat64(float)\n ui8a[0] = 0xfb\n return ui8a.slice(0, 9)\n}\n\n/**\n * Get the canonical CBOR bytes for a major 7 map key, honouring\n * `options.float64`. Bytes are cached because Array.sort compares each key\n * multiple times.\n * @param {Token} token\n * @param {EncodeOptions} [options]\n * @returns {Uint8Array}\n */\nfunction majorSevenBytes (token, options) {\n const tokenEx = /** @type {TokenEx} */ (token)\n const float64 = options?.float64 === true\n const cached = float64 ? tokenEx._keyBytesFloat64 : tokenEx._keyBytes\n if (cached !== undefined) {\n return cached\n }\n\n const bytes = encodeMajorSevenBytes(token, float64)\n if (float64) {\n tokenEx._keyBytesFloat64 = bytes\n } else {\n tokenEx._keyBytes = bytes\n }\n return bytes\n}\n\n/**\n * Order two major 7 map keys by RFC 7049 §3.9 canonical order: shorter encoding\n * first, then bytewise. Because the four simple values encode to one byte they\n * sort ahead of every float, and comparing the `float64`-honouring encoded bytes\n * (rather than the numeric value) makes negative floats, mixed encoding widths\n * and `NaN` deterministic regardless of insertion order.\n * @param {Token} tok1\n * @param {Token} tok2\n * @param {EncodeOptions} [options]\n * @returns {number}\n */\nencodeFloat.compareTokens = function compareTokens (tok1, tok2, options) {\n const b1 = majorSevenBytes(tok1, options)\n const b2 = majorSevenBytes(tok2, options)\n if (b1.length !== b2.length) {\n return b1.length < b2.length ? -1 : 1\n }\n return compare(b1, b2)\n}\n","import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport * as negint from './1negint.js'\nimport * as bytes from './2bytes.js'\nimport * as string from './3string.js'\nimport * as array from './4array.js'\nimport * as map from './5map.js'\nimport * as tag from './6tag.js'\nimport * as float from './7float.js'\nimport { decodeErrPrefix } from './common.js'\nimport { fromArray } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n */\nfunction invalidMinor (data, pos, minor) {\n throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)\n}\n\n/**\n * @param {string} msg\n * @returns {()=>any}\n */\nfunction errorer (msg) {\n return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }\n}\n\n/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */\nexport const jump = []\n\n// unsigned integer, 0x00..0x17 (0..23)\nfor (let i = 0; i <= 0x17; i++) {\n jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]\n}\njump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows\njump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows\njump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows\njump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows\njump[0x1c] = invalidMinor\njump[0x1d] = invalidMinor\njump[0x1e] = invalidMinor\njump[0x1f] = invalidMinor\n// negative integer, -1-0x00..-1-0x17 (-1..-24)\nfor (let i = 0x20; i <= 0x37; i++) {\n jump[i] = invalidMinor // negintDecode, handled by quick[]\n}\njump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows\njump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows\njump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows\njump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows\njump[0x3c] = invalidMinor\njump[0x3d] = invalidMinor\njump[0x3e] = invalidMinor\njump[0x3f] = invalidMinor\n// byte string, 0x00..0x17 bytes follow\nfor (let i = 0x40; i <= 0x57; i++) {\n jump[i] = bytes.decodeBytesCompact\n}\njump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow\njump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow\njump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow\njump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow\njump[0x5c] = invalidMinor\njump[0x5d] = invalidMinor\njump[0x5e] = invalidMinor\njump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by \"break\"\n// UTF-8 string 0x00..0x17 bytes follow\nfor (let i = 0x60; i <= 0x77; i++) {\n jump[i] = string.decodeStringCompact\n}\njump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow\njump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow\njump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow\njump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow\njump[0x7c] = invalidMinor\njump[0x7d] = invalidMinor\njump[0x7e] = invalidMinor\njump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by \"break\"\n// array, 0x00..0x17 data items follow\nfor (let i = 0x80; i <= 0x97; i++) {\n jump[i] = array.decodeArrayCompact\n}\njump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow\njump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow\njump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow\njump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow\njump[0x9c] = invalidMinor\njump[0x9d] = invalidMinor\njump[0x9e] = invalidMinor\njump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by \"break\"\n// map, 0x00..0x17 pairs of data items follow\nfor (let i = 0xa0; i <= 0xb7; i++) {\n jump[i] = map.decodeMapCompact\n}\njump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow\njump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow\njump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow\njump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow\njump[0xbc] = invalidMinor\njump[0xbd] = invalidMinor\njump[0xbe] = invalidMinor\njump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by \"break\"\n// tags\nfor (let i = 0xc0; i <= 0xd7; i++) {\n jump[i] = tag.decodeTagCompact\n}\njump[0xd8] = tag.decodeTag8\njump[0xd9] = tag.decodeTag16\njump[0xda] = tag.decodeTag32\njump[0xdb] = tag.decodeTag64\njump[0xdc] = invalidMinor\njump[0xdd] = invalidMinor\njump[0xde] = invalidMinor\njump[0xdf] = invalidMinor\n// 0xe0..0xf3 simple values, unsupported\nfor (let i = 0xe0; i <= 0xf3; i++) {\n jump[i] = errorer('simple values are not supported')\n}\njump[0xf4] = invalidMinor // false, handled by quick[]\njump[0xf5] = invalidMinor // true, handled by quick[]\njump[0xf6] = invalidMinor // null, handled by quick[]\njump[0xf7] = float.decodeUndefined // undefined\njump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported\njump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)\njump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)\njump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)\njump[0xfc] = invalidMinor\njump[0xfd] = invalidMinor\njump[0xfe] = invalidMinor\njump[0xff] = float.decodeBreak // \"break\" stop code\n\n/** @type {Token[]} */\nexport const quick = []\n// ints <24\nfor (let i = 0; i < 24; i++) {\n quick[i] = new Token(Type.uint, i, 1)\n}\n// negints >= -24\nfor (let i = -1; i >= -24; i--) {\n quick[31 - i] = new Token(Type.negint, i, 1)\n}\n// empty bytes\nquick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)\n// empty string\nquick[0x60] = new Token(Type.string, '', 1)\n// empty list\nquick[0x80] = new Token(Type.array, 0, 1)\n// empty map\nquick[0xa0] = new Token(Type.map, 0, 1)\n// false\nquick[0xf4] = new Token(Type.false, false, 1)\n// true\nquick[0xf5] = new Token(Type.true, true, 1)\n// null\nquick[0xf6] = new Token(Type.null, null, 1)\n\n/**\n * @param {Token} token\n * @returns {AllocatedByteView|undefined}\n */\nexport function quickEncodeToken (token) {\n switch (token.type) {\n case Type.false:\n return fromArray([0xf4])\n case Type.true:\n return fromArray([0xf5])\n case Type.null:\n return fromArray([0xf6])\n case Type.bytes:\n if (!token.value.length) {\n return fromArray([0x40])\n }\n return\n case Type.string:\n if (token.value === '') {\n return fromArray([0x60])\n }\n return\n case Type.array:\n if (token.value === 0) {\n return fromArray([0x80])\n }\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.map:\n if (token.value === 0) {\n return fromArray([0xa0])\n }\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.uint:\n if (token.value < 24) {\n return fromArray([Number(token.value)])\n }\n return\n case Type.negint:\n if (token.value >= -24) {\n return fromArray([31 - Number(token.value)])\n }\n }\n}\n","import { is } from './is.js'\nimport { Token, Type } from './token.js'\nimport { Bl, U8Bl } from './bl.js'\nimport { encodeErrPrefix } from './common.js'\nimport { quickEncodeToken } from './jump.js'\nimport { asU8A, compare, fromString } from './byte-utils.js'\n\nimport { encodeUint, encodeUintValue } from './0uint.js'\nimport { encodeNegint } from './1negint.js'\nimport { encodeBytes } from './2bytes.js'\nimport { encodeString } from './3string.js'\nimport { encodeArray } from './4array.js'\nimport { encodeMap } from './5map.js'\nimport { encodeTag } from './6tag.js'\nimport { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'\n\n/**\n * @typedef {import('../interface.js').EncodeOptions} EncodeOptions\n * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder\n * @typedef {import('../interface.js').Reference} Reference\n * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder\n * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder\n * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').ByteView} ByteView\n * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView\n */\n\n/** @type {EncodeOptions} */\nconst defaultEncodeOptions = {\n float64: false,\n mapSorter,\n quickEncodeToken\n}\n\n/** @type {EncodeOptions} */\nexport const rfc8949EncodeOptions = Object.freeze({\n mapSorter: rfc8949MapSorter,\n quickEncodeToken\n})\n\n/** @returns {TokenTypeEncoder[]} */\nexport function makeCborEncoders () {\n const encoders = []\n encoders[Type.uint.major] = encodeUint\n encoders[Type.negint.major] = encodeNegint\n encoders[Type.bytes.major] = encodeBytes\n encoders[Type.string.major] = encodeString\n encoders[Type.array.major] = encodeArray\n encoders[Type.map.major] = encodeMap\n encoders[Type.tag.major] = encodeTag\n encoders[Type.float.major] = encodeFloat\n return encoders\n}\n\nconst cborEncoders = makeCborEncoders()\n\nconst defaultWriter = new Bl()\n\n/** @implements {Reference} */\nclass Ref {\n /**\n * @param {object|any[]} obj\n * @param {Reference|undefined} parent\n */\n constructor (obj, parent) {\n this.obj = obj\n this.parent = parent\n }\n\n /**\n * @param {object|any[]} obj\n * @returns {boolean}\n */\n includes (obj) {\n /** @type {Reference|undefined} */\n let p = this\n do {\n if (p.obj === obj) {\n return true\n }\n } while (p = p.parent) // eslint-disable-line\n return false\n }\n\n /**\n * @param {Reference|undefined} stack\n * @param {object|any[]} obj\n * @returns {Reference}\n */\n static createCheck (stack, obj) {\n if (stack && stack.includes(obj)) {\n throw new Error(`${encodeErrPrefix} object contains circular references`)\n }\n return new Ref(obj, stack)\n }\n}\n\nconst simpleTokens = {\n null: new Token(Type.null, null),\n undefined: new Token(Type.undefined, undefined),\n true: new Token(Type.true, true),\n false: new Token(Type.false, false),\n emptyArray: new Token(Type.array, 0),\n emptyMap: new Token(Type.map, 0)\n}\n\n/** @type {{[typeName: string]: StrictTypeEncoder}} */\nconst typeEncoders = {\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n number (obj, _typ, _options, _refStack) {\n if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {\n return new Token(Type.float, obj)\n } else if (obj >= 0) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n bigint (obj, _typ, _options, _refStack) {\n if (obj >= BigInt(0)) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n Uint8Array (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n string (obj, _typ, _options, _refStack) {\n return new Token(Type.string, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n boolean (obj, _typ, _options, _refStack) {\n return obj ? simpleTokens.true : simpleTokens.false\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n null (_obj, _typ, _options, _refStack) {\n return simpleTokens.null\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n undefined (_obj, _typ, _options, _refStack) {\n return simpleTokens.undefined\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n ArrayBuffer (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n DataView (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Array (obj, _typ, options, refStack) {\n if (!obj.length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyArray, new Token(Type.break)]\n }\n return simpleTokens.emptyArray\n }\n refStack = Ref.createCheck(refStack, obj)\n const entries = []\n let i = 0\n for (const e of obj) {\n entries[i++] = objectToTokens(e, options, refStack)\n }\n if (options.addBreakTokens) {\n return [new Token(Type.array, obj.length), entries, new Token(Type.break)]\n }\n return [new Token(Type.array, obj.length), entries]\n },\n\n /**\n * @param {any} obj\n * @param {string} typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Object (obj, typ, options, refStack) {\n // could be an Object or a Map\n const isMap = typ !== 'Object'\n // it's slightly quicker to use Object.keys() than Object.entries()\n const keys = isMap ? obj.keys() : Object.keys(obj)\n const maxLength = isMap ? obj.size : keys.length\n\n /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */\n let entries\n\n if (maxLength) {\n // Pre-allocate the array with the expected size\n entries = new Array(maxLength)\n refStack = Ref.createCheck(refStack, obj)\n const skipUndefined = !isMap && options.ignoreUndefinedProperties\n\n let i = 0\n for (const key of keys) {\n const value = isMap ? obj.get(key) : obj[key]\n if (skipUndefined && value === undefined) {\n continue\n }\n entries[i++] = [\n objectToTokens(key, options, refStack),\n objectToTokens(value, options, refStack)\n ]\n }\n\n // Truncate only if properties were skipped\n if (i < maxLength) {\n entries.length = i\n }\n }\n\n if (!entries?.length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyMap, new Token(Type.break)]\n }\n return simpleTokens.emptyMap\n }\n\n sortMapEntries(entries, options)\n if (options.addBreakTokens) {\n return [new Token(Type.map, entries.length), entries, new Token(Type.break)]\n }\n return [new Token(Type.map, entries.length), entries]\n },\n\n /**\n * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded\n * form of the wrapped value. The value is recursively tokenised through\n * `objectToTokens()` so any registered `typeEncoders` apply to it.\n *\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Tagged (obj, _typ, options, refStack) {\n return [\n new Token(Type.tag, obj.tag),\n objectToTokens(obj.value, options, refStack)\n ]\n }\n}\n\ntypeEncoders.Map = typeEncoders.Object\ntypeEncoders.Buffer = typeEncoders.Uint8Array\nfor (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {\n typeEncoders[`${typ}Array`] = typeEncoders.DataView\n}\n\n/**\n * @param {any} obj\n * @param {EncodeOptions} [options]\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\nfunction objectToTokens (obj, options = {}, refStack) {\n const typ = is(obj)\n const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]\n if (typeof customTypeEncoder === 'function') {\n const tokens = customTypeEncoder(obj, typ, options, refStack)\n if (tokens != null) {\n return tokens\n }\n }\n const typeEncoder = typeEncoders[typ]\n if (!typeEncoder) {\n throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)\n }\n return typeEncoder(obj, typ, options, refStack)\n}\n\n/*\nCBOR key sorting is a mess.\n\nThe canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9\nincludes the wording:\n\n> The keys in every map must be sorted lowest value to highest.\n> Sorting is performed on the bytes of the representation of the key\n> data items without paying attention to the 3/5 bit splitting for\n> major types.\n> ...\n> * If two keys have different lengths, the shorter one sorts\n earlier;\n> * If two keys have the same length, the one with the lower value\n in (byte-wise) lexical order sorts earlier.\n\n1. It is not clear what \"bytes of the representation of the key\" means: is it\n the CBOR representation, or the binary representation of the object itself?\n Consider the int and uint difference here.\n2. It is not clear what \"without paying attention to\" means: do we include it\n and compare on that? Or do we omit the special prefix byte, (mostly) treating\n the key in its plain binary representation form.\n\nThe FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR\nwording and clarifies it according to their understanding.\nhttps://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding\n\n> The keys in every map must be sorted lowest value to highest. Sorting is\n> performed on the bytes of the representation of the key data items without\n> paying attention to the 3/5 bit splitting for major types. The sorting rules\n> are:\n> * If the major types are different, the one with the lower value in numerical\n> order sorts earlier.\n> * If two keys have different lengths, the shorter one sorts earlier;\n> * If two keys have the same length, the one with the lower value in\n> (byte-wise) lexical order sorts earlier.\n\nSome other implementations, such as borc, do a full encode then do a\nlength-first, byte-wise-second comparison:\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151\n\nThis has the benefit of being able to easily handle arbitrary keys, including\ncomplex types (maps and arrays).\n\nWe'll opt for the FIDO approach, since it affords some efficies since we don't\nneed a full encode of each key to determine order and can defer to the types\nto determine how to most efficiently order their values (i.e. int and uint\nordering can be done on the numbers, no need for byte-wise, for example).\n\nRecommendation: stick to single key types or you'll get into trouble, and prefer\nstring keys because it's much simpler that way.\n*/\n\n/**\n * @param {TokenOrNestedTokens[]} entries\n * @param {EncodeOptions} options\n */\nfunction sortMapEntries (entries, options) {\n // cast because entries carry the wider TokenOrNestedTokens element type while\n // MapSorter narrows to (Token | Token[])[]; the original direct sort relied on\n // sort's bivariant parameter check, the wrapper below re-states it\n const mapSorter = /** @type {(e1: TokenOrNestedTokens, e2: TokenOrNestedTokens, options?: EncodeOptions) => number} */ (options.mapSorter)\n if (mapSorter) {\n // pass options so a sorter can honour encode options (e.g. major 7 keys\n // order by their float64-honouring encoding); custom sorters that take\n // only (e1, e2) simply ignore the extra argument\n entries.sort((e1, e2) => mapSorter(e1, e2, options))\n }\n}\n\n/**\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @param {EncodeOptions} [options]\n * @returns {number}\n */\nfunction mapSorter (e1, e2, options) {\n // the key position ([0]) could have a single token or an array\n // almost always it'll be a single token but complex key might get involved\n const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]\n const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]\n\n // different key type majors\n if (keyToken1.type.major !== keyToken2.type.major) {\n return keyToken1.type.compare(keyToken2.type)\n }\n\n const major = keyToken1.type.major\n // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)\n const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2, options)\n if (tcmp === 0) {\n // duplicate key or complex type where the first token matched,\n // i.e. a map or array and we're only comparing the opening token\n console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')\n }\n return tcmp\n}\n\n/**\n * @typedef {Token & { _keyBytes?: AllocatedByteView }} TokenEx\n *\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction rfc8949MapSorter (e1, e2) {\n if (e1[0] instanceof Token && e2[0] instanceof Token) {\n const t1 = /** @type {TokenEx} */ (e1[0])\n const t2 = /** @type {TokenEx} */ (e2[0])\n\n if (!t1._keyBytes) {\n t1._keyBytes = encodeRfc8949(t1.value)\n }\n\n if (!t2._keyBytes) {\n t2._keyBytes = encodeRfc8949(t2.value)\n }\n\n return compare(t1._keyBytes, t2._keyBytes)\n }\n\n throw new Error('rfc8949MapSorter: complex key types are not supported yet')\n}\n\n/**\n * @param {any} data\n * @returns {AllocatedByteView}\n */\nfunction encodeRfc8949 (data) {\n return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {TokenOrNestedTokens} tokens\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n */\nfunction tokensToEncoded (writer, tokens, encoders, options) {\n if (Array.isArray(tokens)) {\n for (const token of tokens) {\n tokensToEncoded(writer, token, encoders, options)\n }\n } else {\n encoders[tokens.type.major](writer, tokens, options)\n }\n}\n\n// CBOR major type prefixes, cached from Type for hot path performance\nconst MAJOR_UINT = Type.uint.majorEncoded\nconst MAJOR_NEGINT = Type.negint.majorEncoded\nconst MAJOR_BYTES = Type.bytes.majorEncoded\nconst MAJOR_STRING = Type.string.majorEncoded\nconst MAJOR_ARRAY = Type.array.majorEncoded\nconst MAJOR_MAP = Type.map.majorEncoded\n\n// Simple value bytes (CBOR major type 7 + minor value)\nconst SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE\nconst SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE\nconst SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL\nconst SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED\n\nconst neg1b = BigInt(-1)\nconst pos1b = BigInt(1)\n\n/**\n * Compact direct-path writes avoid the full uint boundary chain.\n * @param {ByteWriter} writer\n * @param {number} major\n * @param {number|bigint} uint\n */\nfunction directEncodeUintValue (writer, major, uint) {\n if (uint < 24) {\n writer.pushByte(major | Number(uint))\n } else {\n encodeUintValue(writer, major, uint)\n }\n}\n\n/**\n * Check if direct encoding can be used for the given options.\n * Direct encoding bypasses token creation for most values.\n * @param {EncodeOptions} options\n * @returns {boolean}\n */\nfunction canDirectEncode (options) {\n // Cannot use direct encode with addBreakTokens (needs special break token handling).\n // Direct encode checks typeEncoders per-value, falling back to tokens as needed.\n // Maps fall back to token-based encoding for efficient key sorting.\n return options.addBreakTokens !== true\n}\n\n/**\n * Encode a map through the default deterministic sorter while keeping values\n * on the direct path. Only keys need tokens for comparison.\n * @param {ByteWriter} writer\n * @param {any} data\n * @param {string} typ\n * @param {EncodeOptions} options\n * @param {Reference|undefined} refStack\n */\nfunction directEncodeMap (writer, data, typ, options, refStack) {\n const isMap = typ === 'Map'\n const keys = isMap ? data.keys() : Object.keys(data)\n const maxLength = isMap ? data.size : keys.length\n\n if (!maxLength) {\n writer.pushByte(MAJOR_MAP)\n return\n }\n\n refStack = Ref.createCheck(refStack, data)\n const skipUndefined = !isMap && options.ignoreUndefinedProperties\n const entries = new Array(maxLength)\n let length = 0\n\n for (const key of keys) {\n const value = isMap ? data.get(key) : data[key]\n if (skipUndefined && value === undefined) {\n continue\n }\n entries[length++] = [objectToTokens(key, options, refStack), value]\n }\n\n if (length === 0) {\n writer.pushByte(MAJOR_MAP)\n return\n }\n if (length < maxLength) {\n entries.length = length\n }\n\n entries.sort((e1, e2) => mapSorter(e1, e2, options))\n directEncodeUintValue(writer, MAJOR_MAP, length)\n for (const [key, value] of entries) {\n tokensToEncoded(writer, key, cborEncoders, options)\n directEncode(writer, value, options, refStack)\n }\n}\n\n/**\n * Direct encode a value to the writer, bypassing token creation for most types.\n * Falls back to token-based encoding for custom type encoders.\n * @param {ByteWriter} writer\n * @param {any} data\n * @param {EncodeOptions} options\n * @param {Reference|undefined} refStack\n */\nfunction directEncode (writer, data, options, refStack) {\n const typ = is(data)\n\n // Check for custom encoder for THIS specific type\n const customEncoder = options.typeEncoders && options.typeEncoders[typ]\n if (customEncoder) {\n const tokens = customEncoder(data, typ, options, refStack)\n if (tokens != null) {\n // Custom encoder returned tokens, serialize immediately\n tokensToEncoded(writer, tokens, cborEncoders, options)\n return\n }\n // Custom encoder returned null, fall through to default handling\n }\n\n // Direct encode based on type\n switch (typ) {\n case 'null':\n writer.pushByte(SIMPLE_NULL)\n return\n\n case 'undefined':\n writer.pushByte(SIMPLE_UNDEFINED)\n return\n\n case 'boolean':\n writer.pushByte(data ? SIMPLE_TRUE : SIMPLE_FALSE)\n return\n\n case 'number':\n if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {\n // Float, use token encoder for complex float encoding\n encodeFloat(writer, new Token(Type.float, data), options)\n } else if (data >= 0) {\n directEncodeUintValue(writer, MAJOR_UINT, data)\n } else {\n // Negative integer\n directEncodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)\n }\n return\n\n case 'bigint':\n if (data >= BigInt(0)) {\n directEncodeUintValue(writer, MAJOR_UINT, data)\n } else {\n directEncodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)\n }\n return\n\n case 'string': {\n const bytes = fromString(data)\n directEncodeUintValue(writer, MAJOR_STRING, bytes.length)\n writer.push(bytes)\n return\n }\n\n case 'Uint8Array':\n directEncodeUintValue(writer, MAJOR_BYTES, data.length)\n writer.push(data)\n return\n\n case 'Array':\n if (!data.length) {\n writer.pushByte(MAJOR_ARRAY) // Empty array: 0x80\n return\n }\n refStack = Ref.createCheck(refStack, data)\n directEncodeUintValue(writer, MAJOR_ARRAY, data.length)\n for (const elem of data) {\n directEncode(writer, elem, options, refStack)\n }\n return\n\n case 'Object':\n case 'Map':\n if (options.mapSorter === mapSorter) {\n directEncodeMap(writer, data, typ, options, refStack)\n } else {\n const tokens = typeEncoders.Object(data, typ, options, refStack)\n tokensToEncoded(writer, tokens, cborEncoders, options)\n }\n return\n\n default:\n // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)\n {\n const typeEncoder = typeEncoders[typ]\n if (!typeEncoder) {\n throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)\n }\n const tokens = typeEncoder(data, typ, options, refStack)\n tokensToEncoded(writer, tokens, cborEncoders, options)\n }\n }\n}\n\n/**\n * @template {ArrayBufferLike} T\n * @overload\n * @param {any} data\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n * @param {Uint8Array<T>} destination\n * @returns {Uint8Array<T>}\n */\n/**\n * @overload\n * @param {any} data\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n * @returns {AllocatedByteView}\n */\n/**\n * @param {any} data\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n * @param {ByteView} [destination]\n * @returns {ByteView}\n */\nfunction encodeCustom (data, encoders, options, destination) {\n // arg ordering is different to encodeInto for backward compatibility\n const hasDest = destination instanceof Uint8Array\n let writeTo = hasDest ? new U8Bl(destination) : defaultWriter\n\n const tokens = objectToTokens(data, options)\n if (!Array.isArray(tokens) && options.quickEncodeToken) {\n const quickBytes = options.quickEncodeToken(tokens)\n if (quickBytes) {\n if (hasDest) {\n // Copy quick bytes into destination buffer\n writeTo.push(quickBytes)\n return writeTo.toBytes()\n }\n return quickBytes\n }\n const encoder = encoders[tokens.type.major]\n if (encoder.encodedSize) {\n const size = encoder.encodedSize(tokens, options)\n if (!hasDest) {\n writeTo = new Bl(size)\n }\n encoder(writeTo, tokens, options)\n // this would be a problem with encodedSize() functions\n if (writeTo.chunks.length !== 1) {\n throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)\n }\n return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])\n }\n }\n writeTo.reset()\n tokensToEncoded(writeTo, tokens, encoders, options)\n return writeTo.toBytes(true)\n}\n\n/**\n * @param {any} data\n * @param {EncodeOptions} [options]\n * @returns {AllocatedByteView}\n */\nfunction encode (data, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n\n // Use direct encode path when possible\n if (canDirectEncode(options)) {\n defaultWriter.reset()\n directEncode(defaultWriter, data, options, undefined)\n return defaultWriter.toBytes(true)\n }\n\n return encodeCustom(data, cborEncoders, options)\n}\n\n/**\n * @template {ArrayBufferLike} T\n * @param {any} data\n * @param {Uint8Array<T>} destination\n * @param {EncodeOptions} [options]\n * @returns {{ written: number }}\n */\nfunction encodeInto (data, destination, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n\n // Use direct encode path when possible\n if (canDirectEncode(options)) {\n const writer = new U8Bl(destination)\n directEncode(writer, data, options, undefined)\n return { written: writer.toBytes().length }\n }\n\n const result = encodeCustom(data, cborEncoders, options, destination)\n return { written: result.length }\n}\n\nexport { objectToTokens, encode, encodeCustom, encodeInto, Ref }\n","import { decodeErrPrefix } from './common.js'\nimport { Type } from './token.js'\nimport { jump, quick } from './jump.js'\nimport { asU8A } from './byte-utils.js'\n\n/**\n * @typedef {import('./token.js').Token} Token\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer\n * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl\n */\n\nconst defaultDecodeOptions = {\n strict: false,\n allowIndefinite: true,\n allowUndefined: true,\n allowBigInt: true\n}\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass Tokeniser {\n /**\n * @param {Uint8Array} data\n * @param {DecodeOptions} options\n */\n constructor (data, options = {}) {\n this._pos = 0\n this.data = data\n this.options = options\n }\n\n pos () {\n return this._pos\n }\n\n done () {\n return this._pos >= this.data.length\n }\n\n next () {\n const byt = this.data[this._pos]\n let token = quick[byt]\n if (token === undefined) {\n const decoder = jump[byt]\n // if we're here then there's something wrong with our jump or quick lists!\n if (!decoder) {\n throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)\n }\n const minor = byt & 31\n token = decoder(this.data, this._pos, minor, this.options)\n }\n // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)\n this._pos += token.encodedLength\n return token\n }\n}\n\nconst DONE = Symbol.for('DONE')\nconst BREAK = Symbol.for('BREAK')\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|typeof BREAK|typeof DONE}\n */\nfunction tokenToArray (token, tokeniser, options) {\n const arr = []\n for (let i = 0; i < token.value; i++) {\n const value = tokensToObject(tokeniser, options)\n if (value === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length array\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)\n }\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)\n }\n arr[i] = value\n }\n return arr\n}\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|typeof BREAK|typeof DONE}\n */\nfunction tokenToMap (token, tokeniser, options) {\n const useMaps = options.useMaps === true\n const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true\n const obj = useMaps ? undefined : {}\n const m = useMaps ? new Map() : undefined\n for (let i = 0; i < token.value; i++) {\n const key = tokensToObject(tokeniser, options)\n if (key === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length map\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)\n }\n if (key === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)\n }\n if (!useMaps && typeof key !== 'string') {\n throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)\n }\n if (rejectDuplicateMapKeys) {\n // @ts-ignore\n if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {\n throw new Error(`${decodeErrPrefix} found repeat map key \"${key}\"`)\n }\n }\n const value = tokensToObject(tokeniser, options)\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)\n }\n if (useMaps) {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n m.set(key, value)\n } else if (key === '__proto__') {\n // a plain assignment would invoke the prototype setter instead of creating\n // an own property, losing the entry and mutating the object's prototype\n Object.defineProperty(obj, key, { value, configurable: true, enumerable: true, writable: true })\n } else {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n obj[key] = value\n }\n }\n // @ts-ignore c'mon man\n return useMaps ? m : obj\n}\n\n/**\n * Generator that yields [key, value] entries from a CBOR map token.\n * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).\n * @param {Token} token - The map token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {Generator<[any, any], void, unknown>}\n */\nfunction * tokenToMapEntries (token, tokeniser, options) {\n for (let i = 0; i < token.value; i++) {\n const key = tokensToObject(tokeniser, options)\n if (key === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length map\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)\n }\n if (key === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)\n }\n const value = tokensToObject(tokeniser, options)\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)\n }\n yield [key, value]\n }\n}\n\n/**\n * Creates a TagDecodeControl object for tag decoders.\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {TagDecodeControl}\n */\nfunction createTagDecodeControl (tokeniser, options) {\n /** @type {TagDecodeControl & {_called: boolean}} */\n const decode = function () {\n if (decode._called) {\n throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)\n }\n decode._called = true\n const value = tokensToObject(tokeniser, options)\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} tag content missing`)\n }\n if (value === BREAK) {\n throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)\n }\n return value\n }\n\n decode.entries = function () {\n if (decode._called) {\n throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)\n }\n decode._called = true\n\n const token = tokeniser.next()\n if (!Type.equals(token.type, Type.map)) {\n throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)\n }\n\n const entries = []\n for (const entry of tokenToMapEntries(token, tokeniser, options)) {\n entries.push(entry)\n }\n return entries\n }\n\n decode._called = false\n return decode\n}\n\n/**\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|typeof BREAK|typeof DONE}\n */\nfunction tokensToObject (tokeniser, options) {\n // should we support array as an argument?\n // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?\n if (tokeniser.done()) {\n return DONE\n }\n\n const token = tokeniser.next()\n\n if (Type.equals(token.type, Type.break)) {\n return BREAK\n }\n\n if (token.type.terminal) {\n return token.value\n }\n\n if (Type.equals(token.type, Type.array)) {\n return tokenToArray(token, tokeniser, options)\n }\n\n if (Type.equals(token.type, Type.map)) {\n return tokenToMap(token, tokeniser, options)\n }\n\n if (Type.equals(token.type, Type.tag)) {\n if (options.tags && typeof options.tags[token.value] === 'function') {\n const decodeControl = createTagDecodeControl(tokeniser, options)\n const result = options.tags[token.value](decodeControl)\n if (!decodeControl._called) {\n throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)\n }\n return result\n }\n throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)\n }\n throw new Error('unsupported')\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {[any, Uint8Array]}\n */\nfunction decodeFirst (data, options) {\n if (!(data instanceof Uint8Array)) {\n throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)\n }\n options = Object.assign({}, defaultDecodeOptions, options)\n // Convert Buffer to plain Uint8Array for faster slicing in decode path\n const u8aData = asU8A(data)\n const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)\n const decoded = tokensToObject(tokeniser, options)\n if (decoded === DONE) {\n throw new Error(`${decodeErrPrefix} did not find any content to decode`)\n }\n if (decoded === BREAK) {\n throw new Error(`${decodeErrPrefix} got unexpected break`)\n }\n return [decoded, data.subarray(tokeniser.pos())]\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {any}\n */\nfunction decode (data, options) {\n const [decoded, remainder] = decodeFirst(data, options)\n if (remainder.length > 0) {\n throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)\n }\n return decoded\n}\n\nexport { Tokeniser, tokensToObject, decode, decodeFirst }\n","/**\n * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl\n * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder\n */\n\n/**\n * A wrapper class for representing a CBOR tag with an arbitrary nested value.\n *\n * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit\n * a CBOR tag header followed by the encoded form of `value`, and it can be\n * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)\n * to round-trip a tag through decode without losing the tag number.\n *\n * Use `Tagged` for one-off tag handling where defining a dedicated\n * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when\n * wrapping a structure in a single application-specific tag (COSE, dCBOR\n * envelopes, etc.).\n *\n * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer\n * a dedicated `typeEncoders` entry instead.\n */\nexport class Tagged {\n /**\n * @param {number} tag - CBOR tag number, a non-negative integer\n * @param {any} value - The value to be tagged; encoded recursively\n */\n constructor (tag, value) {\n if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {\n throw new TypeError('Tagged: tag must be a non-negative integer')\n }\n this.tag = tag\n this.value = value\n }\n\n /**\n * Build a tag decoder for use in `decode()`'s `tags` option that returns the\n * decoded content wrapped in a `Tagged` instance, preserving the tag number\n * for the caller to inspect.\n *\n * @param {number} tag - The CBOR tag number this decoder will be registered for\n * @returns {TaggedTagDecoder}\n *\n * @example\n * import { decode, Tagged } from 'cborg'\n * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })\n * // value instanceof Tagged; value.tag === 16\n */\n static decoder (tag) {\n return (decode) => new Tagged(tag, decode())\n }\n\n /**\n * Build a `tags` option for `decode()` that wraps each listed tag number in\n * a `Tagged` instance, preserving those tags through decode without\n * registering a dedicated decoder per tag.\n *\n * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve\n * @returns {{[tagNumber: number]: TaggedTagDecoder}}\n *\n * @example\n * import { decode, Tagged } from 'cborg'\n * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })\n */\n static preserve (...tagNumbers) {\n /** @type {{[tagNumber: number]: TaggedTagDecoder}} */\n const tags = {}\n for (const tag of tagNumbers) {\n tags[tag] = Tagged.decoder(tag)\n }\n return tags\n }\n}\n\n// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'\n// for instances, allowing the default Tagged typeEncoder to match.\nObject.defineProperty(Tagged.prototype, Symbol.toStringTag, {\n value: 'Tagged'\n})\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\nimport {\n decode as cborgDecode,\n encodeInto as cborgEncodeInto,\n Token,\n Tokenizer,\n Type,\n} from \"cborg\";\nimport type { Encodable } from \"../cbor.js\";\n\n/** Decodes text keeping a leading U+FEFF, which a default TextDecoder drops. */\nconst bomPreservingDecoder = new TextDecoder(\"utf-8\", { ignoreBOM: true });\n\n/** Encodes text into fresh arrays, never into a pool shared with other code. */\nconst textEncoder = new TextEncoder();\n\n/**\n * Tokenizer that keeps a leading byte order mark in text strings. cborg's own\n * decoder drops it, which would hand back a different string than the one\n * the bytes hold.\n */\nclass TextTokenizer extends Tokenizer {\n next(): Token {\n const start = this.pos();\n const token = super.next();\n if (token.type === Type.string) {\n // The header is one byte, plus 1, 2, 4 or 8 length bytes past minor 23\n const minor = this.data[start] & 0x1f;\n const header = minor < 24 ? 1 : 1 + (1 << (minor - 24));\n const text = this.data.subarray(start + header, this.pos());\n if (text[0] === 0xef && text[1] === 0xbb && text[2] === 0xbf) {\n token.value = bomPreservingDecoder.decode(text);\n }\n }\n return token;\n }\n}\n\n/**\n * Decodes bytes the Rust validator already checked into what cborg makes of\n * them, maps as `Map`. Decoded byte strings are copies, never views into the\n * input.\n *\n * @internal\n */\nexport function parse(data: Uint8Array): unknown {\n // cborg copies byte strings out with slice(), which on a Node Buffer\n // returns a view, so decode from a plain view over the same bytes\n const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n\n // A custom tokenizer does not get cborg's decode defaults, so the one for\n // 64-bit integers is set here explicitly\n const options = {\n allowBigInt: true,\n useMaps: true,\n rejectDuplicateMapKeys: true,\n };\n return cborgDecode(bytes, {\n ...options,\n tokenizer: new TextTokenizer(bytes, options),\n }) as unknown;\n}\n\n/**\n * Reports whether a string is well-formed UTF-16. A lone surrogate has no\n * UTF-8 form, and encoding it would silently turn it into U+FFFD.\n */\nfunction isWellFormed(text: string): boolean {\n for (let i = 0; i < text.length; i++) {\n const unit = text.charCodeAt(i);\n if (unit >= 0xd800 && unit <= 0xdbff) {\n const next = text.charCodeAt(i + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) {\n return false;\n }\n i++;\n } else if (unit >= 0xdc00 && unit <= 0xdfff) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Serializes a value bound to its codec into the bytes the WASM boundary\n * takes, canonical by cborg's ordering and verified again on the Rust side.\n *\n * cborg's own encode reuses one writer across all callers and can hand out\n * views into it, exposing earlier outputs through their buffer. Encoding into\n * a buffer owned here keeps plaintext out of that shared writer. Text is\n * encoded here too, as cborg would draw it from Node's shared Buffer pool.\n * Every scratch buffer and text encoding is wiped before it is dropped.\n *\n * @internal\n */\nexport function serialize<T>(item: Encodable<T>): Uint8Array {\n const value = item.codec.encode(item.value);\n\n const texts: Uint8Array[] = [];\n const options = {\n typeEncoders: {\n string: (text: string) => {\n if (!isWellFormed(text)) {\n throw new Error(\"text is not well-formed, it holds a lone surrogate\");\n }\n const token = new Token(Type.string, text);\n token.encodedBytes = textEncoder.encode(text);\n texts.push(token.encodedBytes);\n return token;\n },\n },\n };\n try {\n for (let size = 256; ; size *= 2) {\n const scratch = new Uint8Array(size);\n try {\n const { written } = cborgEncodeInto(value, scratch, options);\n return scratch.slice(0, written);\n } catch (err) {\n if (\n !(err instanceof Error) ||\n !err.message.includes(\"destination buffer is too small\")\n ) {\n throw err;\n }\n } finally {\n scratch.fill(0);\n }\n }\n } finally {\n for (const text of texts) {\n text.fill(0);\n }\n }\n}\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * Typed codecs over the restricted CBOR type system used across Dark Bio.\n *\n * https://datatracker.ietf.org/doc/html/rfc8949\n *\n * Only a minimal subset of CBOR is supported: booleans, null, 64-bit\n * integers, text strings, byte strings, arrays and maps with integer keys. The\n * encoding is deterministic (RFC 8949 Section 4.2.1). Integers take their\n * shortest form, map keys are sorted by their encoded bytes, and there are no\n * indefinite lengths, floats or tags.\n *\n * A codec declares the shape of a value the way a Rust type deriving `Cbor`\n * does. Values are bound to their codec before they are encoded, and bytes\n * before they are decoded. The `cose` and `cwt` functions take them the same\n * way. {@link encode} and {@link decode} reject any encoding that breaks the\n * rules above. The cborg library handles the bytes, so a codec converts to and\n * from what cborg takes, such as a `Map` for a map.\n *\n * @example\n * ```ts\n * import { cbor } from \"@darkbio/crypto\";\n *\n * const Triple = cbor.tuple(cbor.uint, cbor.text, cbor.bytes);\n * const bytes = await cbor.encode(Triple.value([1n, \"two\", new Uint8Array([3])]));\n * // bytes holds 83 01 63 74 77 6f 41 03 in hex\n *\n * const [a, b, c] = await cbor.decode(Triple.bytes(bytes));\n * console.log(a, b, c); // 1n two Uint8Array(1) [ 3 ]\n * ```\n *\n * @module\n */\n\nimport { cbor_verify } from \"./wasm/darkbio_crypto_wasm.js\";\nimport { parse, serialize } from \"./internal/cborg.js\";\nimport { ensureInit } from \"./internal/init.js\";\nimport { U64_MAX } from \"./internal/limits.js\";\n\n/** A value bound to the codec that encodes it. */\nexport interface Encodable<T> {\n /** The codec that encodes the value. */\n readonly codec: Codec<T>;\n /** The value to encode. */\n readonly value: T;\n}\n\n/** Bytes bound to the codec that decodes them. */\nexport interface Decodable<T> {\n /** The codec that decodes the bytes. */\n readonly codec: Codec<T>;\n /** The CBOR bytes to decode. */\n readonly bytes: Uint8Array;\n}\n\n/**\n * A codec between a value of type T and the representation cborg encodes and\n * decodes. Both directions throw a {@link CodecError} on a value of the wrong\n * shape.\n */\nexport interface Codec<T> {\n /** Converts a value into what cborg encodes, checking its shape. */\n encode(value: T): unknown;\n /** Converts what cborg decoded into a value, checking its shape. */\n decode(value: unknown): T;\n /** Binds a value to this codec for encoding. */\n value(value: T): Encodable<T>;\n /** Binds bytes to this codec for decoding. */\n bytes(data: Uint8Array): Decodable<T>;\n}\n\n/** A required field of a map, a codec at an integer key. */\nexport interface Field<T> {\n /** The integer key of the field in the map. */\n readonly key: number;\n /** The codec of the field's value. */\n readonly codec: Codec<T>;\n /** Marks the field as required. */\n readonly required: true;\n}\n\n/** An optional field of a map, absent from the map when undefined. */\nexport interface OptionalField<T> {\n /** The integer key of the field in the map. */\n readonly key: number;\n /** The codec of the field's value. */\n readonly codec: Codec<T>;\n /** Marks the field as optional. */\n readonly required: false;\n}\n\n/** The fields of a map codec, by name. */\nexport type Fields = Record<string, Field<unknown> | OptionalField<unknown>>;\n\n/** The value type of a map codec, required fields present and optional ones optional. */\nexport type Values<F extends Fields> = {\n [K in keyof F as F[K] extends Field<unknown> ? K : never]: F[K] extends Field<\n infer T\n >\n ? T\n : never;\n} & {\n [\n K in keyof F as F[K] extends OptionalField<unknown> ? K : never\n ]?: F[K] extends OptionalField<infer T> ? T : never;\n};\n\n/** The item codecs of a tuple codec, one per position of the value types. */\nexport type Codecs<T extends unknown[]> = { [I in keyof T]: Codec<T[I]> };\n\n/**\n * A value of the wrong shape for a codec. The path names where in the value\n * the mismatch is, array items as `[i]` and map fields as `.name`, empty at\n * the top.\n */\nexport class CodecError extends Error {\n /** What is wrong with the value. */\n readonly reason: string;\n /** Where in the value the mismatch is, empty at the top. */\n readonly path: string;\n\n /**\n * Creates an error for a value of the wrong shape.\n *\n * @param reason - What is wrong with the value\n * @param path - Where in the value the mismatch is, empty at the top\n */\n constructor(reason: string, path = \"\") {\n super(path === \"\" ? reason : `${reason} at ${path}`);\n this.name = \"CodecError\";\n this.reason = reason;\n this.path = path;\n }\n}\n\n/** Runs a step of a codec, prefixing the path of a failure inside it. */\nfunction within<T>(segment: string, run: () => T): T {\n try {\n return run();\n } catch (err) {\n if (err instanceof CodecError) {\n throw new CodecError(err.reason, segment + err.path);\n }\n throw err;\n }\n}\n\n/**\n * Builds a codec from its two directions, adding the value and bytes bindings.\n * Both directions should throw a {@link CodecError} on a value of the wrong\n * shape.\n *\n * @example\n * ```ts\n * import { cbor } from \"@darkbio/crypto\";\n *\n * // A date carried as whole seconds since the Unix epoch\n * const date = cbor.codec<Date>(\n * (value) => cbor.uint.encode(BigInt(Math.floor(value.getTime() / 1000))),\n * (value) => new Date(Number(cbor.uint.decode(value)) * 1000),\n * );\n * const bytes = await cbor.encode(date.value(new Date(\"2026-01-01T00:00:00Z\")));\n * console.log(await cbor.decode(date.bytes(bytes))); // 2026-01-01T00:00:00.000Z\n * ```\n *\n * @param encode - Converts a value into what cborg encodes\n * @param decode - Converts what cborg decoded into a value\n * @returns The codec\n */\nexport function codec<T>(\n encode: (value: T) => unknown,\n decode: (value: unknown) => T,\n): Codec<T> {\n const self: Codec<T> = {\n encode,\n decode,\n value: (value) => ({ codec: self, value }),\n bytes: (data) => ({ codec: self, bytes: data }),\n };\n return self;\n}\n\n/** Builds a codec whose two directions share one check. */\nfunction primitive<T>(\n check: (value: unknown) => value is T,\n reason: string,\n): Codec<T> {\n const guard = (value: unknown): T => {\n if (!check(value)) {\n throw new CodecError(reason);\n }\n return value;\n };\n return codec(guard, guard);\n}\n\nconst I64_MIN = -(1n << 63n);\nconst I64_MAX = (1n << 63n) - 1n;\n\n/** Reads an integer cborg produced, a number within the safe range or a bigint beyond it. */\nfunction integer(value: unknown, reason: string): bigint {\n if (typeof value === \"number\" && Number.isSafeInteger(value)) {\n return BigInt(value);\n }\n if (typeof value === \"bigint\") {\n return value;\n }\n throw new CodecError(reason);\n}\n\n/** A boolean. */\nexport const bool: Codec<boolean> = primitive(\n (value): value is boolean => typeof value === \"boolean\",\n \"not a boolean\",\n);\n\n/** Null, the counterpart of Rust's `cbor::Null` and of a `None` option. */\nexport const nil: Codec<null> = primitive(\n (value): value is null => value === null,\n \"not null\",\n);\n\n/**\n * A UTF-8 text string. Decoding keeps every character, a leading U+FEFF\n * included. Encoding rejects a string with a lone surrogate, since it has no\n * UTF-8 form.\n */\nexport const text: Codec<string> = primitive(\n (value): value is string => typeof value === \"string\",\n \"not text\",\n);\n\n/** A byte string. */\nexport const bytes: Codec<Uint8Array> = primitive(\n (value): value is Uint8Array => value instanceof Uint8Array,\n \"not bytes\",\n);\n\n/**\n * Anything, passed through as cborg decoded it, the counterpart of\n * `cbor::Raw`. The value is not checked against any shape, but {@link encode}\n * and {@link decode} still check its encoding.\n */\nexport const raw: Codec<unknown> = codec(\n (value) => value,\n (value) => value,\n);\n\n/** An unsigned 64-bit integer, a bigint in both directions. */\nexport const uint: Codec<bigint> = codec(\n (value) => {\n if (typeof value !== \"bigint\" || value < 0n || value > U64_MAX) {\n throw new CodecError(\"not an unsigned 64 bit integer\");\n }\n return value;\n },\n (value) => {\n const parsed = integer(value, \"not an unsigned 64 bit integer\");\n if (parsed < 0n || parsed > U64_MAX) {\n throw new CodecError(\"not an unsigned 64 bit integer\");\n }\n return parsed;\n },\n);\n\n/** A signed 64-bit integer, a bigint in both directions. */\nexport const int: Codec<bigint> = codec(\n (value) => {\n if (typeof value !== \"bigint\" || value < I64_MIN || value > I64_MAX) {\n throw new CodecError(\"not a signed 64 bit integer\");\n }\n return value;\n },\n (value) => {\n const parsed = integer(value, \"not a signed 64 bit integer\");\n if (parsed < I64_MIN || parsed > I64_MAX) {\n throw new CodecError(\"not a signed 64 bit integer\");\n }\n return parsed;\n },\n);\n\n/**\n * A value or null, the counterpart of `Option<T>` in an array or as a\n * nullable map field.\n *\n * @param item - The codec of the value when it is not null\n * @returns The codec\n */\nexport function nullable<T>(item: Codec<T>): Codec<T | null> {\n return codec(\n (value) => (value === null ? null : item.encode(value)),\n (value) => (value === null ? null : item.decode(value)),\n );\n}\n\n/**\n * A member of a set of small integers, the counterpart of a Rust enum encoded\n * as its discriminant.\n *\n * @param values - The integers the value may take\n * @returns The codec\n */\nexport function enumeration<E extends number>(values: readonly E[]): Codec<E> {\n const members = new Set<number>(values);\n const guard = (value: unknown): E => {\n if (typeof value !== \"number\" || !members.has(value)) {\n throw new CodecError(\"not a member of the enumeration\");\n }\n return value as E;\n };\n return codec(guard, guard);\n}\n\n/**\n * An array of any length of one kind of item, the counterpart of `Array<T>`.\n *\n * @param item - The codec of every item\n * @returns The codec\n */\nexport function array<T>(item: Codec<T>): Codec<T[]> {\n return codec(\n (value) => {\n if (!Array.isArray(value)) {\n throw new CodecError(\"not an array\");\n }\n return value.map((element: T, i) =>\n within(`[${i}]`, () => item.encode(element)),\n );\n },\n (value) => {\n if (!Array.isArray(value)) {\n throw new CodecError(\"not an array\");\n }\n return value.map((element: unknown, i) =>\n within(`[${i}]`, () => item.decode(element)),\n );\n },\n );\n}\n\n/**\n * An array of a fixed length with an item codec per position, the counterpart\n * of a tuple or a struct with `#[cbor(array)]`.\n *\n * @param items - The codec of each item, in order\n * @returns The codec\n */\nexport function tuple<T extends unknown[]>(...items: Codecs<T>): Codec<T> {\n const codecs: Codec<unknown>[] = items;\n return codec(\n (value) => {\n if (!Array.isArray(value) || value.length !== codecs.length) {\n throw new CodecError(`not an array of ${codecs.length}`);\n }\n return codecs.map((item, i) =>\n within(`[${i}]`, () => item.encode(value[i])),\n );\n },\n (value) => {\n if (!Array.isArray(value) || value.length !== codecs.length) {\n throw new CodecError(`not an array of ${codecs.length}`);\n }\n return codecs.map((item, i) =>\n within(`[${i}]`, () => item.decode((value as unknown[])[i])),\n ) as T;\n },\n );\n}\n\n/**\n * Declares a required map field.\n *\n * @param key - The integer key of the field in the map\n * @param codec - The codec of the field's value\n * @returns The field\n * @throws CodecError if the key is not a safe integer\n */\nexport function field<T>(key: number, codec: Codec<T>): Field<T> {\n if (!Number.isSafeInteger(key)) {\n throw new CodecError(\"map key is not an integer\");\n }\n return { key, codec, required: true };\n}\n\n/**\n * Declares a map field that may be absent, the counterpart of an\n * `Option<T>` field. The field is left out of the map when its value is\n * undefined.\n *\n * @param field - The field to make optional\n * @returns The optional field\n */\nexport function optional<T>(field: Field<T>): OptionalField<T> {\n return { key: field.key, codec: field.codec, required: false };\n}\n\n/**\n * An integer-keyed map with exactly the declared fields, the counterpart of\n * a struct with `#[cbor(key = N)]` fields. Both ways, a field the map does\n * not declare and a required field missing are refused, as is a key that is\n * not an integer. Only own properties of a value count as its fields.\n *\n * @example\n * ```ts\n * import { cbor } from \"@darkbio/crypto\";\n *\n * const Bar = cbor.map({\n * x: cbor.field(1, cbor.uint), // required\n * y: cbor.optional(cbor.field(2, cbor.bytes)), // omitted when undefined\n * z: cbor.field(3, cbor.nullable(cbor.uint)), // always present, a value or null\n * });\n * const bytes = await cbor.encode(Bar.value({ x: 7n, z: null }));\n * // bytes holds a2 01 07 03 f6 in hex\n *\n * console.log(await cbor.decode(Bar.bytes(bytes))); // { x: 7n, z: null }\n * ```\n *\n * @param fields - The fields of the map, by name\n * @returns The codec\n * @throws CodecError if two fields share a key\n */\nexport function map<F extends Fields>(fields: F): Codec<Values<F>> {\n const entries = Object.entries(fields).map(\n ([name, field]) => [name, { ...field }] as const,\n );\n const declared = new Set(entries.map(([name]) => name));\n const names = new Map<number, string>();\n for (const [name, field] of entries) {\n if (names.has(field.key)) {\n throw new CodecError(`map key ${field.key} declared twice`);\n }\n names.set(field.key, name);\n }\n return codec(\n (value) => {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new CodecError(\"not an object\");\n }\n const record = value as Record<string, unknown>;\n for (const name of Object.keys(record)) {\n if (!declared.has(name)) {\n throw new CodecError(`unexpected field ${name}`);\n }\n }\n const encoded = new Map<number, unknown>();\n for (const [name, field] of entries) {\n const item = Object.hasOwn(record, name) ? record[name] : undefined;\n if (item === undefined) {\n if (field.required) {\n throw new CodecError(`missing field ${name}`);\n }\n continue;\n }\n encoded.set(\n field.key,\n within(`.${name}`, () => field.codec.encode(item)),\n );\n }\n return encoded;\n },\n (value) => {\n if (!(value instanceof Map)) {\n throw new CodecError(\"not a map\");\n }\n const decoded: [string, unknown][] = [];\n for (const key of (value as Map<unknown, unknown>).keys()) {\n if (typeof key !== \"number\" || !Number.isSafeInteger(key)) {\n throw new CodecError(\"map key is not an integer\");\n }\n if (!names.has(key)) {\n throw new CodecError(`unexpected key ${key}`);\n }\n }\n for (const [name, field] of entries) {\n if (!(value as Map<unknown, unknown>).has(field.key)) {\n if (field.required) {\n throw new CodecError(`missing key ${field.key}`);\n }\n continue;\n }\n decoded.push([\n name,\n within(`.${name}`, () =>\n field.codec.decode((value as Map<unknown, unknown>).get(field.key)),\n ),\n ]);\n }\n return Object.fromEntries(decoded) as Values<F>;\n },\n );\n}\n\n/**\n * Encodes a value bound to its codec into deterministic CBOR.\n *\n * @param item - The value and the codec to encode it with\n * @returns The CBOR bytes\n * @throws CodecError on a value of the wrong shape\n * @throws If the encoding falls outside the restricted type system, such as a\n * float in a raw value or text with a lone surrogate\n */\nexport async function encode<T>(item: Encodable<T>): Promise<Uint8Array> {\n const data = serialize(item);\n await ensureInit();\n cbor_verify(data);\n return data;\n}\n\n/**\n * Decodes deterministic CBOR bound to its codec. The bytes must pass\n * {@link verify} before anything is decoded.\n *\n * @param item - The bytes and the codec to decode them with\n * @returns The decoded value\n * @throws If the bytes are not valid restricted CBOR\n * @throws CodecError on bytes of the wrong shape\n */\nexport async function decode<T>(item: Decodable<T>): Promise<T> {\n await ensureInit();\n cbor_verify(item.bytes);\n return item.codec.decode(parse(item.bytes));\n}\n\n/**\n * Verifies that data is exactly one complete CBOR item under the restricted\n * type system.\n *\n * It checks UTF-8 text, deterministic integer and length encodings, integer\n * map keys in order without duplicates, and the nesting limit. It does not\n * check application-specific schemas or values. The `cose` and `cwt`\n * functions apply the same check to every payload they sign, embed or return.\n *\n * @param data - The CBOR bytes to validate\n * @throws If the data is not valid restricted CBOR\n */\nexport async function verify(data: Uint8Array): Promise<void> {\n await ensureInit();\n cbor_verify(data);\n}\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * Renders bytes as lowercase hex.\n *\n * @internal\n */\nexport function toHex(data: Uint8Array): string {\n return Array.from(data, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\",\n );\n}\n\n/**\n * Reports whether two byte arrays hold the same bytes.\n *\n * @internal\n */\nexport function equal(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * Composite ML-DSA-65 + Ed25519 digital signatures.\n *\n * https://datatracker.ietf.org/doc/html/draft-ietf-lamps-pq-composite-sigs\n *\n * A key signs a message with ML-DSA-65 and Ed25519 at once, and a signature\n * verifies only if both halves do. Keys and signatures round-trip through\n * fixed-size byte arrays. Keys also support PEM serialization.\n *\n * @example\n * ```ts\n * import { xdsa } from \"@darkbio/crypto\";\n *\n * const secret = await xdsa.SecretKey.generate();\n * const verifier = secret.publicKey();\n * const text = new TextEncoder();\n *\n * const signature = secret.sign(text.encode(\"hello\"));\n * console.log(verifier.verify(text.encode(\"hello\"), signature)); // true\n * console.log(verifier.verify(text.encode(\"tampered\"), signature)); // false\n *\n * const restored = await xdsa.PublicKey.fromPem(verifier.toPem());\n * console.log(restored.fingerprint().equals(verifier.fingerprint())); // true\n * ```\n *\n * @module\n */\n\nimport {\n xdsa_secret_key_size,\n xdsa_public_key_size,\n xdsa_signature_size,\n xdsa_fingerprint_size,\n XdsaSecretKey as WasmSecretKey,\n XdsaPublicKey as WasmPublicKey,\n XdsaSignature as WasmSignature,\n XdsaFingerprint as WasmFingerprint,\n} from \"./wasm/darkbio_crypto_wasm.js\";\nimport { ensureInit, requireInit } from \"./internal/init.js\";\nimport { codec, CodecError, type Codec } from \"./cbor.js\";\nimport { equal, toHex } from \"./internal/bytes.js\";\n\n/**\n * Size of the secret key seed in bytes, the 32-byte ML-DSA-65 seed followed by\n * the 32-byte Ed25519 seed.\n */\nexport const SECRET_KEY_SIZE = 64;\n\n/**\n * Size of the public key in bytes, the 1952-byte ML-DSA-65 key followed by the\n * 32-byte Ed25519 key.\n */\nexport const PUBLIC_KEY_SIZE = 1984;\n\n/**\n * Size of a signature in bytes, the 3309-byte ML-DSA-65 signature followed by\n * the 64-byte Ed25519 signature.\n */\nexport const SIGNATURE_SIZE = 3373;\n\n/** Size of a key fingerprint in bytes. */\nexport const FINGERPRINT_SIZE = 32;\n\n/**\n * Returns the sizes in bytes as the Rust library defines them, the same values\n * as the constants of this module.\n */\nexport async function sizes(): Promise<{\n secretKey: number;\n publicKey: number;\n signature: number;\n fingerprint: number;\n}> {\n await ensureInit();\n return {\n secretKey: xdsa_secret_key_size(),\n publicKey: xdsa_public_key_size(),\n signature: xdsa_signature_size(),\n fingerprint: xdsa_fingerprint_size(),\n };\n}\n\n/** A 256-bit unique identifier for an xDSA key. */\nexport class Fingerprint {\n /** @internal */\n readonly _wasm: WasmFingerprint;\n\n private constructor(inner: WasmFingerprint) {\n this._wasm = inner;\n }\n\n /** @internal */\n static _fromWasm(inner: WasmFingerprint): Fingerprint {\n return new Fingerprint(inner);\n }\n\n /**\n * Creates a fingerprint from a 32-byte array.\n *\n * @throws If `bytes` is not 32 bytes long\n */\n static async fromBytes(bytes: Uint8Array): Promise<Fingerprint> {\n await ensureInit();\n return new Fingerprint(WasmFingerprint.from_bytes(bytes));\n }\n\n /** Converts a fingerprint into a 32-byte array. */\n toBytes(): Uint8Array {\n return this._wasm.to_bytes();\n }\n\n /** Renders a fingerprint as lowercase hex. */\n toHex(): string {\n return toHex(this.toBytes());\n }\n\n /** Reports whether another fingerprint is the same. */\n equals(other: Fingerprint): boolean {\n return equal(this.toBytes(), other.toBytes());\n }\n}\n\n/** An xDSA signature, an ML-DSA-65 signature paired with an Ed25519 one. */\nexport class Signature {\n /** @internal */\n readonly _wasm: WasmSignature;\n\n private constructor(inner: WasmSignature) {\n this._wasm = inner;\n }\n\n /** @internal */\n static _fromWasm(inner: WasmSignature): Signature {\n return new Signature(inner);\n }\n\n /**\n * Creates a signature from a 3373-byte array. The halves are only checked\n * when the signature is verified.\n *\n * @throws If `bytes` is not 3373 bytes long\n */\n static async fromBytes(bytes: Uint8Array): Promise<Signature> {\n await ensureInit();\n return new Signature(WasmSignature.from_bytes(bytes));\n }\n\n /** Converts a signature into a 3373-byte array. */\n toBytes(): Uint8Array {\n return this._wasm.to_bytes();\n }\n}\n\n/**\n * An xDSA public key, an ML-DSA-65 key paired with an Ed25519 key, for\n * verifying quantum resistant digital signatures.\n */\nexport class PublicKey {\n /** @internal */\n readonly _wasm: WasmPublicKey;\n\n private constructor(inner: WasmPublicKey) {\n this._wasm = inner;\n }\n\n /** @internal */\n static _fromWasm(inner: WasmPublicKey): PublicKey {\n return new PublicKey(inner);\n }\n\n /**\n * Creates a public key from a 1984-byte array.\n *\n * @throws If `bytes` is not 1984 bytes long or not a valid composite key\n */\n static async fromBytes(bytes: Uint8Array): Promise<PublicKey> {\n await ensureInit();\n return new PublicKey(WasmPublicKey.from_bytes(bytes));\n }\n\n /**\n * Parses a PEM string into a public key. The input must be exactly one\n * `PUBLIC KEY` block, with no leading whitespace, strict base64 and LF or\n * CRLF line endings throughout.\n *\n * @throws If the PEM is malformed or holds another kind of key\n */\n static async fromPem(pem: string): Promise<PublicKey> {\n await ensureInit();\n return new PublicKey(WasmPublicKey.from_pem(pem));\n }\n\n /** Converts a public key into a 1984-byte array. */\n toBytes(): Uint8Array {\n return this._wasm.to_bytes();\n }\n\n /** Serializes a public key into a `PUBLIC KEY` PEM block with LF line endings. */\n toPem(): string {\n return this._wasm.to_pem();\n }\n\n /** Reports whether another public key is the same. */\n equals(other: PublicKey): boolean {\n return equal(this.toBytes(), other.toBytes());\n }\n\n /** Returns a 256-bit unique identifier for this key. */\n fingerprint(): Fingerprint {\n return Fingerprint._fromWasm(this._wasm.fingerprint());\n }\n\n /**\n * Verifies a digital signature of the message. Both the ML-DSA-65 and the\n * Ed25519 halves must verify.\n *\n * @param message - The signed message\n * @param signature - The signature to check\n * @returns True if the signature is valid for this key and message, false\n * otherwise\n */\n verify(message: Uint8Array, signature: Signature): boolean {\n return this._wasm.verify(message, signature._wasm);\n }\n}\n\n/**\n * An xDSA secret key, an ML-DSA-65 key paired with an Ed25519 key, for\n * creating quantum resistant digital signatures. The key stays in WASM memory\n * unless {@link SecretKey.toBytes} or {@link SecretKey.toPem} copies it out.\n */\nexport class SecretKey {\n private inner: WasmSecretKey | undefined;\n\n private constructor(inner: WasmSecretKey) {\n this.inner = inner;\n }\n\n /** @internal */\n get _wasm(): WasmSecretKey {\n if (this.inner === undefined) {\n throw new Error(\"secret key used after dispose\");\n }\n return this.inner;\n }\n\n /** Generates a new, random secret key. */\n static async generate(): Promise<SecretKey> {\n await ensureInit();\n return new SecretKey(WasmSecretKey.generate());\n }\n\n /**\n * Creates a secret key from a 64-byte seed.\n *\n * @throws If `bytes` is not 64 bytes long\n */\n static async fromBytes(bytes: Uint8Array): Promise<SecretKey> {\n await ensureInit();\n return new SecretKey(WasmSecretKey.from_bytes(bytes));\n }\n\n /**\n * Parses a PEM string into a secret key. The input must be exactly one\n * `PRIVATE KEY` block, with no leading whitespace, strict base64 and LF or\n * CRLF line endings throughout.\n *\n * @throws If the PEM is malformed or holds another kind of key\n */\n static async fromPem(pem: string): Promise<SecretKey> {\n await ensureInit();\n return new SecretKey(WasmSecretKey.from_pem(pem));\n }\n\n /** Converts a secret key into its 64-byte seed. */\n toBytes(): Uint8Array {\n return this._wasm.to_bytes();\n }\n\n /** Serializes a secret key into a `PRIVATE KEY` PEM block with LF line endings. */\n toPem(): string {\n return this._wasm.to_pem();\n }\n\n /** Retrieves the public counterpart of the secret key. */\n publicKey(): PublicKey {\n return PublicKey._fromWasm(this._wasm.public_key());\n }\n\n /** Returns a 256-bit unique identifier for this key, the same as its public key's. */\n fingerprint(): Fingerprint {\n return Fingerprint._fromWasm(this._wasm.fingerprint());\n }\n\n /**\n * Creates a digital signature of the message.\n *\n * @param message - The message to sign\n * @returns The signature\n */\n sign(message: Uint8Array): Signature {\n return Signature._fromWasm(this._wasm.sign(message));\n }\n\n /**\n * Wipes the secret key held in WASM memory. Every later use of this key\n * throws, and disposing it again does nothing. Copies already exported, such\n * as by {@link SecretKey.toBytes}, are not affected. Without a dispose, the\n * key is only wiped if the garbage collector finalizes it, which is not\n * guaranteed.\n */\n dispose(): void {\n const inner = this.inner;\n this.inner = undefined;\n inner?.free();\n }\n}\n\n/** Private COSE algorithm identifier of composite ML-DSA-65 + Ed25519 signatures. */\nexport const ALGORITHM_ID = -70000;\n\n/**\n * Codec of a public key as its 1984 bytes. Decoding throws a\n * {@link CodecError} unless the bytes are a valid key. Calling its decode\n * directly needs any async function of this package to have run first.\n */\nexport const publicKey: Codec<PublicKey> = codec(\n (key) => {\n if (!(key instanceof PublicKey)) {\n throw new CodecError(\"not a public key\");\n }\n return key.toBytes();\n },\n (value) => {\n if (!(value instanceof Uint8Array)) {\n throw new CodecError(\"not a public key\");\n }\n requireInit();\n try {\n return PublicKey._fromWasm(WasmPublicKey.from_bytes(value));\n } catch (err) {\n throw new CodecError(\n `not a public key: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n },\n);\n\n/**\n * Codec of a fingerprint as its 32 bytes. Decoding throws a {@link CodecError}\n * unless the value is 32 bytes. Calling its decode directly needs any async\n * function of this package to have run first.\n */\nexport const fingerprint: Codec<Fingerprint> = codec(\n (print) => {\n if (!(print instanceof Fingerprint)) {\n throw new CodecError(\"not a fingerprint\");\n }\n return print.toBytes();\n },\n (value) => {\n if (!(value instanceof Uint8Array)) {\n throw new CodecError(\"not a fingerprint\");\n }\n requireInit();\n try {\n return Fingerprint._fromWasm(WasmFingerprint.from_bytes(value));\n } catch (err) {\n throw new CodecError(\n `not a fingerprint: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n },\n);\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * X-Wing HPKE encryption.\n *\n * https://datatracker.ietf.org/doc/html/rfc9180\n * https://datatracker.ietf.org/doc/html/draft-connolly-cfrg-xwing-kem\n *\n * Messages are encrypted to a public key with X-Wing, a hybrid of ML-KEM-768\n * and X25519, and sealed with ChaCha20-Poly1305. Encryption and decryption use\n * an application domain, prefixed with `dark-bio-v1:`, which both sides must\n * agree on. The ciphertext also authenticates a second message that must be\n * supplied separately.\n *\n * A {@link Sender} and {@link Receiver} pair shares one encapsulated key across\n * many messages, which must be opened in the order they were sealed. The\n * domain is fixed when the contexts are created.\n *\n * @example\n * ```ts\n * import { xhpke } from \"@darkbio/crypto\";\n *\n * const secret = await xhpke.SecretKey.generate();\n * const text = new TextEncoder();\n * const domain = text.encode(\"example\");\n *\n * const sealed = secret.publicKey().seal(text.encode(\"secret\"), text.encode(\"header\"), domain);\n * const plaintext = secret.open(sealed, text.encode(\"header\"), domain);\n * console.log(new TextDecoder().decode(plaintext)); // secret\n *\n * // A tampered header fails authentication\n * try {\n * secret.open(sealed, text.encode(\"other\"), domain);\n * } catch {\n * console.log(\"rejected\");\n * }\n * ```\n *\n * @example\n * ```ts\n * import { xhpke } from \"@darkbio/crypto\";\n *\n * const secret = await xhpke.SecretKey.generate();\n * const domain = new TextEncoder().encode(\"example\");\n *\n * const { sender, encapKey } = secret.publicKey().newSender(domain);\n * const receiver = secret.newReceiver(encapKey, domain);\n *\n * for (const message of [\"first\", \"second\"]) {\n * const ciphertext = sender.seal(new TextEncoder().encode(message), new Uint8Array());\n * const plaintext = receiver.open(ciphertext, new Uint8Array());\n * console.log(new TextDecoder().decode(plaintext)); // first, then second\n * }\n * ```\n *\n * @module\n */\n\nimport {\n xhpke_secret_key_size,\n xhpke_public_key_size,\n xhpke_encap_key_size,\n xhpke_fingerprint_size,\n XhpkeSecretKey as WasmSecretKey,\n XhpkePublicKey as WasmPublicKey,\n XhpkeFingerprint as WasmFingerprint,\n XhpkeSender as WasmSender,\n XhpkeReceiver as WasmReceiver,\n} from \"./wasm/darkbio_crypto_wasm.js\";\nimport { ensureInit, requireInit } from \"./internal/init.js\";\nimport { codec, CodecError, type Codec } from \"./cbor.js\";\nimport { equal, toHex } from \"./internal/bytes.js\";\n\n/** Size of the secret key seed in bytes. */\nexport const SECRET_KEY_SIZE = 32;\n\n/** Size of the public key in bytes. */\nexport const PUBLIC_KEY_SIZE = 1216;\n\n/**\n * Size of the encapsulated key in bytes, the prefix of every\n * {@link PublicKey.seal} output.\n */\nexport const ENCAP_KEY_SIZE = 1120;\n\n/** Size of a key fingerprint in bytes. */\nexport const FINGERPRINT_SIZE = 32;\n\n/**\n * Returns the sizes in bytes as the Rust library defines them, the same values\n * as the constants of this module.\n */\nexport async function sizes(): Promise<{\n secretKey: number;\n publicKey: number;\n encapKey: number;\n fingerprint: number;\n}> {\n await ensureInit();\n return {\n secretKey: xhpke_secret_key_size(),\n publicKey: xhpke_public_key_size(),\n encapKey: xhpke_encap_key_size(),\n fingerprint: xhpke_fingerprint_size(),\n };\n}\n\n/** A 256-bit unique identifier for an xHPKE key. */\nexport class Fingerprint {\n /** @internal */\n readonly _wasm: WasmFingerprint;\n\n private constructor(inner: WasmFingerprint) {\n this._wasm = inner;\n }\n\n /** @internal */\n static _fromWasm(inner: WasmFingerprint): Fingerprint {\n return new Fingerprint(inner);\n }\n\n /**\n * Creates a fingerprint from a 32-byte array.\n *\n * @throws If `bytes` is not 32 bytes long\n */\n static async fromBytes(bytes: Uint8Array): Promise<Fingerprint> {\n await ensureInit();\n return new Fingerprint(WasmFingerprint.from_bytes(bytes));\n }\n\n /** Converts a fingerprint into a 32-byte array. */\n toBytes(): Uint8Array {\n return this._wasm.to_bytes();\n }\n\n /** Renders a fingerprint as lowercase hex. */\n toHex(): string {\n return toHex(this.toBytes());\n }\n\n /** Reports whether another fingerprint is the same. */\n equals(other: Fingerprint): boolean {\n return equal(this.toBytes(), other.toBytes());\n }\n}\n\n/** An X-Wing public key for encrypting HPKE messages. */\nexport class PublicKey {\n /** @internal */\n readonly _wasm: WasmPublicKey;\n\n private constructor(inner: WasmPublicKey) {\n this._wasm = inner;\n }\n\n /** @internal */\n static _fromWasm(inner: WasmPublicKey): PublicKey {\n return new PublicKey(inner);\n }\n\n /**\n * Creates a public key from a 1216-byte array.\n *\n * @throws If `bytes` is not 1216 bytes long or not a valid X-Wing key\n */\n static async fromBytes(bytes: Uint8Array): Promise<PublicKey> {\n await ensureInit();\n return new PublicKey(WasmPublicKey.from_bytes(bytes));\n }\n\n /**\n * Parses a PEM string into a public key. The input must be exactly one\n * `PUBLIC KEY` block, with no leading whitespace, strict base64 and LF or\n * CRLF line endings throughout.\n *\n * @throws If the PEM is malformed or holds another kind of key\n */\n static async fromPem(pem: string): Promise<PublicKey> {\n await ensureInit();\n return new PublicKey(WasmPublicKey.from_pem(pem));\n }\n\n /** Converts a public key into a 1216-byte array. */\n toBytes(): Uint8Array {\n return this._wasm.to_bytes();\n }\n\n /** Serializes a public key into a `PUBLIC KEY` PEM block with LF line endings. */\n toPem(): string {\n return this._wasm.to_pem();\n }\n\n /** Reports whether another public key is the same. */\n equals(other: PublicKey): boolean {\n return equal(this.toBytes(), other.toBytes());\n }\n\n /**\n * Returns a 256-bit unique identifier for this key, the SHA-256 hash of the\n * public key bytes.\n */\n fingerprint(): Fingerprint {\n return Fingerprint._fromWasm(this._wasm.fingerprint());\n }\n\n /**\n * Creates an HPKE sender context for multi-message encryption to this\n * public key. Messages it seals must be opened in order by a\n * {@link Receiver} created from the returned encapsulated key.\n *\n * HPKE runs in base mode, which does not authenticate the sender. The\n * recipient cannot verify who created the context.\n *\n * @param domain - Application domain, fixed for every message of the context\n * @returns The stateful sender and the 1120-byte encapsulated key, which\n * must be transmitted to the recipient\n */\n newSender(domain: Uint8Array): { sender: Sender; encapKey: Uint8Array } {\n const wasmSender = this._wasm.new_sender(domain);\n const encapKey = wasmSender.encap_key();\n return { sender: Sender._fromWasm(wasmSender), encapKey };\n }\n\n /**\n * Encrypts a message to this public key, also authenticating a second\n * message that is not included in the output. Opening it with\n * {@link SecretKey.open} needs the same second message and domain.\n *\n * HPKE runs in base mode, which does not authenticate the sender. The\n * recipient cannot verify who sealed the message.\n *\n * @param msgToSeal - The message to encrypt\n * @param msgToAuth - The message to authenticate but not include\n * @param domain - Application domain, which both sides must agree on\n * @returns The 1120-byte encapsulated key followed by the ciphertext\n */\n seal(\n msgToSeal: Uint8Array,\n msgToAuth: Uint8Array,\n domain: Uint8Array,\n ): Uint8Array {\n return this._wasm.seal(msgToSeal, msgToAuth, domain);\n }\n}\n\n/**\n * An X-Wing secret key for decrypting HPKE messages. The key stays in WASM\n * memory unless {@link SecretKey.toBytes} or {@link SecretKey.toPem} copies it\n * out.\n */\nexport class SecretKey {\n private inner: WasmSecretKey | undefined;\n\n private constructor(inner: WasmSecretKey) {\n this.inner = inner;\n }\n\n /** @internal */\n get _wasm(): WasmSecretKey {\n if (this.inner === undefined) {\n throw new Error(\"secret key used after dispose\");\n }\n return this.inner;\n }\n\n /** Generates a new, random secret key. */\n static async generate(): Promise<SecretKey> {\n await ensureInit();\n return new SecretKey(WasmSecretKey.generate());\n }\n\n /**\n * Creates a secret key from a 32-byte seed.\n *\n * @throws If `bytes` is not 32 bytes long\n */\n static async fromBytes(bytes: Uint8Array): Promise<SecretKey> {\n await ensureInit();\n return new SecretKey(WasmSecretKey.from_bytes(bytes));\n }\n\n /**\n * Parses a PEM string into a secret key. The input must be exactly one\n * `PRIVATE KEY` block, with no leading whitespace, strict base64 and LF or\n * CRLF line endings throughout.\n *\n * @throws If the PEM is malformed or holds another kind of key\n */\n static async fromPem(pem: string): Promise<SecretKey> {\n await ensureInit();\n return new SecretKey(WasmSecretKey.from_pem(pem));\n }\n\n /** Converts a secret key into its 32-byte seed. */\n toBytes(): Uint8Array {\n return this._wasm.to_bytes();\n }\n\n /** Serializes a secret key into a `PRIVATE KEY` PEM block with LF line endings. */\n toPem(): string {\n return this._wasm.to_pem();\n }\n\n /** Retrieves the public counterpart of the secret key. */\n publicKey(): PublicKey {\n return PublicKey._fromWasm(this._wasm.public_key());\n }\n\n /**\n * Returns a 256-bit unique identifier for this key, the SHA-256 hash of the\n * public key bytes.\n */\n fingerprint(): Fingerprint {\n return Fingerprint._fromWasm(this._wasm.fingerprint());\n }\n\n /**\n * Creates an HPKE receiver context for multi-message decryption. Messages\n * must be opened in the order the {@link Sender} sealed them.\n *\n * HPKE runs in base mode, which does not authenticate the sender. The\n * recipient cannot verify who created the context.\n *\n * @param encapKey - The 1120-byte encapsulated key from {@link PublicKey.newSender}\n * @param domain - The same application domain the sender uses\n * @returns The stateful receiver\n * @throws If `encapKey` is not 1120 bytes long or is malformed\n */\n newReceiver(encapKey: Uint8Array, domain: Uint8Array): Receiver {\n return Receiver._fromWasm(this._wasm.new_receiver(encapKey, domain));\n }\n\n /**\n * Decrypts a message sealed to this key and checks the second message it\n * authenticates.\n *\n * HPKE runs in base mode, which does not authenticate the sender. The\n * recipient cannot verify who sealed the message.\n *\n * @param sealed - The 1120-byte encapsulated key followed by the\n * ciphertext, as {@link PublicKey.seal} returns them\n * @param msgToAuth - The same second message used during sealing\n * @param domain - The same application domain used during sealing\n * @returns The decrypted message\n * @throws If the data is malformed, sealed to another key or tampered with,\n * or `msgToAuth` or `domain` differ\n */\n open(\n sealed: Uint8Array,\n msgToAuth: Uint8Array,\n domain: Uint8Array,\n ): Uint8Array {\n return this._wasm.open(sealed, msgToAuth, domain);\n }\n\n /**\n * Wipes the secret key held in WASM memory. Every later use of this key\n * throws, and disposing it again does nothing. Copies already exported, such\n * as by {@link SecretKey.toBytes}, and receivers already created from it are\n * not affected. Without a dispose, the key is only wiped if the garbage\n * collector finalizes it, which is not guaranteed.\n */\n dispose(): void {\n const inner = this.inner;\n this.inner = undefined;\n inner?.free();\n }\n}\n\n/**\n * A stateful HPKE encryption context for multi-message communication, created\n * by {@link PublicKey.newSender}. Each seal uses the next nonce in the\n * sequence, so identical messages encrypt differently. The matching\n * {@link Receiver} must open messages in the order they were sealed.\n */\nexport class Sender {\n private inner: WasmSender | undefined;\n\n private constructor(inner: WasmSender) {\n this.inner = inner;\n }\n\n /** @internal */\n static _fromWasm(inner: WasmSender): Sender {\n return new Sender(inner);\n }\n\n private get wasm(): WasmSender {\n if (this.inner === undefined) {\n throw new Error(\"sender used after dispose\");\n }\n return this.inner;\n }\n\n /**\n * Encrypts a message using the next nonce in the sequence.\n *\n * @param msgToSeal - The message to encrypt\n * @param msgToAuth - The message to authenticate but not include\n * @returns The ciphertext\n */\n seal(msgToSeal: Uint8Array, msgToAuth: Uint8Array): Uint8Array {\n return this.wasm.seal(msgToSeal, msgToAuth);\n }\n\n /**\n * Wipes the keys of this context held in WASM memory. Every later use of the\n * sender throws, and disposing it again does nothing. Without a dispose, the\n * keys are only wiped if the garbage collector finalizes the sender, which is\n * not guaranteed.\n */\n dispose(): void {\n const inner = this.inner;\n this.inner = undefined;\n inner?.free();\n }\n}\n\n/**\n * A stateful HPKE decryption context for multi-message communication, created\n * by {@link SecretKey.newReceiver}. Messages must be opened in the order the\n * {@link Sender} sealed them.\n */\nexport class Receiver {\n private inner: WasmReceiver | undefined;\n\n private constructor(inner: WasmReceiver) {\n this.inner = inner;\n }\n\n /** @internal */\n static _fromWasm(inner: WasmReceiver): Receiver {\n return new Receiver(inner);\n }\n\n private get wasm(): WasmReceiver {\n if (this.inner === undefined) {\n throw new Error(\"receiver used after dispose\");\n }\n return this.inner;\n }\n\n /**\n * Decrypts a message using the next nonce in the sequence.\n *\n * @param msgToOpen - The ciphertext from {@link Sender.seal}\n * @param msgToAuth - The same second message used during sealing\n * @returns The decrypted message\n * @throws If the message is out of order or was tampered with, or\n * `msgToAuth` differs\n */\n open(msgToOpen: Uint8Array, msgToAuth: Uint8Array): Uint8Array {\n return this.wasm.open(msgToOpen, msgToAuth);\n }\n\n /**\n * Wipes the keys of this context held in WASM memory. Every later use of the\n * receiver throws, and disposing it again does nothing. Without a dispose,\n * the keys are only wiped if the garbage collector finalizes the receiver,\n * which is not guaranteed.\n */\n dispose(): void {\n const inner = this.inner;\n this.inner = undefined;\n inner?.free();\n }\n}\n\n/** Private COSE algorithm identifier of X-Wing (ML-KEM-768 + X25519). */\nexport const ALGORITHM_ID = -70001;\n\n/**\n * Codec of a public key as its 1216 bytes. Decoding throws a\n * {@link CodecError} unless the bytes are a valid key. Calling its decode\n * directly needs any async function of this package to have run first.\n */\nexport const publicKey: Codec<PublicKey> = codec(\n (key) => {\n if (!(key instanceof PublicKey)) {\n throw new CodecError(\"not a public key\");\n }\n return key.toBytes();\n },\n (value) => {\n if (!(value instanceof Uint8Array)) {\n throw new CodecError(\"not a public key\");\n }\n requireInit();\n try {\n return PublicKey._fromWasm(WasmPublicKey.from_bytes(value));\n } catch (err) {\n throw new CodecError(\n `not a public key: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n },\n);\n\n/**\n * Codec of a fingerprint as its 32 bytes. Decoding throws a {@link CodecError}\n * unless the value is 32 bytes. Calling its decode directly needs any async\n * function of this package to have run first.\n */\nexport const fingerprint: Codec<Fingerprint> = codec(\n (print) => {\n if (!(print instanceof Fingerprint)) {\n throw new CodecError(\"not a fingerprint\");\n }\n return print.toBytes();\n },\n (value) => {\n if (!(value instanceof Uint8Array)) {\n throw new CodecError(\"not a fingerprint\");\n }\n requireInit();\n try {\n return Fingerprint._fromWasm(WasmFingerprint.from_bytes(value));\n } catch (err) {\n throw new CodecError(\n `not a fingerprint: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n },\n);\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * COSE signing and encryption with xDSA and xHPKE.\n *\n * https://datatracker.ietf.org/doc/html/rfc9052\n * https://datatracker.ietf.org/doc/html/draft-ietf-cose-hpke\n *\n * Signatures are COSE_Sign1 envelopes carrying the signer's fingerprint and a\n * timestamp in the protected header. Encryption is COSE_Encrypt0 around a\n * signed envelope, so every message created by {@link seal} is also signed.\n * Payloads and authenticated messages are values bound to a `cbor` codec.\n * Signing, verification, encryption and decryption use an application domain,\n * prefixed with `dark-bio-v1:`, which both sides must agree on.\n *\n * ## Domain separation and freshness\n *\n * Choose distinct domains for distinct application operations. Domains\n * prevent a message for one purpose from being accepted for another; they do\n * not stop repeated use within the same domain. Verification accepts a\n * signature whose timestamp is at most `maxDriftSecs` seconds in the past or\n * future. An undefined `maxDriftSecs` skips this timestamp check. Applications\n * that require one-time acceptance must also track a message identifier,\n * nonce or challenge to reject replays.\n *\n * ## Wire profile\n *\n * Interoperating implementations must match these Dark Bio conventions:\n *\n * - Envelopes are untagged COSE_Sign1 and COSE_Encrypt0 arrays. CBOR tags are\n * not accepted. Headers are deterministic maps with integer keys.\n * - The private algorithm IDs are -70000 for xDSA and -70001 for xHPKE. The\n * protected `kid` is the appropriate public key's fingerprint. Signatures\n * require the private timestamp header -70002 and name it in `crit`.\n * - For signatures, the Sig_structure external_aad is the CBOR encoding of\n * `[bstr(\"dark-bio-v1:\" || domain), msgToAuth]`. An embedded payload is the\n * CBOR encoding of the caller's value.\n * - For {@link signDetached}, the caller's message is authenticated in that\n * external_aad, while the Sig_structure payload is an empty byte string and\n * the envelope payload is null. A generic COSE detached-payload API that\n * puts the caller's message in the Sig_structure payload must be adapted to\n * this convention.\n * - For encryption, the Enc_structure external_aad is the CBOR encoding of\n * `msgToAuth`, and the complete encoded Enc_structure is the HPKE AAD. HPKE\n * key derivation uses `\"dark-bio-v1:\" || domain` as its info. The X-Wing\n * encapsulated key is carried in unprotected header -4.\n *\n * Here bstr denotes a CBOR byte string and || denotes byte concatenation. The\n * domain and `msgToAuth` are not included in the returned envelope, so both\n * parties must know them or transmit them separately.\n *\n * @example\n * ```ts\n * import { cbor, cose, xdsa, xhpke } from \"@darkbio/crypto\";\n *\n * const signer = await xdsa.SecretKey.generate();\n * const domain = new TextEncoder().encode(\"example\");\n * const context = cbor.text.value(\"context\");\n *\n * // Sign a payload, binding a second message supplied separately\n * const envelope = await cose.sign(cbor.text.value(\"hello\"), context, signer, domain);\n * const payload = await cose.verify(cbor.text.bytes(envelope), context, signer.publicKey(), domain, 60);\n * console.log(payload); // hello\n *\n * // Sign and encrypt to a recipient in one step, then open and verify it back\n * const recipient = await xhpke.SecretKey.generate();\n * const sealed = await cose.seal(cbor.text.value(\"secret\"), context, signer, recipient.publicKey(), domain);\n * const opened = await cose.open(cbor.text.bytes(sealed), context, recipient, signer.publicKey(), domain, 60);\n * console.log(opened); // secret\n * ```\n *\n * @module\n */\n\nimport type { Decodable, Encodable } from \"./cbor.js\";\nimport { parse, serialize } from \"./internal/cborg.js\";\nimport {\n cose_sign,\n cose_sign_detached,\n cose_verify,\n cose_verify_detached,\n cose_signer,\n cose_peek,\n cose_recipient,\n cose_seal,\n cose_open,\n cose_encrypt,\n cose_decrypt,\n} from \"./wasm/darkbio_crypto_wasm.js\";\nimport { ensureInit } from \"./internal/init.js\";\nimport { U64_MAX } from \"./internal/limits.js\";\nimport {\n SecretKey as XdsaSecretKey,\n PublicKey as XdsaPublicKey,\n Fingerprint as XdsaFingerprint,\n} from \"./xdsa.js\";\nimport {\n SecretKey as XhpkeSecretKey,\n PublicKey as XhpkePublicKey,\n Fingerprint as XhpkeFingerprint,\n} from \"./xhpke.js\";\n\n/**\n * Converts the drift bound of a verification for the WASM boundary.\n */\nfunction driftToBigInt(maxDriftSecs?: number): bigint | undefined {\n if (maxDriftSecs === undefined) return undefined;\n if (!Number.isFinite(maxDriftSecs)) {\n throw new Error(\n \"maxDriftSecs must be a non-negative number within 64 bits\",\n );\n }\n const secs = BigInt(Math.floor(maxDriftSecs));\n if (secs < 0n || secs > U64_MAX) {\n throw new Error(\n \"maxDriftSecs must be a non-negative number within 64 bits\",\n );\n }\n return secs;\n}\n\n/**\n * Creates a COSE_Sign1 signature with an embedded payload.\n *\n * Uses the current system time as the signature timestamp.\n *\n * @param msgToEmbed - The message to sign, embedded in the envelope\n * @param msgToAuth - Additional authenticated data, signed but not embedded\n * @param signer - The xDSA secret key to sign with\n * @param domain - Application domain for separating protocol purposes\n * @returns The serialized COSE_Sign1 envelope\n * @throws CodecError if a message does not fit its codec\n * @throws If a message falls outside the restricted CBOR type system\n */\nexport async function sign<E, A>(\n msgToEmbed: Encodable<E>,\n msgToAuth: Encodable<A>,\n signer: XdsaSecretKey,\n domain: Uint8Array,\n): Promise<Uint8Array> {\n await ensureInit();\n return cose_sign(\n serialize(msgToEmbed),\n serialize(msgToAuth),\n signer._wasm,\n domain,\n );\n}\n\n/**\n * Creates a COSE_Sign1 signature without an embedded payload, the envelope\n * payload being null.\n *\n * The caller's message is authenticated in external_aad, and the payload in\n * the signature input is empty. See the module's wire profile for\n * interoperability. Uses the current system time as the signature timestamp.\n *\n * @param msgToAuth - The message to sign, not embedded in the envelope\n * @param signer - The xDSA secret key to sign with\n * @param domain - Application domain for separating protocol purposes\n * @returns The serialized COSE_Sign1 envelope\n * @throws CodecError if the message does not fit its codec\n * @throws If the message falls outside the restricted CBOR type system\n */\nexport async function signDetached<A>(\n msgToAuth: Encodable<A>,\n signer: XdsaSecretKey,\n domain: Uint8Array,\n): Promise<Uint8Array> {\n await ensureInit();\n return cose_sign_detached(serialize(msgToAuth), signer._wasm, domain);\n}\n\n/**\n * Verifies a COSE_Sign1 signature and returns the embedded payload.\n *\n * Uses the current system time for the drift check.\n *\n * @param msgToCheck - The serialized COSE_Sign1 envelope, bound to the codec\n * of its payload\n * @param msgToAuth - The same additional authenticated data used during signing\n * @param verifier - The xDSA public key to verify against\n * @param domain - Application domain for separating protocol purposes\n * @param maxDriftSecs - Maximum allowed timestamp difference in seconds, past\n * or future. A value of n accepts differences up to and including n, with\n * fractions rounded down. Undefined skips the check.\n * @returns The decoded payload\n * @throws If the envelope is malformed, carries no payload or does not verify\n * for this key, `msgToAuth` and `domain`, or its timestamp drifts too far\n * @throws If `maxDriftSecs` is negative or beyond 64 bits\n * @throws CodecError if the payload or `msgToAuth` does not fit its codec\n */\nexport async function verify<T, A>(\n msgToCheck: Decodable<T>,\n msgToAuth: Encodable<A>,\n verifier: XdsaPublicKey,\n domain: Uint8Array,\n maxDriftSecs?: number,\n): Promise<T> {\n await ensureInit();\n const payload = cose_verify(\n msgToCheck.bytes,\n serialize(msgToAuth),\n verifier._wasm,\n domain,\n driftToBigInt(maxDriftSecs),\n );\n return msgToCheck.codec.decode(parse(payload));\n}\n\n/**\n * Verifies a COSE_Sign1 signature with a detached payload.\n *\n * Uses the current system time for the drift check.\n *\n * @param msgToCheck - The serialized COSE_Sign1 envelope, with a null payload\n * @param msgToAuth - The same message used during signing\n * @param verifier - The xDSA public key to verify against\n * @param domain - Application domain for separating protocol purposes\n * @param maxDriftSecs - Maximum allowed timestamp difference in seconds, past\n * or future. A value of n accepts differences up to and including n, with\n * fractions rounded down. Undefined skips the check.\n * @throws If the envelope is malformed, embeds a payload or does not verify\n * for this key, `msgToAuth` and `domain`, or its timestamp drifts too far\n * @throws If `maxDriftSecs` is negative or beyond 64 bits\n * @throws CodecError if `msgToAuth` does not fit its codec\n */\nexport async function verifyDetached<A>(\n msgToCheck: Uint8Array,\n msgToAuth: Encodable<A>,\n verifier: XdsaPublicKey,\n domain: Uint8Array,\n maxDriftSecs?: number,\n): Promise<void> {\n await ensureInit();\n cose_verify_detached(\n msgToCheck,\n serialize(msgToAuth),\n verifier._wasm,\n domain,\n driftToBigInt(maxDriftSecs),\n );\n}\n\n/**\n * Extracts the signer's fingerprint from a COSE_Sign1 envelope without\n * verifying it.\n *\n * This allows looking up the appropriate verification key before attempting\n * full signature verification. The fingerprint is unauthenticated.\n *\n * @param signature - The serialized COSE_Sign1 envelope\n * @returns The signer's fingerprint from the protected header's `kid`\n * @throws If the envelope is malformed\n */\nexport async function signer(signature: Uint8Array): Promise<XdsaFingerprint> {\n await ensureInit();\n return XdsaFingerprint._fromWasm(cose_signer(signature));\n}\n\n/**\n * Extracts the embedded payload from a COSE_Sign1 envelope without verifying\n * it.\n *\n * The payload is unauthenticated and must not be trusted until verified with\n * {@link verify}. Use {@link signer} to extract the signer's fingerprint for\n * key lookup.\n *\n * @param signature - The serialized COSE_Sign1 envelope, bound to the codec of\n * its payload\n * @returns The decoded, unverified payload\n * @throws If the envelope is malformed or carries no payload\n * @throws CodecError if the payload does not fit its codec\n */\nexport async function peek<T>(signature: Decodable<T>): Promise<T> {\n await ensureInit();\n return signature.codec.decode(parse(cose_peek(signature.bytes)));\n}\n\n/**\n * Extracts the recipient's fingerprint from a COSE_Encrypt0 envelope without\n * decrypting it.\n *\n * This allows looking up the appropriate decryption key before attempting\n * full decryption. The fingerprint is unauthenticated.\n *\n * @param ciphertext - The serialized COSE_Encrypt0 envelope\n * @returns The recipient's fingerprint from the protected header's `kid`\n * @throws If the envelope is malformed\n */\nexport async function recipient(\n ciphertext: Uint8Array,\n): Promise<XhpkeFingerprint> {\n await ensureInit();\n return XhpkeFingerprint._fromWasm(cose_recipient(ciphertext));\n}\n\n/**\n * Signs a message then encrypts it to a recipient.\n *\n * Uses the current system time as the signature timestamp.\n *\n * @param msgToSeal - The message to sign and encrypt\n * @param msgToAuth - Additional authenticated data, signed and bound to the\n * encryption but not embedded\n * @param signerKey - The xDSA secret key to sign with\n * @param recipientKey - The xHPKE public key to encrypt to\n * @param domain - Application domain for HPKE key derivation\n * @returns The serialized COSE_Encrypt0 envelope holding the encrypted\n * COSE_Sign1\n * @throws CodecError if a message does not fit its codec\n * @throws If a message falls outside the restricted CBOR type system\n */\nexport async function seal<S, A>(\n msgToSeal: Encodable<S>,\n msgToAuth: Encodable<A>,\n signerKey: XdsaSecretKey,\n recipientKey: XhpkePublicKey,\n domain: Uint8Array,\n): Promise<Uint8Array> {\n await ensureInit();\n const plaintext = serialize(msgToSeal);\n try {\n return cose_seal(\n plaintext,\n serialize(msgToAuth),\n signerKey._wasm,\n recipientKey._wasm,\n domain,\n );\n } finally {\n plaintext.fill(0);\n }\n}\n\n/**\n * Decrypts and verifies a sealed message.\n *\n * Uses the current system time for the drift check.\n *\n * @param msgToOpen - The serialized COSE_Encrypt0 envelope, bound to the codec\n * of its payload\n * @param msgToAuth - The same additional authenticated data used during sealing\n * @param recipientKey - The xHPKE secret key to decrypt with\n * @param senderKey - The xDSA public key to verify the signature against\n * @param domain - Application domain for HPKE key derivation\n * @param maxDriftSecs - Maximum allowed timestamp difference in seconds, past\n * or future. A value of n accepts differences up to and including n, with\n * fractions rounded down. Undefined skips the check.\n * @returns The decoded payload\n * @throws If the envelope is malformed, does not decrypt or verify for these\n * keys, `msgToAuth` and `domain`, or its timestamp drifts too far\n * @throws If `maxDriftSecs` is negative or beyond 64 bits\n * @throws CodecError if the payload or `msgToAuth` does not fit its codec\n */\nexport async function open<T, A>(\n msgToOpen: Decodable<T>,\n msgToAuth: Encodable<A>,\n recipientKey: XhpkeSecretKey,\n senderKey: XdsaPublicKey,\n domain: Uint8Array,\n maxDriftSecs?: number,\n): Promise<T> {\n await ensureInit();\n const payload = cose_open(\n msgToOpen.bytes,\n serialize(msgToAuth),\n recipientKey._wasm,\n senderKey._wasm,\n domain,\n driftToBigInt(maxDriftSecs),\n );\n try {\n return msgToOpen.codec.decode(parse(payload));\n } finally {\n payload.fill(0);\n }\n}\n\n/**\n * Encrypts an already signed COSE_Sign1 envelope to a recipient.\n *\n * For most use cases, prefer {@link seal}, which signs and encrypts in one\n * step. Use this only when re-encrypting a message from {@link decrypt} to a\n * different recipient without access to the original signer's key. The\n * envelope is encrypted as given, without being checked.\n *\n * @param sign1 - The COSE_Sign1 envelope, such as one from {@link decrypt}\n * @param msgToAuth - The same additional authenticated data used during sealing\n * @param recipientKey - The xHPKE public key to encrypt to\n * @param domain - Application domain for HPKE key derivation\n * @returns The serialized COSE_Encrypt0 envelope\n * @throws CodecError if `msgToAuth` does not fit its codec\n */\nexport async function encrypt<A>(\n sign1: Uint8Array,\n msgToAuth: Encodable<A>,\n recipientKey: XhpkePublicKey,\n domain: Uint8Array,\n): Promise<Uint8Array> {\n await ensureInit();\n return cose_encrypt(sign1, serialize(msgToAuth), recipientKey._wasm, domain);\n}\n\n/**\n * Decrypts a sealed message without verifying the signature.\n *\n * This allows inspecting the signer before verification. Use {@link signer}\n * to extract the signer's fingerprint, then {@link verify} with the same\n * `msgToAuth` and `domain` to verify.\n *\n * @param msgToOpen - The serialized COSE_Encrypt0 envelope\n * @param msgToAuth - The same additional authenticated data used during sealing\n * @param recipientKey - The xHPKE secret key to decrypt with\n * @param domain - Application domain for HPKE key derivation\n * @returns The decrypted COSE_Sign1 envelope, not yet verified\n * @throws If the envelope is malformed or does not decrypt for this key,\n * `msgToAuth` and `domain`\n * @throws CodecError if `msgToAuth` does not fit its codec\n */\nexport async function decrypt<A>(\n msgToOpen: Uint8Array,\n msgToAuth: Encodable<A>,\n recipientKey: XhpkeSecretKey,\n domain: Uint8Array,\n): Promise<Uint8Array> {\n await ensureInit();\n return cose_decrypt(\n msgToOpen,\n serialize(msgToAuth),\n recipientKey._wasm,\n domain,\n );\n}\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * CBOR Web Tokens on top of COSE Sign1.\n *\n * https://datatracker.ietf.org/doc/html/rfc8392\n *\n * Tokens carry a set of claims encoded as a CBOR map. Standard CWT and EAT\n * claims are declared as fields under {@link claims}. A token's claim set is a\n * `cbor.map` of them, with custom claims as fields at other integer keys.\n *\n * {@link verify} checks the signature against the supplied key and, when\n * requested, the `nbf` and `exp` time bounds. Applications must establish\n * trust in that key, check issuer and audience claims, and apply their own\n * attestation policy. EAT claim relationships and proof of possession of a\n * `cnf` key are not automatically checked.\n *\n * @example\n * ```ts\n * import { cbor, cwt, xdsa } from \"@darkbio/crypto\";\n *\n * const DeviceCert = cbor.map({\n * sub: cwt.claims.subject,\n * exp: cwt.claims.expiration,\n * nbf: cwt.claims.notBefore,\n * cnf: cwt.claims.confirmXdsa,\n * ueid: cwt.claims.eat.ueid,\n * });\n * const issuer = await xdsa.SecretKey.generate();\n * const device = await xdsa.SecretKey.generate();\n * const domain = new TextEncoder().encode(\"device-cert\");\n * const now = 1_700_000_000n;\n *\n * // Example RAND UEID from the generated identity, type 0x01 and 16 identifier bytes.\n * // Provision it once and retain it for the device's lifetime, even if keys change.\n * const ueid = new Uint8Array([0x01, ...device.fingerprint().toBytes().slice(0, 16)]);\n *\n * const cert = { sub: \"ark-0001\", exp: now + 3600n, nbf: now, cnf: device.publicKey(), ueid };\n * const token = await cwt.issue(DeviceCert.value(cert), issuer, domain);\n *\n * const verified = await cwt.verify(DeviceCert.bytes(token), issuer.publicKey(), domain, now + 60n);\n * console.log(verified.sub, verified.cnf.equals(device.publicKey())); // ark-0001 true\n *\n * // Outside the validity window the token is rejected\n * await cwt.verify(DeviceCert.bytes(token), issuer.publicKey(), domain, now + 7200n).catch(() => {\n * console.log(\"expired\");\n * });\n * ```\n *\n * @module\n */\n\nimport {\n bool,\n bytes,\n codec,\n CodecError,\n enumeration,\n field,\n map,\n text,\n uint,\n type Codec,\n type Decodable,\n type Encodable,\n} from \"./cbor.js\";\nimport { parse, serialize } from \"./internal/cborg.js\";\nimport {\n cwt_issue,\n cwt_verify,\n cwt_signer,\n cwt_peek,\n} from \"./wasm/darkbio_crypto_wasm.js\";\nimport { ensureInit } from \"./internal/init.js\";\nimport { U64_MAX } from \"./internal/limits.js\";\nimport * as xdsa from \"./xdsa.js\";\nimport * as xhpke from \"./xhpke.js\";\n\n/** The debug port state, per RFC 9711 Section 4.2.9. */\nexport enum DebugState {\n /** Debug is currently enabled. */\n Enabled = 0,\n /** Debug is currently disabled. */\n Disabled = 1,\n /** Debug was disabled at boot and has not been enabled since. */\n DisabledSinceBoot = 2,\n /**\n * All debug has been disabled since boot. End users and developers cannot\n * re-enable it, but the manufacturer identified by `oemid` may do so. The\n * `oemid` claim must be present, and the application must enforce this.\n */\n DisabledPermanently = 3,\n /**\n * All debug facilities are permanently disabled, including manufacturer\n * facilities, and none can be re-enabled.\n */\n DisabledFullyPermanently = 4,\n}\n\n/** The token's intended purpose, per RFC 9711 Section 4.3.3. */\nexport enum IntendedUse {\n /** General-purpose attestation. */\n Generic = 1,\n /** Attestation for service registration. */\n Registration = 2,\n /** Attestation prior to key/config provisioning. */\n Provisioning = 3,\n /** Attestation for certificate signing requests. */\n CertIssuance = 4,\n /** Attestation accompanying a proof-of-possession. */\n ProofOfPossession = 5,\n}\n\n/**\n * An OEM identifier in one of the three forms RFC 9711 allows:\n *\n * - `pen`, an IANA private enterprise number\n * - `ieee`, a 3-byte IEEE organizationally unique identifier\n * - `random`, a 16-byte random identifier\n */\nexport type Oemid =\n { pen: bigint } | { ieee: Uint8Array } | { random: Uint8Array };\n\n/** Codec of an OEM identifier, an unsigned integer or 3 or 16 bytes. */\nexport const oemid: Codec<Oemid> = codec(\n (value) => {\n if (typeof value !== \"object\" || value === null) {\n throw new CodecError(\"not an OEM identifier\");\n }\n const forms = Object.keys(value);\n if (forms.length !== 1) {\n throw new CodecError(\"not an OEM identifier of exactly one form\");\n }\n const data = (value as Record<string, unknown>)[forms[0]];\n switch (forms[0]) {\n case \"pen\":\n return uint.encode(data as bigint);\n case \"ieee\":\n if (!(data instanceof Uint8Array) || data.length !== 3) {\n throw new CodecError(\"IEEE OEM identifier is not 3 bytes\");\n }\n return data;\n case \"random\":\n if (!(data instanceof Uint8Array) || data.length !== 16) {\n throw new CodecError(\"random OEM identifier is not 16 bytes\");\n }\n return data;\n default:\n throw new CodecError(\"not an OEM identifier\");\n }\n },\n (value) => {\n if (value instanceof Uint8Array) {\n if (value.length === 3) {\n return { ieee: value };\n }\n if (value.length === 16) {\n return { random: value };\n }\n throw new CodecError(\"OEM identifier is not 3 or 16 bytes\");\n }\n try {\n return { pen: uint.decode(value) };\n } catch {\n throw new CodecError(\"not an OEM identifier\");\n }\n },\n);\n\n/**\n * Codec of a version, the text wrapped in a one-element array as RFC 9711\n * has it. The optional scheme element is not supported.\n */\nexport const version: Codec<string> = codec(\n (value) => [text.encode(value)],\n (value) => {\n if (\n !Array.isArray(value) ||\n value.length !== 1 ||\n typeof value[0] !== \"string\"\n ) {\n throw new CodecError(\"not a version\");\n }\n return value[0];\n },\n);\n\n/**\n * Codec of a confirmation, a public key the token's subject holds (RFC 8747).\n * The key is wrapped in a COSE_Key of exactly the key type and the key bytes.\n *\n * A verified token authenticates this key binding, but does not prove that\n * the presenter holds the matching secret key. Applications must check that\n * separately using their protocol's proof-of-possession mechanism.\n *\n * @param algorithm - The COSE algorithm identifier of the key type\n * @param key - The codec of the key\n * @returns The codec\n */\nexport function confirmation<K>(algorithm: number, key: Codec<K>): Codec<K> {\n const coseKey = map({\n type: field(1, enumeration([algorithm])),\n key: field(-2, key),\n });\n const claim = map({ key: field(1, coseKey) });\n return codec(\n (value: K) => claim.encode({ key: { type: algorithm, key: value } }),\n (value) => claim.decode(value).key.key,\n );\n}\n\n/** The numeric members of an enum object. */\nfunction members<E extends number>(values: Record<string, E | string>): E[] {\n return Object.values(values).filter(\n (value): value is E => typeof value === \"number\",\n );\n}\n\n/**\n * The registered claims, RFC 8392 for the token ones and RFC 9711 for the\n * attestation ones under `eat`. A claim set is a `cbor.map` of these.\n */\nexport const claims = {\n /** The issuer, the principal that issued the token (key 1). */\n issuer: field(1, text),\n /** The subject, the principal the token is about (key 2). */\n subject: field(2, text),\n /** The audience, the recipients the token is meant for (key 3). */\n audience: field(3, text),\n /**\n * The expiration time in seconds since the Unix epoch. The token is\n * rejected at or after it (key 4).\n */\n expiration: field(4, uint),\n /**\n * The not-before time in seconds since the Unix epoch. The token is\n * rejected before it (key 5).\n */\n notBefore: field(5, uint),\n /** The issue time in seconds since the Unix epoch (key 6). */\n issuedAt: field(6, uint),\n /** The token identifier, opaque bytes unique to the token (key 7). */\n tokenId: field(7, bytes),\n /**\n * The confirmation, an xDSA public key the subject holds (key 8). A\n * verified token does not prove that the presenter holds the secret key.\n */\n confirmXdsa: field(8, confirmation(xdsa.ALGORITHM_ID, xdsa.publicKey)),\n /**\n * The confirmation, an xHPKE public key the subject holds (key 8). A\n * verified token does not prove that the presenter holds the secret key.\n */\n confirmXhpke: field(8, confirmation(xhpke.ALGORITHM_ID, xhpke.publicKey)),\n /**\n * The Entity Attestation Token claims of RFC 9711.\n *\n * These declare the claims and check their wire representations.\n * Applications must evaluate the claims against their attestation policy and\n * enforce RFC 9711's relationships between claims. For example, `hwModel`\n * and `oemBoot` require `oemid`, `hwVersion` requires `hwModel`, and\n * `swVersion` requires `swName`. {@link DebugState.DisabledPermanently} also\n * requires `oemid`. {@link verify} does not check these relationships.\n */\n eat: {\n /**\n * The universal entity identifier, a globally unique device identifier\n * such as a serial number or IMEI (key 256). Its first byte is the type\n * prefix of RFC 9711 Section 4.2.1.\n *\n * A RAND UEID uses prefix 0x01 followed by 16, 24 or 32 bytes of random\n * identifier data, provisioned once for the device. The bytes are carried\n * as supplied, so callers must check the prefix, length and identifier\n * policy.\n */\n ueid: field(256, bytes),\n /** The hardware manufacturer, in one of the {@link Oemid} forms (key 258). */\n oemid: field(258, oemid),\n /** The product or board model identifier, as the manufacturer defines it (key 259). */\n hwModel: field(259, bytes),\n /** The hardware revision identifier (key 260). */\n hwVersion: field(260, version),\n /** The number of seconds since the last boot (key 261). */\n uptime: field(261, uint),\n /** Whether every boot stage was OEM authorized, so secure boot passed (key 262). */\n oemBoot: field(262, bool),\n /** The state of the device's debug facilities at attestation time (key 263). */\n debugStatus: field(263, enumeration(members(DebugState))),\n /** The number of times the device has booted, never decreasing (key 267). */\n bootCount: field(267, uint),\n /** Random bytes drawn at boot, the same in every token of one boot cycle (key 268). */\n bootSeed: field(268, bytes),\n /** The name of the firmware or software running on the device (key 270). */\n swName: field(270, text),\n /** The software version identifier (key 271). */\n swVersion: field(271, version),\n /** The purpose the token was issued for (key 275). */\n intendedUse: field(275, enumeration(members(IntendedUse))),\n },\n};\n\n/** Converts the clock of a verification for the WASM boundary. */\nfunction nowToBigInt(now?: number | bigint): bigint | undefined {\n if (now === undefined) return undefined;\n if (\n typeof now !== \"bigint\" &&\n (typeof now !== \"number\" || !Number.isFinite(now))\n ) {\n throw new Error(\"now must be a non-negative Unix timestamp within 64 bits\");\n }\n const secs = typeof now === \"bigint\" ? now : BigInt(Math.floor(now));\n if (secs < 0n || secs > U64_MAX) {\n throw new Error(\"now must be a non-negative Unix timestamp within 64 bits\");\n }\n return secs;\n}\n\n/**\n * Issues a CWT by signing the claims with COSE Sign1.\n *\n * The claims must encode as a CBOR map, such as a `cbor.map` of the\n * {@link claims} fields. Uses the current system time as the COSE signature\n * timestamp.\n *\n * @param claims - The claims to include in the token\n * @param signer - The xDSA secret key to sign with\n * @param domain - Application domain for separating protocol purposes\n * @returns The serialized CWT\n * @throws CodecError if the claims do not fit their codec\n * @throws If the claims do not encode as a CBOR map\n */\nexport async function issue<C>(\n claims: Encodable<C>,\n signer: xdsa.SecretKey,\n domain: Uint8Array,\n): Promise<Uint8Array> {\n await ensureInit();\n return cwt_issue(serialize(claims), signer._wasm, domain);\n}\n\n/**\n * Verifies a CWT's COSE signature and temporal validity, then returns the\n * decoded claims.\n *\n * When `now` is given, the `nbf` claim (key 5) must be present and\n * `nbf <= now`. If the `exp` claim (key 4) is present too, `now < exp` must\n * also hold. When `now` is undefined, temporal validation is skipped entirely.\n *\n * The COSE signature timestamp is not checked, since temporal validity comes\n * from the CWT claims. The codec determines the accepted claim schema.\n * Successful verification does not establish issuer trust, enforce an\n * audience, evaluate attestation policy or EAT claim relationships, or prove\n * possession of a confirmation key. The application must perform those checks.\n *\n * @param token - The serialized CWT, bound to the codec of its claims\n * @param verifier - The xDSA public key to verify against\n * @param domain - Application domain for separating protocol purposes\n * @param now - Time of the check in seconds since the Unix epoch, with\n * fractions rounded down, or undefined to skip the time checks\n * @returns The decoded claims\n * @throws If the token is malformed, does not verify for this key and\n * `domain`, or fails a time check\n * @throws If `now` is negative or beyond 64 bits\n * @throws CodecError if the claims do not fit their codec\n */\nexport async function verify<C>(\n token: Decodable<C>,\n verifier: xdsa.PublicKey,\n domain: Uint8Array,\n now?: number | bigint,\n): Promise<C> {\n await ensureInit();\n const payload = cwt_verify(\n token.bytes,\n verifier._wasm,\n domain,\n nowToBigInt(now),\n );\n return token.codec.decode(parse(payload));\n}\n\n/**\n * Extracts the signer's fingerprint from a CWT without verifying the\n * signature.\n *\n * The fingerprint is unauthenticated. Use it to look up the appropriate\n * verification key before calling {@link verify}.\n *\n * @param token - The serialized CWT\n * @returns The signer's fingerprint\n * @throws If the token is malformed\n */\nexport async function signer(token: Uint8Array): Promise<xdsa.Fingerprint> {\n await ensureInit();\n return xdsa.Fingerprint._fromWasm(cwt_signer(token));\n}\n\n/**\n * Extracts and decodes the claims from a CWT without verifying the signature.\n *\n * The claims are unauthenticated and must not be trusted until verified with\n * {@link verify}. Use {@link signer} to extract the signer's fingerprint for\n * key lookup. The one intended use of this function is self-signed key\n * discovery.\n *\n * @param token - The serialized CWT, bound to the codec of its claims\n * @returns The decoded, unverified claims\n * @throws If the token is malformed\n * @throws CodecError if the claims do not fit their codec\n */\nexport async function peek<C>(token: Decodable<C>): Promise<C> {\n await ensureInit();\n return token.codec.decode(parse(cwt_peek(token.bytes)));\n}\n"],"x_google_ignoreList":[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22],"mappings":";;;;;;;;GAKa,IAAb,MAAa,EAAgB;CACzB,OAAO,OAAO,GAAK;EACf,IAAM,IAAM,OAAO,OAAO,EAAgB,SAAS;EAGnD,OAFA,EAAI,YAAY,GAChB,GAA4B,SAAS,GAAK,EAAI,WAAW,CAAG,GACrD;CACX;CACA,qBAAqB;EACjB,IAAM,IAAM,KAAK;EAGjB,OAFA,KAAK,YAAY,GACjB,GAA4B,WAAW,IAAI,GACpC;CACX;CACA,OAAO;EACH,IAAM,IAAM,KAAK,mBAAmB;EACpC,EAAK,2BAA2B,GAAK,CAAC;CAC1C;CAMA,OAAO,WAAW,GAAO;EACrB,IAAM,IAAO,EAAkB,GAAO,EAAK,iBAAiB,GACtD,IAAO,GACP,IAAM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AAK,GAAY,GAAQ,EAAU,CAAC,CAAC;EAExD,WAAW,EAAM,KAAK,CAAI;EAE1B,UAAU,EAAM,KAAK,EAAK;EAE1B,QAAQ,EAAM,KAAK,EAAI;EAEvB,WAAW,EAAM,KAAK,EAAO;EAE7B,aAAa,EAAM,KAAK,GAAY,GAAQ,EAAW,CAAC,CAAC;CAC3D;AACF;AAGA,SAAS,GAAY,GAA2C;CAC9D,IAAI,MAAQ,KAAA,GAAW;CACvB,IACE,OAAO,KAAQ,aACd,OAAO,KAAQ,YAAY,CAAC,OAAO,SAAS,CAAG,IAEhD,MAAU,MAAM,0DAA0D;CAE5E,IAAM,IAAO,OAAO,KAAQ,WAAW,IAAM,OAAO,KAAK,MAAM,CAAG,CAAC;CACnE,IAAI,IAAO,MAAM,IAAO,IACtB,MAAU,MAAM,0DAA0D;CAE5E,OAAO;AACT;AAgBA,eAAsB,GACpB,GACA,GACA,GACqB;CAErB,OADA,MAAM,EAAW,GACV,GAAU,EAAU,CAAM,GAAG,EAAO,OAAO,CAAM;AAC1D;AA2BA,eAAsB,GACpB,GACA,GACA,GACA,GACY;CACZ,MAAM,EAAW;CACjB,IAAM,IAAU,GACd,EAAM,OACN,EAAS,OACT,GACA,GAAY,CAAG,CACjB;CACA,OAAO,EAAM,MAAM,OAAO,GAAM,CAAO,CAAC;AAC1C;AAaA,eAAsB,GAAO,GAA8C;CAEzE,OADA,MAAM,EAAW,GACjB,EAAwB,UAAU,GAAW,CAAK,CAAC;AACrD;AAeA,eAAsB,GAAQ,GAAiC;CAE7D,OADA,MAAM,EAAW,GACV,EAAM,MAAM,OAAO,GAAM,GAAS,EAAM,KAAK,CAAC,CAAC;AACxD"}
1
+ {"version":3,"file":"index.js","names":["textEncoder","uint.readUint8","uint.readUint16","uint.readUint32","neg1b","pos1b","uint.readUint64","uint.uintBoundaries","toToken","uint.readUint8","uint.readUint16","uint.readUint32","uint.readUint64","toToken","uint.readUint8","uint.readUint16","uint.readUint32","uint.readUint64","toToken","uint.readUint8","uint.readUint16","uint.readUint32","uint.readUint64","uint.readUint8","uint.readUint16","uint.readUint32","uint.readUint64","uint.readUint8","uint.readUint16","uint.readUint32","uint.readUint64","uint.decodeUint8","uint.decodeUint16","uint.decodeUint32","uint.decodeUint64","negint.decodeNegint8","negint.decodeNegint16","negint.decodeNegint32","negint.decodeNegint64","bytes.decodeBytesCompact","bytes.decodeBytes8","bytes.decodeBytes16","bytes.decodeBytes32","bytes.decodeBytes64","string.decodeStringCompact","string.decodeString8","string.decodeString16","string.decodeString32","string.decodeString64","array.decodeArrayCompact","array.decodeArray8","array.decodeArray16","array.decodeArray32","array.decodeArray64","array.decodeArrayIndefinite","map.decodeMapCompact","map.decodeMap8","map.decodeMap16","map.decodeMap32","map.decodeMap64","map.decodeMapIndefinite","tag.decodeTagCompact","tag.decodeTag8","tag.decodeTag16","tag.decodeTag32","tag.decodeTag64","float.decodeUndefined","float.decodeFloat16","float.decodeFloat32","float.decodeFloat64","float.decodeBreak","decode"],"sources":["../src/wasm/darkbio_crypto_wasm.js","../src/internal/init.ts","../src/internal/limits.ts","../src/rand.ts","../src/hkdf.ts","../src/argon2.ts","../node_modules/cborg/lib/is.js","../node_modules/cborg/lib/token.js","../node_modules/cborg/lib/byte-utils.js","../node_modules/cborg/lib/bl.js","../node_modules/cborg/lib/common.js","../node_modules/cborg/lib/0uint.js","../node_modules/cborg/lib/1negint.js","../node_modules/cborg/lib/2bytes.js","../node_modules/cborg/lib/3string.js","../node_modules/cborg/lib/4array.js","../node_modules/cborg/lib/5map.js","../node_modules/cborg/lib/6tag.js","../node_modules/cborg/lib/7float.js","../node_modules/cborg/lib/jump.js","../node_modules/cborg/lib/encode.js","../node_modules/cborg/lib/decode.js","../node_modules/cborg/lib/tagged.js","../src/internal/cborg.ts","../src/cbor.ts","../src/internal/bytes.ts","../src/xdsa.ts","../src/xhpke.ts","../src/cose.ts","../src/cwt.ts"],"sourcesContent":["/* @ts-self-types=\"./darkbio_crypto_wasm.d.ts\" */\n\n/**\n * Opaque padding policy for a single sealing call.\n */\nexport class CosePadding {\n static __wrap(ptr) {\n const obj = Object.create(CosePadding.prototype);\n obj.__wbg_ptr = ptr;\n CosePaddingFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n CosePaddingFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_cosepadding_free(ptr, 0);\n }\n /**\n * Creates a policy that pads to the smallest size that fits. Sizes start at\n * `floor`, and each next one is the previous one plus `1/step` of it,\n * rounded up.\n * @param {number} floor\n * @param {number} step\n * @returns {CosePadding}\n */\n static buckets(floor, step) {\n const ret = wasm.cosepadding_buckets(floor, step);\n return CosePadding.__wrap(ret);\n }\n /**\n * Creates a policy that adds no padding.\n * @returns {CosePadding}\n */\n static none() {\n const ret = wasm.cosepadding_none();\n return CosePadding.__wrap(ret);\n }\n}\nif (Symbol.dispose) CosePadding.prototype[Symbol.dispose] = CosePadding.prototype.free;\n\n/**\n * Opaque xDSA fingerprint.\n */\nexport class XdsaFingerprint {\n static __wrap(ptr) {\n const obj = Object.create(XdsaFingerprint.prototype);\n obj.__wbg_ptr = ptr;\n XdsaFingerprintFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XdsaFingerprintFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xdsafingerprint_free(ptr, 0);\n }\n /**\n * Creates a fingerprint from a 32-byte array.\n * @param {Uint8Array} bytes\n * @returns {XdsaFingerprint}\n */\n static from_bytes(bytes) {\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xdsafingerprint_from_bytes(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XdsaFingerprint.__wrap(ret[0]);\n }\n /**\n * Serializes the fingerprint to a 32-byte array.\n * @returns {Uint8Array}\n */\n to_bytes() {\n const ret = wasm.xdsafingerprint_to_bytes(this.__wbg_ptr);\n var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v1;\n }\n}\nif (Symbol.dispose) XdsaFingerprint.prototype[Symbol.dispose] = XdsaFingerprint.prototype.free;\n\n/**\n * Opaque xDSA public key. Key material stays inside WASM memory.\n */\nexport class XdsaPublicKey {\n static __wrap(ptr) {\n const obj = Object.create(XdsaPublicKey.prototype);\n obj.__wbg_ptr = ptr;\n XdsaPublicKeyFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XdsaPublicKeyFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xdsapublickey_free(ptr, 0);\n }\n /**\n * Returns a 32-byte fingerprint uniquely identifying this key.\n * @returns {XdsaFingerprint}\n */\n fingerprint() {\n const ret = wasm.xdsapublickey_fingerprint(this.__wbg_ptr);\n return XdsaFingerprint.__wrap(ret);\n }\n /**\n * Creates a public key from a 1984-byte array.\n * @param {Uint8Array} bytes\n * @returns {XdsaPublicKey}\n */\n static from_bytes(bytes) {\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xdsapublickey_from_bytes(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XdsaPublicKey.__wrap(ret[0]);\n }\n /**\n * Parses a public key from PEM format.\n * @param {string} pem\n * @returns {XdsaPublicKey}\n */\n static from_pem(pem) {\n const ptr0 = passStringToWasm0(pem, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xdsapublickey_from_pem(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XdsaPublicKey.__wrap(ret[0]);\n }\n /**\n * Serializes the public key to a 1984-byte array.\n * @returns {Uint8Array}\n */\n to_bytes() {\n const ret = wasm.xdsapublickey_to_bytes(this.__wbg_ptr);\n var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v1;\n }\n /**\n * Serializes the public key to PEM format.\n * @returns {string}\n */\n to_pem() {\n let deferred1_0;\n let deferred1_1;\n try {\n const ret = wasm.xdsapublickey_to_pem(this.__wbg_ptr);\n deferred1_0 = ret[0];\n deferred1_1 = ret[1];\n return getStringFromWasm0(ret[0], ret[1]);\n } finally {\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n }\n /**\n * Verifies a signature on a message.\n * @param {Uint8Array} message\n * @param {XdsaSignature} signature\n * @returns {boolean}\n */\n verify(message, signature) {\n const ptr0 = passArray8ToWasm0(message, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n _assertClass(signature, XdsaSignature);\n const ret = wasm.xdsapublickey_verify(this.__wbg_ptr, ptr0, len0, signature.__wbg_ptr);\n return ret !== 0;\n }\n}\nif (Symbol.dispose) XdsaPublicKey.prototype[Symbol.dispose] = XdsaPublicKey.prototype.free;\n\n/**\n * Opaque xDSA secret key. Key material stays inside WASM memory.\n */\nexport class XdsaSecretKey {\n static __wrap(ptr) {\n const obj = Object.create(XdsaSecretKey.prototype);\n obj.__wbg_ptr = ptr;\n XdsaSecretKeyFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XdsaSecretKeyFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xdsasecretkey_free(ptr, 0);\n }\n /**\n * Returns a 32-byte fingerprint uniquely identifying this key.\n * @returns {XdsaFingerprint}\n */\n fingerprint() {\n const ret = wasm.xdsasecretkey_fingerprint(this.__wbg_ptr);\n return XdsaFingerprint.__wrap(ret);\n }\n /**\n * Creates a private key from a 64-byte seed, wiping the seed from WASM\n * memory before return.\n * @param {Uint8Array} bytes\n * @returns {XdsaSecretKey}\n */\n static from_bytes(bytes) {\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xdsasecretkey_from_bytes(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XdsaSecretKey.__wrap(ret[0]);\n }\n /**\n * Parses a secret key from PEM format, wiping the PEM from WASM memory\n * before return.\n * @param {string} pem\n * @returns {XdsaSecretKey}\n */\n static from_pem(pem) {\n const ptr0 = passStringToWasm0(pem, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xdsasecretkey_from_pem(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XdsaSecretKey.__wrap(ret[0]);\n }\n /**\n * Generates a new random private key.\n * @returns {XdsaSecretKey}\n */\n static generate() {\n const ret = wasm.xdsasecretkey_generate();\n return XdsaSecretKey.__wrap(ret);\n }\n /**\n * Returns the public key corresponding to this private key.\n * @returns {XdsaPublicKey}\n */\n public_key() {\n const ret = wasm.xdsasecretkey_public_key(this.__wbg_ptr);\n return XdsaPublicKey.__wrap(ret);\n }\n /**\n * Signs a message with this secret key.\n * @param {Uint8Array} message\n * @returns {XdsaSignature}\n */\n sign(message) {\n const ptr0 = passArray8ToWasm0(message, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xdsasecretkey_sign(this.__wbg_ptr, ptr0, len0);\n return XdsaSignature.__wrap(ret);\n }\n /**\n * Serializes the secret key to a 64-byte seed, copied straight into JS\n * memory so no unwiped copy is left in WASM memory.\n * @returns {Uint8Array}\n */\n to_bytes() {\n const ret = wasm.xdsasecretkey_to_bytes(this.__wbg_ptr);\n return ret;\n }\n /**\n * Serializes the secret key to PEM format, copied straight into a JS\n * string so no unwiped copy is left in WASM memory.\n * @returns {string}\n */\n to_pem() {\n const ret = wasm.xdsasecretkey_to_pem(this.__wbg_ptr);\n return ret;\n }\n}\nif (Symbol.dispose) XdsaSecretKey.prototype[Symbol.dispose] = XdsaSecretKey.prototype.free;\n\n/**\n * Opaque xDSA signature.\n */\nexport class XdsaSignature {\n static __wrap(ptr) {\n const obj = Object.create(XdsaSignature.prototype);\n obj.__wbg_ptr = ptr;\n XdsaSignatureFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XdsaSignatureFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xdsasignature_free(ptr, 0);\n }\n /**\n * Creates a signature from a 3373-byte array.\n * @param {Uint8Array} bytes\n * @returns {XdsaSignature}\n */\n static from_bytes(bytes) {\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xdsasignature_from_bytes(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XdsaSignature.__wrap(ret[0]);\n }\n /**\n * Serializes the signature to a 3373-byte array.\n * @returns {Uint8Array}\n */\n to_bytes() {\n const ret = wasm.xdsasignature_to_bytes(this.__wbg_ptr);\n var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v1;\n }\n}\nif (Symbol.dispose) XdsaSignature.prototype[Symbol.dispose] = XdsaSignature.prototype.free;\n\n/**\n * Opaque xHPKE fingerprint.\n */\nexport class XhpkeFingerprint {\n static __wrap(ptr) {\n const obj = Object.create(XhpkeFingerprint.prototype);\n obj.__wbg_ptr = ptr;\n XhpkeFingerprintFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XhpkeFingerprintFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xhpkefingerprint_free(ptr, 0);\n }\n /**\n * Creates a fingerprint from a 32-byte array.\n * @param {Uint8Array} bytes\n * @returns {XhpkeFingerprint}\n */\n static from_bytes(bytes) {\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkefingerprint_from_bytes(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XhpkeFingerprint.__wrap(ret[0]);\n }\n /**\n * Serializes the fingerprint to a 32-byte array.\n * @returns {Uint8Array}\n */\n to_bytes() {\n const ret = wasm.xhpkefingerprint_to_bytes(this.__wbg_ptr);\n var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v1;\n }\n}\nif (Symbol.dispose) XhpkeFingerprint.prototype[Symbol.dispose] = XhpkeFingerprint.prototype.free;\n\n/**\n * Opaque xHPKE public key. Key material stays inside WASM memory.\n */\nexport class XhpkePublicKey {\n static __wrap(ptr) {\n const obj = Object.create(XhpkePublicKey.prototype);\n obj.__wbg_ptr = ptr;\n XhpkePublicKeyFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XhpkePublicKeyFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xhpkepublickey_free(ptr, 0);\n }\n /**\n * Returns a 32-byte fingerprint uniquely identifying this key.\n * @returns {XhpkeFingerprint}\n */\n fingerprint() {\n const ret = wasm.xhpkepublickey_fingerprint(this.__wbg_ptr);\n return XhpkeFingerprint.__wrap(ret);\n }\n /**\n * Creates a public key from a 1216-byte array.\n * @param {Uint8Array} bytes\n * @returns {XhpkePublicKey}\n */\n static from_bytes(bytes) {\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkepublickey_from_bytes(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XhpkePublicKey.__wrap(ret[0]);\n }\n /**\n * Parses a public key from PEM format.\n * @param {string} pem\n * @returns {XhpkePublicKey}\n */\n static from_pem(pem) {\n const ptr0 = passStringToWasm0(pem, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkepublickey_from_pem(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XhpkePublicKey.__wrap(ret[0]);\n }\n /**\n * Creates an HPKE sender context for multi-message encryption.\n * @param {Uint8Array} domain\n * @returns {XhpkeSender}\n */\n new_sender(domain) {\n const ptr0 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkepublickey_new_sender(this.__wbg_ptr, ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XhpkeSender.__wrap(ret[0]);\n }\n /**\n * Encrypts a single-shot message to this public key, wiping the plaintext\n * from WASM memory before return.\n * Returns: encapsulated key (1120 bytes) || ciphertext\n * @param {Uint8Array} msg_to_seal\n * @param {Uint8Array} msg_to_auth\n * @param {Uint8Array} domain\n * @returns {Uint8Array}\n */\n seal(msg_to_seal, msg_to_auth, domain) {\n const ptr0 = passArray8ToWasm0(msg_to_seal, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkepublickey_seal(this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v4 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v4;\n }\n /**\n * Serializes the public key to a 1216-byte array.\n * @returns {Uint8Array}\n */\n to_bytes() {\n const ret = wasm.xhpkepublickey_to_bytes(this.__wbg_ptr);\n var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v1;\n }\n /**\n * Serializes the public key to PEM format.\n * @returns {string}\n */\n to_pem() {\n let deferred1_0;\n let deferred1_1;\n try {\n const ret = wasm.xhpkepublickey_to_pem(this.__wbg_ptr);\n deferred1_0 = ret[0];\n deferred1_1 = ret[1];\n return getStringFromWasm0(ret[0], ret[1]);\n } finally {\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n }\n}\nif (Symbol.dispose) XhpkePublicKey.prototype[Symbol.dispose] = XhpkePublicKey.prototype.free;\n\n/**\n * Stateful HPKE receiver for multi-message decryption.\n */\nexport class XhpkeReceiver {\n static __wrap(ptr) {\n const obj = Object.create(XhpkeReceiver.prototype);\n obj.__wbg_ptr = ptr;\n XhpkeReceiverFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XhpkeReceiverFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xhpkereceiver_free(ptr, 0);\n }\n /**\n * Decrypts a message using the next nonce in the sequence. The plaintext\n * is copied straight into JS memory so no unwiped copy is left in WASM\n * memory.\n * @param {Uint8Array} msg_to_open\n * @param {Uint8Array} msg_to_auth\n * @returns {Uint8Array}\n */\n open(msg_to_open, msg_to_auth) {\n const ptr0 = passArray8ToWasm0(msg_to_open, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkereceiver_open(this.__wbg_ptr, ptr0, len0, ptr1, len1);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n}\nif (Symbol.dispose) XhpkeReceiver.prototype[Symbol.dispose] = XhpkeReceiver.prototype.free;\n\n/**\n * Opaque xHPKE secret key. Key material stays inside WASM memory.\n */\nexport class XhpkeSecretKey {\n static __wrap(ptr) {\n const obj = Object.create(XhpkeSecretKey.prototype);\n obj.__wbg_ptr = ptr;\n XhpkeSecretKeyFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XhpkeSecretKeyFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xhpkesecretkey_free(ptr, 0);\n }\n /**\n * Returns a 32-byte fingerprint uniquely identifying this key.\n * @returns {XhpkeFingerprint}\n */\n fingerprint() {\n const ret = wasm.xhpkesecretkey_fingerprint(this.__wbg_ptr);\n return XhpkeFingerprint.__wrap(ret);\n }\n /**\n * Creates a private key from a 32-byte seed, wiping the seed from WASM\n * memory before return.\n * @param {Uint8Array} bytes\n * @returns {XhpkeSecretKey}\n */\n static from_bytes(bytes) {\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkesecretkey_from_bytes(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XhpkeSecretKey.__wrap(ret[0]);\n }\n /**\n * Parses a secret key from PEM format, wiping the PEM from WASM memory\n * before return.\n * @param {string} pem\n * @returns {XhpkeSecretKey}\n */\n static from_pem(pem) {\n const ptr0 = passStringToWasm0(pem, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkesecretkey_from_pem(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XhpkeSecretKey.__wrap(ret[0]);\n }\n /**\n * Generates a new random private key.\n * @returns {XhpkeSecretKey}\n */\n static generate() {\n const ret = wasm.xhpkesecretkey_generate();\n return XhpkeSecretKey.__wrap(ret);\n }\n /**\n * Creates an HPKE receiver context for multi-message decryption.\n * @param {Uint8Array} encap_key\n * @param {Uint8Array} domain\n * @returns {XhpkeReceiver}\n */\n new_receiver(encap_key, domain) {\n const ptr0 = passArray8ToWasm0(encap_key, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkesecretkey_new_receiver(this.__wbg_ptr, ptr0, len0, ptr1, len1);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XhpkeReceiver.__wrap(ret[0]);\n }\n /**\n * Decrypts a single-shot sealed message. The plaintext is copied straight\n * into JS memory so no unwiped copy is left in WASM memory.\n * Input: encapsulated key (1120 bytes) || ciphertext\n * @param {Uint8Array} sealed\n * @param {Uint8Array} msg_to_auth\n * @param {Uint8Array} domain\n * @returns {Uint8Array}\n */\n open(sealed, msg_to_auth, domain) {\n const ptr0 = passArray8ToWasm0(sealed, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkesecretkey_open(this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * Returns the public key corresponding to this private key.\n * @returns {XhpkePublicKey}\n */\n public_key() {\n const ret = wasm.xhpkesecretkey_public_key(this.__wbg_ptr);\n return XhpkePublicKey.__wrap(ret);\n }\n /**\n * Serializes the secret key to a 32-byte seed, copied straight into JS\n * memory so no unwiped copy is left in WASM memory.\n * @returns {Uint8Array}\n */\n to_bytes() {\n const ret = wasm.xhpkesecretkey_to_bytes(this.__wbg_ptr);\n return ret;\n }\n /**\n * Serializes the secret key to PEM format, copied straight into a JS\n * string so no unwiped copy is left in WASM memory.\n * @returns {string}\n */\n to_pem() {\n const ret = wasm.xhpkesecretkey_to_pem(this.__wbg_ptr);\n return ret;\n }\n}\nif (Symbol.dispose) XhpkeSecretKey.prototype[Symbol.dispose] = XhpkeSecretKey.prototype.free;\n\n/**\n * Stateful HPKE sender for multi-message encryption.\n */\nexport class XhpkeSender {\n static __wrap(ptr) {\n const obj = Object.create(XhpkeSender.prototype);\n obj.__wbg_ptr = ptr;\n XhpkeSenderFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n XhpkeSenderFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_xhpkesender_free(ptr, 0);\n }\n /**\n * Returns the 1120-byte encapsulated key.\n * @returns {Uint8Array}\n */\n encap_key() {\n const ret = wasm.xhpkesender_encap_key(this.__wbg_ptr);\n var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v1;\n }\n /**\n * Encrypts a message using the next nonce in the sequence, wiping the\n * plaintext from WASM memory before return.\n * @param {Uint8Array} msg_to_seal\n * @param {Uint8Array} msg_to_auth\n * @returns {Uint8Array}\n */\n seal(msg_to_seal, msg_to_auth) {\n const ptr0 = passArray8ToWasm0(msg_to_seal, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.xhpkesender_seal(this.__wbg_ptr, ptr0, len0, ptr1, len1);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v3;\n }\n}\nif (Symbol.dispose) XhpkeSender.prototype[Symbol.dispose] = XhpkeSender.prototype.free;\n\n/**\n * Derives a key from the password, salt, and cost parameters using Argon2id,\n * returning a byte array that can be used as a cryptographic key.\n *\n * RFC 9106 Section 4 recommends time=1, memory=2 GiB and threads=4, or, where\n * that much memory is not available, time=3, memory=64 MiB and threads=4. The\n * first profile needs exactly 2 GiB, which is past what this binding can\n * allocate. The threads parameter is Argon2's lane count, which changes the\n * derived key; it does not select how many threads compute it.\n *\n * All parameters are validated up front: the underlying implementation panics\n * on invalid inputs, which inside WASM would trap and poison the instance.\n * The password and the derived key are wiped from WASM memory before return.\n * @param {Uint8Array} password\n * @param {Uint8Array} salt\n * @param {number} time\n * @param {number} memory\n * @param {number} threads\n * @param {number} out_len\n * @returns {Uint8Array}\n */\nexport function argon2_key(password, salt, time, memory, threads, out_len) {\n const ptr0 = passArray8ToWasm0(password, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(salt, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.argon2_key(ptr0, len0, ptr1, len1, time, memory, threads, out_len);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * Verifies that data is valid CBOR using the restricted type system.\n * @param {Uint8Array} data\n */\nexport function cbor_verify(data) {\n const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.cbor_verify(ptr0, len0);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n}\n\n/**\n * Decrypts a sealed message without verifying the signature. The decrypted\n * COSE_Sign1 is copied straight into JS memory and the binding's own copy is\n * wiped; copies made inside crypto-rs are outside its reach.\n * @param {Uint8Array} msg_to_open\n * @param {Uint8Array} msg_to_auth\n * @param {XhpkeSecretKey} recipient\n * @param {Uint8Array} domain\n * @returns {Uint8Array}\n */\nexport function cose_decrypt(msg_to_open, msg_to_auth, recipient, domain) {\n const ptr0 = passArray8ToWasm0(msg_to_open, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n _assertClass(recipient, XhpkeSecretKey);\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.cose_decrypt(ptr0, len0, ptr1, len1, recipient.__wbg_ptr, ptr2, len2);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * Encrypts an already-signed COSE_Sign1 to a recipient. The binding's own copy\n * of the signed message is wiped before return.\n * @param {Uint8Array} sign1\n * @param {Uint8Array} msg_to_auth\n * @param {XhpkePublicKey} recipient\n * @param {Uint8Array} domain\n * @param {CosePadding} padding\n * @returns {Uint8Array}\n */\nexport function cose_encrypt(sign1, msg_to_auth, recipient, domain, padding) {\n const ptr0 = passArray8ToWasm0(sign1, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n _assertClass(recipient, XhpkePublicKey);\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n _assertClass(padding, CosePadding);\n const ret = wasm.cose_encrypt(ptr0, len0, ptr1, len1, recipient.__wbg_ptr, ptr2, len2, padding.__wbg_ptr);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v4 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v4;\n}\n\n/**\n * Decrypts and verifies a sealed message. The plaintext is copied straight\n * into JS memory and the binding's own copy is wiped; copies made inside\n * crypto-rs are outside its reach.\n * @param {Uint8Array} msg_to_open\n * @param {Uint8Array} msg_to_auth\n * @param {XhpkeSecretKey} recipient\n * @param {XdsaPublicKey} sender\n * @param {Uint8Array} domain\n * @param {bigint | null} [max_drift_secs]\n * @returns {Uint8Array}\n */\nexport function cose_open(msg_to_open, msg_to_auth, recipient, sender, domain, max_drift_secs) {\n const ptr0 = passArray8ToWasm0(msg_to_open, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n _assertClass(recipient, XhpkeSecretKey);\n _assertClass(sender, XdsaPublicKey);\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.cose_open(ptr0, len0, ptr1, len1, recipient.__wbg_ptr, sender.__wbg_ptr, ptr2, len2, !isLikeNone(max_drift_secs), isLikeNone(max_drift_secs) ? BigInt(0) : max_drift_secs);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * Extracts the embedded payload from a COSE_Sign1 without verifying. The\n * payload is copied straight into JS memory and the binding's own copies are\n * wiped; copies made inside crypto-rs are outside its reach.\n * @param {Uint8Array} signature\n * @returns {Uint8Array}\n */\nexport function cose_peek(signature) {\n const ptr0 = passArray8ToWasm0(signature, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.cose_peek(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * Extracts the recipient's fingerprint from a COSE_Encrypt0 without decrypting.\n * @param {Uint8Array} ciphertext\n * @returns {XhpkeFingerprint}\n */\nexport function cose_recipient(ciphertext) {\n const ptr0 = passArray8ToWasm0(ciphertext, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.cose_recipient(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XhpkeFingerprint.__wrap(ret[0]);\n}\n\n/**\n * Signs a message then encrypts it to a recipient (sign-then-encrypt). The\n * binding's own copy of the plaintext is wiped before return; copies made\n * inside crypto-rs are outside its reach.\n * @param {Uint8Array} msg_to_seal\n * @param {Uint8Array} msg_to_auth\n * @param {XdsaSecretKey} signer\n * @param {XhpkePublicKey} recipient\n * @param {Uint8Array} domain\n * @param {CosePadding} padding\n * @returns {Uint8Array}\n */\nexport function cose_seal(msg_to_seal, msg_to_auth, signer, recipient, domain, padding) {\n const ptr0 = passArray8ToWasm0(msg_to_seal, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n _assertClass(signer, XdsaSecretKey);\n _assertClass(recipient, XhpkePublicKey);\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n _assertClass(padding, CosePadding);\n const ret = wasm.cose_seal(ptr0, len0, ptr1, len1, signer.__wbg_ptr, recipient.__wbg_ptr, ptr2, len2, padding.__wbg_ptr);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v4 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v4;\n}\n\n/**\n * Creates a COSE_Sign1 signature with an embedded payload.\n * @param {Uint8Array} msg_to_embed\n * @param {Uint8Array} msg_to_auth\n * @param {XdsaSecretKey} signer\n * @param {Uint8Array} domain\n * @returns {Uint8Array}\n */\nexport function cose_sign(msg_to_embed, msg_to_auth, signer, domain) {\n const ptr0 = passArray8ToWasm0(msg_to_embed, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n _assertClass(signer, XdsaSecretKey);\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.cose_sign(ptr0, len0, ptr1, len1, signer.__wbg_ptr, ptr2, len2);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v4 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v4;\n}\n\n/**\n * Creates a COSE_Sign1 signature without an embedded payload (detached mode).\n * @param {Uint8Array} msg_to_auth\n * @param {XdsaSecretKey} signer\n * @param {Uint8Array} domain\n * @returns {Uint8Array}\n */\nexport function cose_sign_detached(msg_to_auth, signer, domain) {\n const ptr0 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n _assertClass(signer, XdsaSecretKey);\n const ptr1 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.cose_sign_detached(ptr0, len0, signer.__wbg_ptr, ptr1, len1);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v3;\n}\n\n/**\n * Extracts the signer's fingerprint from a COSE_Sign1 without verifying. The\n * binding's own copy of the signed message is wiped before return.\n * @param {Uint8Array} signature\n * @returns {XdsaFingerprint}\n */\nexport function cose_signer(signature) {\n const ptr0 = passArray8ToWasm0(signature, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.cose_signer(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XdsaFingerprint.__wrap(ret[0]);\n}\n\n/**\n * Verifies a COSE_Sign1 signature and returns the embedded payload.\n * @param {Uint8Array} msg_to_check\n * @param {Uint8Array} msg_to_auth\n * @param {XdsaPublicKey} verifier\n * @param {Uint8Array} domain\n * @param {bigint | null} [max_drift_secs]\n * @returns {Uint8Array}\n */\nexport function cose_verify(msg_to_check, msg_to_auth, verifier, domain, max_drift_secs) {\n const ptr0 = passArray8ToWasm0(msg_to_check, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n _assertClass(verifier, XdsaPublicKey);\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.cose_verify(ptr0, len0, ptr1, len1, verifier.__wbg_ptr, ptr2, len2, !isLikeNone(max_drift_secs), isLikeNone(max_drift_secs) ? BigInt(0) : max_drift_secs);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v4 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v4;\n}\n\n/**\n * Verifies a COSE_Sign1 signature with a detached payload.\n * @param {Uint8Array} msg_to_check\n * @param {Uint8Array} msg_to_auth\n * @param {XdsaPublicKey} verifier\n * @param {Uint8Array} domain\n * @param {bigint | null} [max_drift_secs]\n */\nexport function cose_verify_detached(msg_to_check, msg_to_auth, verifier, domain, max_drift_secs) {\n const ptr0 = passArray8ToWasm0(msg_to_check, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(msg_to_auth, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n _assertClass(verifier, XdsaPublicKey);\n const ptr2 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.cose_verify_detached(ptr0, len0, ptr1, len1, verifier.__wbg_ptr, ptr2, len2, !isLikeNone(max_drift_secs), isLikeNone(max_drift_secs) ? BigInt(0) : max_drift_secs);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n}\n\n/**\n * Issues a CWT by signing pre-encoded CBOR claims with COSE Sign1.\n * @param {Uint8Array} claims_cbor\n * @param {XdsaSecretKey} signer\n * @param {Uint8Array} domain\n * @returns {Uint8Array}\n */\nexport function cwt_issue(claims_cbor, signer, domain) {\n const ptr0 = passArray8ToWasm0(claims_cbor, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n _assertClass(signer, XdsaSecretKey);\n const ptr1 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.cwt_issue(ptr0, len0, signer.__wbg_ptr, ptr1, len1);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v3;\n}\n\n/**\n * Extracts and decodes claims from a CWT without verifying the signature.\n * @param {Uint8Array} token\n * @returns {Uint8Array}\n */\nexport function cwt_peek(token) {\n const ptr0 = passArray8ToWasm0(token, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.cwt_peek(ptr0, len0);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v2;\n}\n\n/**\n * Extracts the signer's fingerprint from a CWT without verifying.\n * @param {Uint8Array} token\n * @returns {XdsaFingerprint}\n */\nexport function cwt_signer(token) {\n const ptr0 = passArray8ToWasm0(token, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.cwt_signer(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return XdsaFingerprint.__wrap(ret[0]);\n}\n\n/**\n * Verifies a CWT's COSE signature and temporal validity, returning\n * the raw CBOR-encoded claims.\n * @param {Uint8Array} token\n * @param {XdsaPublicKey} verifier\n * @param {Uint8Array} domain\n * @param {bigint | null} [now]\n * @returns {Uint8Array}\n */\nexport function cwt_verify(token, verifier, domain, now) {\n const ptr0 = passArray8ToWasm0(token, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n _assertClass(verifier, XdsaPublicKey);\n const ptr1 = passArray8ToWasm0(domain, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.cwt_verify(ptr0, len0, verifier.__wbg_ptr, ptr1, len1, !isLikeNone(now), isLikeNone(now) ? BigInt(0) : now);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v3;\n}\n\n/**\n * Derives a key using the given pseudorandom key and optional context info,\n * skipping the extraction step.\n *\n * The pseudorandom key should have been generated by hkdf_extract, or be a\n * uniformly random or pseudorandom cryptographically strong key. See RFC 5869,\n * Section 3.3. Most common scenarios will want to use hkdf_key instead. The\n * pseudorandom key and the derived key are wiped from WASM memory before\n * return.\n * @param {Uint8Array} prk\n * @param {Uint8Array} info\n * @param {number} out_len\n * @returns {Uint8Array}\n */\nexport function hkdf_expand(prk, info, out_len) {\n const ptr0 = passArray8ToWasm0(prk, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(info, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.hkdf_expand(ptr0, len0, ptr1, len1, out_len);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * Generates a pseudorandom key for use with hkdf_expand from an input secret\n * and an optional independent salt.\n *\n * Only use this function if you need to reuse the extracted key with multiple\n * expand invocations and different context values. Most common scenarios,\n * including the generation of multiple keys, should use hkdf_key instead.\n * The secret and the key are wiped from WASM memory before return.\n * @param {Uint8Array} secret\n * @param {Uint8Array} salt\n * @returns {Uint8Array}\n */\nexport function hkdf_extract(secret, salt) {\n const ptr0 = passArray8ToWasm0(secret, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(salt, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.hkdf_extract(ptr0, len0, ptr1, len1);\n return ret;\n}\n\n/**\n * Derives a key from the secret, salt, and info using HKDF-SHA256, returning a\n * byte array that can be used as a cryptographic key.\n *\n * The out_len may not exceed the maximum output length for SHA-256 HKDF, which\n * is 255 * 32 = 8160 bytes. The secret and the key are wiped from WASM memory\n * before return.\n * @param {Uint8Array} secret\n * @param {Uint8Array} salt\n * @param {Uint8Array} info\n * @param {number} out_len\n * @returns {Uint8Array}\n */\nexport function hkdf_key(secret, salt, info, out_len) {\n const ptr0 = passArray8ToWasm0(secret, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(salt, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ptr2 = passArray8ToWasm0(info, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ret = wasm.hkdf_key(ptr0, len0, ptr1, len1, ptr2, len2, out_len);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * Generates a buffer of up to 64 MiB filled with randomness. The bytes are\n * wiped from WASM memory before return, since they often become key material.\n * @param {number} bytes\n * @returns {Uint8Array}\n */\nexport function rand_generate(bytes) {\n const ret = wasm.rand_generate(bytes);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * Size of a key fingerprint in bytes.\n * @returns {number}\n */\nexport function xdsa_fingerprint_size() {\n const ret = wasm.xdsa_fingerprint_size();\n return ret >>> 0;\n}\n\n/**\n * Size of the public key in bytes.\n * @returns {number}\n */\nexport function xdsa_public_key_size() {\n const ret = wasm.xdsa_public_key_size();\n return ret >>> 0;\n}\n\n/**\n * Size of the secret key in bytes.\n * @returns {number}\n */\nexport function xdsa_secret_key_size() {\n const ret = wasm.xdsa_secret_key_size();\n return ret >>> 0;\n}\n\n/**\n * Size of a composite signature in bytes.\n * @returns {number}\n */\nexport function xdsa_signature_size() {\n const ret = wasm.xdsa_signature_size();\n return ret >>> 0;\n}\n\n/**\n * Size of the encapsulated key in bytes.\n * @returns {number}\n */\nexport function xhpke_encap_key_size() {\n const ret = wasm.xhpke_encap_key_size();\n return ret >>> 0;\n}\n\n/**\n * Size of the fingerprint in bytes.\n * @returns {number}\n */\nexport function xhpke_fingerprint_size() {\n const ret = wasm.xhpke_fingerprint_size();\n return ret >>> 0;\n}\n\n/**\n * Size of the public key in bytes.\n * @returns {number}\n */\nexport function xhpke_public_key_size() {\n const ret = wasm.xhpke_public_key_size();\n return ret >>> 0;\n}\n\n/**\n * Size of the secret key seed in bytes.\n * @returns {number}\n */\nexport function xhpke_secret_key_size() {\n const ret = wasm.xhpke_secret_key_size();\n return ret >>> 0;\n}\nfunction __wbg_get_imports() {\n const import0 = {\n __proto__: null,\n __wbg_Error_30c8987f7c2ed4e2: function(arg0, arg1) {\n const ret = Error(getStringFromWasm0(arg0, arg1));\n return ret;\n },\n __wbg___wbindgen_throw_41e9ee4f547fc59a: function(arg0, arg1) {\n throw new Error(getStringFromWasm0(arg0, arg1));\n },\n __wbg_getRandomValues_436a51d0629d84e1: function() { return handleError(function (arg0, arg1) {\n globalThis.crypto.getRandomValues(getArrayU8FromWasm0(arg0, arg1));\n }, arguments); },\n __wbg_new_from_slice_9a868026ffa4208a: function(arg0, arg1) {\n const ret = new Uint8Array(getArrayU8FromWasm0(arg0, arg1));\n return ret;\n },\n __wbg_now_aa4ccb83129e9e55: function() {\n const ret = Date.now();\n return ret;\n },\n __wbindgen_generic_0000000000000001: function(arg0, arg1) {\n // Cast intrinsic for `Ref(String) -> Externref`.\n const ret = getStringFromWasm0(arg0, arg1);\n return ret;\n },\n __wbindgen_init_externref_table: function() {\n const table = wasm.__wbindgen_externrefs;\n const offset = table.grow(4);\n table.set(0, undefined);\n table.set(offset + 0, undefined);\n table.set(offset + 1, null);\n table.set(offset + 2, true);\n table.set(offset + 3, false);\n },\n };\n return {\n __proto__: null,\n \"./darkbio_crypto_wasm_bg.js\": import0,\n };\n}\n\nconst CosePaddingFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_cosepadding_free(ptr, 1));\nconst XdsaFingerprintFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xdsafingerprint_free(ptr, 1));\nconst XdsaPublicKeyFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xdsapublickey_free(ptr, 1));\nconst XdsaSecretKeyFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xdsasecretkey_free(ptr, 1));\nconst XdsaSignatureFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xdsasignature_free(ptr, 1));\nconst XhpkeFingerprintFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xhpkefingerprint_free(ptr, 1));\nconst XhpkePublicKeyFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xhpkepublickey_free(ptr, 1));\nconst XhpkeReceiverFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xhpkereceiver_free(ptr, 1));\nconst XhpkeSecretKeyFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xhpkesecretkey_free(ptr, 1));\nconst XhpkeSenderFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_xhpkesender_free(ptr, 1));\n\nfunction addToExternrefTable0(obj) {\n const idx = wasm.__externref_table_alloc();\n wasm.__wbindgen_externrefs.set(idx, obj);\n return idx;\n}\n\nfunction _assertClass(instance, klass) {\n if (!(instance instanceof klass)) {\n throw new Error(`expected instance of ${klass.name}`);\n }\n}\n\nfunction getArrayU8FromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);\n}\n\nfunction getStringFromWasm0(ptr, len) {\n return decodeText(ptr >>> 0, len);\n}\n\nlet cachedUint8ArrayMemory0 = null;\nfunction getUint8ArrayMemory0() {\n if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {\n cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);\n }\n return cachedUint8ArrayMemory0;\n}\n\nfunction handleError(f, args) {\n try {\n return f.apply(this, args);\n } catch (e) {\n const idx = addToExternrefTable0(e);\n wasm.__wbindgen_exn_store(idx);\n }\n}\n\nfunction isLikeNone(x) {\n return x === undefined || x === null;\n}\n\nfunction passArray8ToWasm0(arg, malloc) {\n const ptr = malloc(arg.length * 1, 1) >>> 0;\n getUint8ArrayMemory0().set(arg, ptr / 1);\n WASM_VECTOR_LEN = arg.length;\n return ptr;\n}\n\nfunction passStringToWasm0(arg, malloc, realloc) {\n if (realloc === undefined) {\n const buf = cachedTextEncoder.encode(arg);\n const ptr = malloc(buf.length, 1) >>> 0;\n getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);\n WASM_VECTOR_LEN = buf.length;\n return ptr;\n }\n\n let len = arg.length;\n let ptr = malloc(len, 1) >>> 0;\n\n const mem = getUint8ArrayMemory0();\n\n let offset = 0;\n\n for (; offset < len; offset++) {\n const code = arg.charCodeAt(offset);\n if (code > 0x7F) break;\n mem[ptr + offset] = code;\n }\n if (offset !== len) {\n if (offset !== 0) {\n arg = arg.slice(offset);\n }\n ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;\n const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);\n const ret = cachedTextEncoder.encodeInto(arg, view);\n\n offset += ret.written;\n ptr = realloc(ptr, len, offset, 1) >>> 0;\n }\n\n WASM_VECTOR_LEN = offset;\n return ptr;\n}\n\nfunction takeFromExternrefTable0(idx) {\n const value = wasm.__wbindgen_externrefs.get(idx);\n wasm.__externref_table_dealloc(idx);\n return value;\n}\n\nlet cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\ncachedTextDecoder.decode();\nconst MAX_SAFARI_DECODE_BYTES = 2146435072;\nlet numBytesDecoded = 0;\nfunction decodeText(ptr, len) {\n numBytesDecoded += len;\n if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {\n cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\n cachedTextDecoder.decode();\n numBytesDecoded = len;\n }\n return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));\n}\n\nconst cachedTextEncoder = new TextEncoder();\n\nif (!('encodeInto' in cachedTextEncoder)) {\n cachedTextEncoder.encodeInto = function (arg, view) {\n const buf = cachedTextEncoder.encode(arg);\n view.set(buf);\n return {\n read: arg.length,\n written: buf.length\n };\n };\n}\n\nlet WASM_VECTOR_LEN = 0;\n\nlet wasmModule, wasmInstance, wasm;\nfunction __wbg_finalize_init(instance, module) {\n wasmInstance = instance;\n wasm = instance.exports;\n wasmModule = module;\n cachedUint8ArrayMemory0 = null;\n wasm.__wbindgen_start();\n return wasm;\n}\n\nasync function __wbg_load(module, imports) {\n if (typeof Response === 'function' && module instanceof Response) {\n if (!module.ok) {\n throw new Error(`failed to fetch Wasm: ${module.status} ${module.statusText} fetching '${module.url}'`);\n }\n\n if (typeof WebAssembly.instantiateStreaming === 'function') {\n try {\n return await WebAssembly.instantiateStreaming(module, imports);\n } catch (e) {\n const validResponse = expectedResponseType(module.type);\n\n if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {\n console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n } else { throw e; }\n }\n }\n\n const bytes = await module.arrayBuffer();\n return await WebAssembly.instantiate(bytes, imports);\n } else {\n const instance = await WebAssembly.instantiate(module, imports);\n\n if (instance instanceof WebAssembly.Instance) {\n return { instance, module };\n } else {\n return instance;\n }\n }\n\n function expectedResponseType(type) {\n switch (type) {\n case 'basic': case 'cors': case 'default': return true;\n }\n return false;\n }\n}\n\nfunction initSync(module) {\n if (wasm !== undefined) return wasm;\n\n\n if (module !== undefined) {\n if (Object.getPrototypeOf(module) === Object.prototype) {\n ({module} = module)\n } else {\n console.warn('using deprecated parameters for `initSync()`; pass a single object instead')\n }\n }\n\n const imports = __wbg_get_imports();\n if (!(module instanceof WebAssembly.Module)) {\n module = new WebAssembly.Module(module);\n }\n const instance = new WebAssembly.Instance(module, imports);\n return __wbg_finalize_init(instance, module);\n}\n\nasync function __wbg_init(module_or_path) {\n if (wasm !== undefined) return wasm;\n\n\n if (module_or_path !== undefined) {\n if (Object.getPrototypeOf(module_or_path) === Object.prototype) {\n ({module_or_path} = module_or_path)\n } else {\n console.warn('using deprecated parameters for the initialization function; pass a single object instead')\n }\n }\n\n if (module_or_path === undefined) {\n module_or_path = new URL('darkbio_crypto_wasm_bg.wasm', import.meta.url);\n }\n const imports = __wbg_get_imports();\n\n if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {\n module_or_path = fetch(module_or_path);\n }\n\n const { instance, module } = await __wbg_load(await module_or_path, imports);\n\n return __wbg_finalize_init(instance, module);\n}\n\nexport { initSync, __wbg_init as default };\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\nimport init from \"../wasm/darkbio_crypto_wasm.js\";\n\nlet initPromise: Promise<unknown> | undefined;\nlet initComplete = false;\n\n/**\n * Ensures the WASM module is instantiated exactly once. Concurrent callers\n * share the single in-flight initialization; a failed attempt is cleared so\n * the next call can retry.\n *\n * @internal\n */\nexport function ensureInit(): Promise<unknown> {\n if (initPromise === undefined) {\n initPromise = init()\n .then((module) => {\n initComplete = true;\n return module;\n })\n .catch((err: unknown) => {\n initPromise = undefined;\n throw err;\n });\n }\n return initPromise;\n}\n\n/**\n * Fails unless the WASM module is instantiated, for the synchronous paths a\n * codec takes when it constructs a key. Every async entry point of the\n * package initialises the module, so a codec run after any of them is fine.\n *\n * @internal\n */\nexport function requireInit(): void {\n if (!initComplete) {\n throw new Error(\n \"crypto module not initialised, await any entry point first\",\n );\n }\n}\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/** Largest 32 bit unsigned integer, the size type of the WASM module. */\nexport const U32_MAX = 0xffffffff;\n\n/** Largest 64 bit unsigned integer. */\nexport const U64_MAX = (1n << 64n) - 1n;\n\n/**\n * Checks a count or size fits the 32 bit unsigned integers of the WASM\n * module, which would otherwise wrap it.\n *\n * @internal\n */\nexport function u32(value: number, name: string): number {\n if (!Number.isInteger(value) || value < 0 || value > U32_MAX) {\n throw new Error(`${name} must be a non-negative 32 bit integer`);\n }\n return value;\n}\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * Random bytes from the runtime's secure random source.\n *\n * @example\n * ```ts\n * import { rand } from \"@darkbio/crypto\";\n *\n * const nonce = await rand.generate(32);\n * console.log(nonce.length); // 32\n * ```\n *\n * @module\n */\n\nimport { rand_generate } from \"./wasm/darkbio_crypto_wasm.js\";\nimport { ensureInit } from \"./internal/init.js\";\nimport { u32 } from \"./internal/limits.js\";\n\n/**\n * Generates cryptographically secure random bytes.\n *\n * @param bytes - Number of random bytes to generate, at most 64 MiB\n * @returns A new array filled with random bytes\n * @throws If `bytes` is not a whole number between 0 and 64 MiB\n */\nexport async function generate(bytes: number): Promise<Uint8Array> {\n await ensureInit();\n return rand_generate(u32(bytes, \"bytes\"));\n}\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * HKDF-SHA256 key derivation.\n *\n * https://datatracker.ietf.org/doc/html/rfc5869\n *\n * Stretches a secret that is already high entropy, a shared secret or a file\n * key, into one or more keys bound to a context string. It is not a password\n * hash; the `argon2` module is the one for that.\n *\n * @example\n * ```ts\n * import { hkdf } from \"@darkbio/crypto\";\n *\n * const secret = new Uint8Array(32).fill(42);\n * const salt = new Uint8Array();\n * const text = new TextEncoder();\n *\n * // Distinct contexts derive independent keys from the same secret\n * const encryption = await hkdf.key(secret, salt, text.encode(\"example encryption key\"), 32);\n * const authentication = await hkdf.key(secret, salt, text.encode(\"example authentication key\"), 32);\n * ```\n *\n * @module\n */\n\nimport {\n hkdf_key,\n hkdf_extract,\n hkdf_expand,\n} from \"./wasm/darkbio_crypto_wasm.js\";\nimport { ensureInit } from \"./internal/init.js\";\nimport { u32 } from \"./internal/limits.js\";\n\n/**\n * Derives a key from the secret, salt and info using HKDF-SHA256.\n *\n * @param secret - The input keying material, already high entropy\n * @param salt - Optional salt, empty for none\n * @param info - Context the key is bound to, empty for none\n * @param outLen - Length of the key in bytes, at most 8160\n * @returns The derived key\n * @throws If `outLen` is not a whole number between 0 and 8160\n */\nexport async function key(\n secret: Uint8Array,\n salt: Uint8Array,\n info: Uint8Array,\n outLen: number,\n): Promise<Uint8Array> {\n await ensureInit();\n return hkdf_key(secret, salt, info, u32(outLen, \"outLen\"));\n}\n\n/**\n * Extracts a 32-byte pseudorandom key from the secret and salt, for use with\n * {@link expand}.\n *\n * Only use this to reuse the extracted key with multiple {@link expand} calls\n * and different contexts. Most scenarios, including the derivation of multiple\n * keys, should use {@link key} instead.\n *\n * @param secret - The input keying material, already high entropy\n * @param salt - Optional salt, empty for none\n * @returns A 32-byte pseudorandom key\n */\nexport async function extract(\n secret: Uint8Array,\n salt: Uint8Array,\n): Promise<Uint8Array> {\n await ensureInit();\n return hkdf_extract(secret, salt);\n}\n\n/**\n * Derives a key from a pseudorandom key and context info, skipping the\n * extraction step.\n *\n * The pseudorandom key should come from {@link extract}, or be a uniformly\n * random or pseudorandom cryptographically strong key. See RFC 5869 Section\n * 3.3. Most scenarios should use {@link key} instead.\n *\n * @param prk - A 32-byte pseudorandom key\n * @param info - Context the key is bound to, empty for none\n * @param outLen - Length of the key in bytes, at most 8160\n * @returns The derived key\n * @throws If `prk` is not 32 bytes, or `outLen` is not a whole number between\n * 0 and 8160\n */\nexport async function expand(\n prk: Uint8Array,\n info: Uint8Array,\n outLen: number,\n): Promise<Uint8Array> {\n await ensureInit();\n return hkdf_expand(prk, info, u32(outLen, \"outLen\"));\n}\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * Argon2id key derivation.\n *\n * https://datatracker.ietf.org/doc/html/rfc9106\n *\n * Turns a password and a salt into key material, made deliberately slow and\n * memory hungry so guessing passwords is expensive. For stretching a secret\n * that is already random, see the `hkdf` module instead.\n *\n * @module\n */\n\nimport { argon2_key } from \"./wasm/darkbio_crypto_wasm.js\";\nimport { ensureInit } from \"./internal/init.js\";\nimport { u32 } from \"./internal/limits.js\";\n\n/**\n * Derives a key from the password, salt and cost parameters using Argon2id.\n *\n * RFC 9106 Section 4 recommends `time = 1`, `memory = 2 * 1024 * 1024`\n * (2 GiB) and `threads = 4`. Its second recommendation uses `time = 3`,\n * `memory = 64 * 1024` (64 MiB) and `threads = 4`. Both use a random 16-byte\n * salt and a 32-byte output. A single WASM allocation stays below 2 GiB, so\n * only the second profile fits within the memory limit below.\n *\n * `time` is the number of passes and `memory` is the total working memory in\n * KiB. `threads` is Argon2's lane count, an algorithm parameter that changes\n * the derived key. It does not select how many threads compute the key. Store\n * the salt and all cost parameters so the same key can be reproduced on other\n * devices.\n *\n * The parameters must stay within these limits:\n *\n * - `time` must be at least 1.\n * - `threads` must be at least 1.\n * - `memory` must be at least `8 * threads` KiB and at most 2097151 KiB, one\n * KiB short of 2 GiB.\n * - `salt` must be at least 8 bytes.\n * - `outLen` must be at least 4 bytes and at most 2147483647 bytes.\n *\n * @example\n * ```ts\n * import { argon2 } from \"@darkbio/crypto\";\n *\n * // Example salt only; generate and store a fresh random 16-byte salt in real code\n * const salt = new TextEncoder().encode(\"example salt1234\");\n * const password = new TextEncoder().encode(\"password\");\n *\n * // RFC 9106's recommended profile for memory-constrained environments\n * const key = await argon2.key(password, salt, 3, 64 * 1024, 4, 32);\n * console.log(key.length); // 32\n * ```\n *\n * @param password - The password to derive from\n * @param salt - A random salt, at least 8 bytes and 16 bytes recommended\n * @param time - Number of passes over the memory\n * @param memory - Size of the working memory in KiB\n * @param threads - Argon2's lane count\n * @param outLen - Length of the key in bytes\n * @returns The derived key\n * @throws If a parameter is outside the limits above, or the working memory\n * cannot be allocated\n */\nexport async function key(\n password: Uint8Array,\n salt: Uint8Array,\n time: number,\n memory: number,\n threads: number,\n outLen: number,\n): Promise<Uint8Array> {\n await ensureInit();\n return argon2_key(\n password,\n salt,\n u32(time, \"time\"),\n u32(memory, \"memory\"),\n u32(threads, \"threads\"),\n u32(outLen, \"outLen\"),\n );\n}\n","// This is an unfortunate replacement for @sindresorhus/is that we need to\n// re-implement for performance purposes. In particular the is.observable()\n// check is expensive, and unnecessary for our purposes. The values returned\n// are compatible with @sindresorhus/is, however.\n\n// Types that reach getObjectType() - excludes types with fast-paths above:\n// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)\nconst objectTypeNames = [\n 'Object', // for Object.create(null) and other non-plain objects\n 'RegExp',\n 'Date',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'ArrayBuffer',\n 'SharedArrayBuffer',\n 'DataView',\n 'Promise',\n 'URL',\n 'HTMLElement',\n 'Int8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array',\n 'Tagged'\n]\n\n/**\n * @param {any} value\n * @returns {string}\n */\nexport function is (value) {\n if (value === null) {\n return 'null'\n }\n if (value === undefined) {\n return 'undefined'\n }\n if (value === true || value === false) {\n return 'boolean'\n }\n const typeOf = typeof value\n if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {\n return typeOf\n }\n if (typeOf === 'function') {\n return 'Function'\n }\n if (Array.isArray(value)) {\n return 'Array'\n }\n // Also catches Node.js Buffer which extends Uint8Array\n if (value instanceof Uint8Array) {\n return 'Uint8Array'\n }\n // Fast path for plain objects (most common case after primitives/arrays/bytes)\n if (value.constructor === Object) {\n return 'Object'\n }\n const objectType = getObjectType(value)\n if (objectType) {\n return objectType\n }\n return 'Object'\n}\n\n/**\n * @param {any} value\n * @returns {string|undefined}\n */\nfunction getObjectType (value) {\n const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)\n if (objectTypeNames.includes(objectTypeName)) {\n return objectTypeName\n }\n return undefined\n}\n","class Type {\n /**\n * @param {number} major\n * @param {string} name\n * @param {boolean} terminal\n */\n constructor (major, name, terminal) {\n this.major = major\n this.majorEncoded = major << 5\n this.name = name\n this.terminal = terminal\n }\n\n toString () {\n return `Type[${this.major}].${this.name}`\n }\n\n /**\n * @param {Type} typ\n * @returns {number}\n */\n compare (typ) {\n return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0\n }\n\n /**\n * Check equality between two Type instances. Safe to use across different\n * copies of the Type class (e.g., when bundlers duplicate the module).\n * (major, name) uniquely identifies a Type; terminal is implied by these.\n * @param {Type} a\n * @param {Type} b\n * @returns {boolean}\n */\n static equals (a, b) {\n return a === b || (a.major === b.major && a.name === b.name)\n }\n}\n\n// convert to static fields when better supported\nType.uint = new Type(0, 'uint', true)\nType.negint = new Type(1, 'negint', true)\nType.bytes = new Type(2, 'bytes', true)\nType.string = new Type(3, 'string', true)\nType.array = new Type(4, 'array', false)\nType.map = new Type(5, 'map', false)\nType.tag = new Type(6, 'tag', false) // terminal?\nType.float = new Type(7, 'float', true)\nType.false = new Type(7, 'false', true)\nType.true = new Type(7, 'true', true)\nType.null = new Type(7, 'null', true)\nType.undefined = new Type(7, 'undefined', true)\nType.break = new Type(7, 'break', true)\n// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)\n\nclass Token {\n /**\n * @param {Type} type\n * @param {any} [value]\n * @param {number} [encodedLength]\n */\n constructor (type, value, encodedLength) {\n this.type = type\n this.value = value\n this.encodedLength = encodedLength\n /** @type {Uint8Array|undefined} */\n this.encodedBytes = undefined\n /** @type {Uint8Array|undefined} */\n this.byteValue = undefined\n }\n\n toString () {\n return `Token[${this.type}].${this.value}`\n }\n}\n\nexport { Type, Token }\n","// Use Uint8Array directly in the browser, use Buffer in Node.js but don't\n// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill\n\n// @ts-ignore\nexport const useBuffer = globalThis.process &&\n // @ts-ignore\n !globalThis.process.browser &&\n // @ts-ignore\n globalThis.Buffer &&\n // @ts-ignore\n typeof globalThis.Buffer.isBuffer === 'function'\n\nconst textEncoder = new TextEncoder()\n\n/**\n * @typedef {import('../interface.js').ByteView} ByteView\n * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView\n */\n\n/**\n * @param {Uint8Array} buf\n * @returns {boolean}\n */\nfunction isBuffer (buf) {\n // @ts-ignore\n return useBuffer && globalThis.Buffer.isBuffer(buf)\n}\n\n/**\n * @param {ByteView|number[]} buf\n * @returns {ByteView}\n */\nexport function asU8A (buf) {\n if (!(buf instanceof Uint8Array)) {\n return Uint8Array.from(buf)\n }\n return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf\n}\n\n// Threshold for manual UTF-8 encoding vs native methods.\n// Node.js Buffer.from: crossover ~24 chars\n// Browser TextEncoder: crossover ~200 chars\nconst FROM_STRING_THRESHOLD_BUFFER = 24\nconst FROM_STRING_THRESHOLD_TEXTENCODER = 200\n\nexport const fromString = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length >= FROM_STRING_THRESHOLD_BUFFER\n ? // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(string)\n : utf8ToBytes(string)\n }\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)\n }\n\n/**\n * Buffer variant not fast enough for what we need\n * @param {number[]} arr\n * @returns {AllocatedByteView}\n */\nexport const fromArray = (arr) => {\n return Uint8Array.from(arr)\n}\n\nexport const slice = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n // Buffer.slice() returns a view, not a copy, so we need special handling\n (bytes, start, end) => {\n if (isBuffer(bytes)) {\n return new Uint8Array(bytes.subarray(start, end))\n }\n return bytes.slice(start, end)\n }\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return bytes.slice(start, end)\n }\n\nexport const concat = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {ByteView[]} chunks\n * @param {number} length\n * @returns {AllocatedByteView}\n */\n (chunks, length) => {\n // might get a stray plain Array here\n chunks = chunks.map((c) => c instanceof Uint8Array\n ? c\n : // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(c))\n // @ts-ignore\n return /** @type {AllocatedByteView} */ (asU8A(globalThis.Buffer.concat(chunks, length)))\n }\n : // eslint-disable-line operator-linebreak\n /**\n * @param {ByteView[]} chunks\n * @param {number} length\n * @returns {AllocatedByteView}\n */\n (chunks, length) => {\n const out = new Uint8Array(length)\n let off = 0\n for (let b of chunks) {\n if (off + b.length > out.length) {\n // final chunk that's bigger than we need\n b = b.subarray(0, out.length - off)\n }\n out.set(b, off)\n off += b.length\n }\n return out\n }\n\nexport const alloc = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {AllocatedByteView}\n */\n (size) => {\n // we always write over the contents we expose so this should be safe\n // @ts-ignore\n return globalThis.Buffer.allocUnsafe(size)\n }\n : // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {AllocatedByteView}\n */\n (size) => {\n return new Uint8Array(size)\n }\n\nexport const toHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore\n return globalThis.Buffer.from(toBytes(d)).toString('hex')\n }\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore not smart enough to figure this out\n return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')\n }\n\nexport const fromHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string|ByteView} hex\n * @returns {ByteView}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n // @ts-ignore\n return globalThis.Buffer.from(hex, 'hex')\n }\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string|ByteView} hex\n * @returns {ByteView}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n if (!hex.length) {\n return new Uint8Array(0)\n }\n return new Uint8Array(hex.split('')\n .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')\n .filter(Boolean)\n .map((/** @type {string} */ e) => parseInt(e, 16)))\n }\n\n/**\n * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj\n * @returns {Uint8Array}\n */\nfunction toBytes (obj) {\n if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {\n return obj\n }\n if (obj instanceof ArrayBuffer) {\n return new Uint8Array(obj)\n }\n if (ArrayBuffer.isView(obj)) {\n return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compare (b1, b2) {\n if (isBuffer(b1) && isBuffer(b2)) {\n // probably not possible to get here in the current API\n // @ts-ignore Buffer\n return b1.compare(b2)\n }\n for (let i = 0; i < b1.length; i++) {\n if (b1[i] === b2[i]) {\n continue\n }\n return b1[i] < b2[i] ? -1 : 1\n }\n return 0\n}\n\n// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143\n// Licensed Apache-2.0.\n\n/**\n * @param {string} str\n * @returns {number[]}\n */\nfunction utf8ToBytes (str) {\n const out = []\n let p = 0\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i)\n if (c < 128) {\n out[p++] = c\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192\n out[p++] = (c & 63) | 128\n } else if (\n ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&\n ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)\n out[p++] = (c >> 18) | 240\n out[p++] = ((c >> 12) & 63) | 128\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n } else {\n if ((c >= 0xD800) && (c <= 0xDFFF)) {\n c = 0xFFFD // Unpaired Surrogate\n }\n out[p++] = (c >> 12) | 224\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n }\n }\n return out\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\n/**\n * @param {number[]} codePoints\n * @returns {string}\n */\nexport function decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n","/**\n * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for\n * writing rather than reading.\n * A Bl object accepts set() operations for individual bytes and copyTo() for\n * inserting byte arrays. These write operations don't automatically increment\n * the internal cursor so its \"length\" won't be changed. Instead, increment()\n * must be called to extend its length to cover the inserted data.\n * The toBytes() call will convert all internal memory to a single Uint8Array of\n * the correct length, truncating any data that is stored but hasn't been\n * included by an increment().\n * get() can retrieve a single byte.\n * All operations (except toBytes()) take an \"offset\" argument that will perform\n * the write at the offset _from the current cursor_. For most operations this\n * will be `0` to write at the current cursor position but it can be ahead of\n * the current cursor. Negative offsets probably work but are untested.\n */\n\n// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39\nimport { alloc, concat, slice } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface.js').ByteView} ByteView\n * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView\n */\n\n// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists\n// for perf reasons. Consider better approaches to this or removing it entirely, it is quite\n// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.\n\nconst defaultChunkSize = 256\n\nexport class Bl {\n /**\n * @param {number} [chunkSize]\n */\n constructor (chunkSize = defaultChunkSize) {\n this.chunkSize = chunkSize\n /** @type {number} */\n this.cursor = 0\n /** @type {number} */\n this.maxCursor = -1\n /** @type {(ByteView|number[])[]} */\n this.chunks = []\n // keep the first chunk around if we can to save allocations for future encodes\n /** @type {ByteView|number[]|null} */\n this._initReuseChunk = null\n }\n\n reset () {\n this.cursor = 0\n this.maxCursor = -1\n if (this.chunks.length) {\n this.chunks = []\n }\n if (this._initReuseChunk !== null) {\n this.chunks.push(this._initReuseChunk)\n this.maxCursor = this._initReuseChunk.length - 1\n }\n }\n\n /**\n * @param {number} byte\n */\n pushByte (byte) {\n let topChunk = this.chunks[this.chunks.length - 1]\n if (this.cursor > this.maxCursor) {\n topChunk = alloc(this.chunkSize)\n this.chunks.push(topChunk)\n this.maxCursor += topChunk.length\n if (this._initReuseChunk === null) {\n this._initReuseChunk = topChunk\n }\n }\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n topChunk[chunkPos] = byte\n this.cursor++\n }\n\n /**\n * @param {ByteView|number[]} bytes\n */\n push (bytes) {\n let topChunk = this.chunks[this.chunks.length - 1]\n const newMax = this.cursor + bytes.length\n if (newMax <= this.maxCursor + 1) {\n // we have at least one chunk and we can fit these bytes into that chunk\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n // @ts-ignore\n topChunk.set(bytes, chunkPos)\n } else {\n // can't fit it in\n if (topChunk) {\n // trip the last chunk to `cursor` if we need to\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n if (chunkPos < topChunk.length) {\n // @ts-ignore\n this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)\n this.maxCursor = this.cursor - 1\n }\n }\n if (bytes.length < 64 && bytes.length < this.chunkSize) {\n // make a new chunk and copy the new one into it\n topChunk = alloc(this.chunkSize)\n this.chunks.push(topChunk)\n this.maxCursor += topChunk.length\n if (this._initReuseChunk === null) {\n this._initReuseChunk = topChunk\n }\n // @ts-ignore\n topChunk.set(bytes, 0)\n } else {\n // push the new bytes in as its own chunk\n this.chunks.push(bytes)\n this.maxCursor += bytes.length\n }\n }\n this.cursor += bytes.length\n }\n\n /**\n * @param {boolean} [reset]\n * @returns {AllocatedByteView}\n */\n toBytes (reset = false) {\n let byts\n if (this.chunks.length === 1) {\n const chunk = this.chunks[0]\n if (reset && this.cursor > chunk.length / 2) {\n // @ts-ignore\n byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)\n this._initReuseChunk = null\n this.chunks = []\n } else {\n // @ts-ignore\n byts = slice(chunk, 0, this.cursor)\n }\n } else {\n // @ts-ignore\n byts = concat(this.chunks, this.cursor)\n }\n if (reset) {\n this.reset()\n }\n return byts\n }\n}\n\n/**\n * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.\n * It provides the same interface as Bl but writes to a fixed destination.\n * @template {ArrayBufferLike} T\n */\nexport class U8Bl {\n /**\n * @param {Uint8Array<T>} dest\n */\n constructor (dest) {\n this.dest = dest\n /** @type {number} */\n this.cursor = 0\n // chunks is for interface compatibility with Bl - encode.js checks chunks.length\n // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].\n /** @type {Array<Uint8Array<T>>} */\n this.chunks = [dest]\n }\n\n reset () {\n this.cursor = 0\n }\n\n /**\n * @param {number} byte\n */\n pushByte (byte) {\n if (this.cursor >= this.dest.length) {\n throw new Error('write out of bounds, destination buffer is too small')\n }\n this.dest[this.cursor++] = byte\n }\n\n /**\n * @param {ByteView|number[]} bytes\n */\n push (bytes) {\n if (this.cursor + bytes.length > this.dest.length) {\n throw new Error('write out of bounds, destination buffer is too small')\n }\n this.dest.set(bytes, this.cursor)\n this.cursor += bytes.length\n }\n\n /**\n * @param {boolean} [reset]\n * @returns {Uint8Array<T>}\n */\n toBytes (reset = false) {\n const byts = this.dest.subarray(0, this.cursor)\n if (reset) {\n this.reset()\n }\n return byts\n }\n}\n","const decodeErrPrefix = 'CBOR decode error:'\nconst encodeErrPrefix = 'CBOR encode error:'\n\nconst uintMinorPrefixBytes = []\nuintMinorPrefixBytes[23] = 1\nuintMinorPrefixBytes[24] = 2\nuintMinorPrefixBytes[25] = 3\nuintMinorPrefixBytes[26] = 5\nuintMinorPrefixBytes[27] = 9\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} need\n */\nfunction assertEnoughData (data, pos, need) {\n if (data.length - pos < need) {\n throw new Error(`${decodeErrPrefix} not enough data for type`)\n }\n}\n\nexport {\n decodeErrPrefix,\n encodeErrPrefix,\n uintMinorPrefixBytes,\n assertEnoughData\n}\n","/* globals BigInt */\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix, assertEnoughData } from './common.js'\n\nexport const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint8 (data, offset, options) {\n assertEnoughData(data, offset, 1)\n const value = data[offset]\n if (options.strict === true && value < uintBoundaries[0]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint16 (data, offset, options) {\n assertEnoughData(data, offset, 2)\n const value = (data[offset] << 8) | data[offset + 1]\n if (options.strict === true && value < uintBoundaries[1]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint32 (data, offset, options) {\n assertEnoughData(data, offset, 4)\n const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n if (options.strict === true && value < uintBoundaries[2]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number|bigint}\n */\nexport function readUint64 (data, offset, options) {\n // assume BigInt, convert back to Number if within safe range\n assertEnoughData(data, offset, 8)\n const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]\n const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)\n if (options.strict === true && value < uintBoundaries[3]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n if (value <= Number.MAX_SAFE_INTEGER) {\n return Number(value)\n }\n if (options.allowBigInt === true) {\n return value\n }\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n}\n\n/* not required thanks to quick[] list\nconst oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))\nexport function decodeUintCompact (data, pos, minor, options) {\n return oneByteTokens[minor]\n}\n*/\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint8 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint16 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint32 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint64 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeUint (writer, token) {\n return encodeUintValue(writer, 0, token.value)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {number} major\n * @param {number|bigint} uint\n */\nexport function encodeUintValue (writer, major, uint) {\n if (uint < uintBoundaries[0]) {\n const nuint = Number(uint)\n // pack into one byte, minor=0, additional=value\n writer.pushByte(major | nuint)\n } else if (uint < uintBoundaries[1]) {\n const nuint = Number(uint)\n // pack into two byte, minor=0, additional=24\n writer.push([major | 24, nuint])\n } else if (uint < uintBoundaries[2]) {\n const nuint = Number(uint)\n // pack into three byte, minor=0, additional=25\n writer.push([major | 25, nuint >>> 8, nuint & 0xff])\n } else if (uint < uintBoundaries[3]) {\n const nuint = Number(uint)\n // pack into five byte, minor=0, additional=26\n writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])\n } else {\n const buint = BigInt(uint)\n if (buint < uintBoundaries[4]) {\n // pack into nine byte, minor=0, additional=27\n const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]\n // simulate bitwise above 32 bits\n let lo = Number(buint & BigInt(0xffffffff))\n let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))\n set[8] = lo & 0xff\n lo = lo >> 8\n set[7] = lo & 0xff\n lo = lo >> 8\n set[6] = lo & 0xff\n lo = lo >> 8\n set[5] = lo & 0xff\n set[4] = hi & 0xff\n hi = hi >> 8\n set[3] = hi & 0xff\n hi = hi >> 8\n set[2] = hi & 0xff\n hi = hi >> 8\n set[1] = hi & 0xff\n writer.push(set)\n } else {\n throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)\n }\n }\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeUint.encodedSize = function encodedSize (token) {\n return encodeUintValue.encodedSize(token.value)\n}\n\n/**\n * @param {number} uint\n * @returns {number}\n */\nencodeUintValue.encodedSize = function encodedSize (uint) {\n if (uint < uintBoundaries[0]) {\n return 1\n }\n if (uint < uintBoundaries[1]) {\n return 2\n }\n if (uint < uintBoundaries[2]) {\n return 3\n }\n if (uint < uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeUint.compareTokens = function compareTokens (tok1, tok2) {\n return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0\n}\n","/* eslint-env es2020 */\n\nimport { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint8 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint16 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint32 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)\n}\n\nconst neg1b = BigInt(-1)\nconst pos1b = BigInt(1)\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint64 (data, pos, _minor, options) {\n const int = uint.readUint64(data, pos + 1, options)\n if (typeof int !== 'bigint') {\n const value = -1 - int\n if (value >= Number.MIN_SAFE_INTEGER) {\n return new Token(Type.negint, value, 9)\n }\n }\n if (options.allowBigInt !== true) {\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n }\n return new Token(Type.negint, neg1b - BigInt(int), 9)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeNegint (writer, token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeNegint.encodedSize = function encodedSize (token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n // handled by quickEncode, we shouldn't get here but it's included for completeness\n if (unsigned < uint.uintBoundaries[0]) {\n return 1\n }\n if (unsigned < uint.uintBoundaries[1]) {\n return 2\n }\n if (unsigned < uint.uintBoundaries[2]) {\n return 3\n }\n if (unsigned < uint.uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeNegint.compareTokens = function compareTokens (tok1, tok2) {\n // opposite of the uint comparison since we store the uint version in bytes\n return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0\n}\n","import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { compare, fromString } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length) {\n assertEnoughData(data, pos, prefix + length)\n const buf = data.slice(pos + prefix, pos + prefix + length)\n return new Token(Type.bytes, buf, prefix + length)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeBytesCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * `encodedBytes` allows for caching when we do a byte version of a string\n * for key sorting purposes\n * @param {Token} token\n * @returns {Uint8Array}\n */\nfunction tokenBytes (token) {\n if (token.encodedBytes === undefined) {\n token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value\n }\n // @ts-ignore c'mon\n return token.encodedBytes\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeBytes (writer, token) {\n const bytes = tokenBytes(token)\n uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)\n writer.push(bytes)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeBytes.encodedSize = function encodedSize (token) {\n const bytes = tokenBytes(token)\n return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeBytes.compareTokens = function compareTokens (tok1, tok2) {\n return compareBytes(tokenBytes(tok1), tokenBytes(tok2))\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compareBytes (b1, b2) {\n return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)\n}\n","import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { encodeBytes } from './2bytes.js'\n\nconst textDecoder = new TextDecoder()\n\n// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for\n// map keys) are faster to decode with a simple loop than TextDecoder overhead.\nconst ASCII_THRESHOLD = 32\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n */\n\n/**\n * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),\n * a simple loop is faster than TextDecoder.\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n * @returns {string}\n */\nfunction toStr (bytes, start, end) {\n const len = end - start\n if (len < ASCII_THRESHOLD) {\n let str = ''\n for (let i = start; i < end; i++) {\n const c = bytes[i]\n if (c & 0x80) { // non-ASCII, fall back to TextDecoder\n return textDecoder.decode(bytes.subarray(start, end))\n }\n str += String.fromCharCode(c)\n }\n return str\n }\n return textDecoder.decode(bytes.subarray(start, end))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length, options) {\n const totLength = prefix + length\n assertEnoughData(data, pos, totLength)\n const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)\n if (options.retainStringBytes === true) {\n tok.byteValue = data.slice(pos + prefix, pos + totLength)\n }\n return tok\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeStringCompact (data, pos, minor, options) {\n return toToken(data, pos, 1, minor, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)\n }\n return toToken(data, pos, 9, l, options)\n}\n\nexport const encodeString = encodeBytes\n","import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.array, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeArrayCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArrayIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeArray (writer, token) {\n uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)\n}\n\n// using an array as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeArray.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeArray.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n","import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.map, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeMapCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMapIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeMap (writer, token) {\n uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)\n}\n\n// using a map as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeMap.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeMap.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n","import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeTagCompact (_data, _pos, minor, _options) {\n return new Token(Type.tag, minor, 1)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag8 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag16 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag32 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag64 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeTag (writer, token) {\n uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)\n}\n\nencodeTag.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeTag.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n","// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer\n// where possible\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix } from './common.js'\nimport { compare } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n * @typedef {import('../interface.js').EncodeOptions} EncodeOptions\n */\n\nexport const MINOR_FALSE = 20\nexport const MINOR_TRUE = 21\nexport const MINOR_NULL = 22\nexport const MINOR_UNDEFINED = 23\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUndefined (_data, _pos, _minor, options) {\n if (options.allowUndefined === false) {\n throw new Error(`${decodeErrPrefix} undefined values are not supported`)\n } else if (options.coerceUndefinedToNull === true) {\n return new Token(Type.null, null, 1)\n }\n return new Token(Type.undefined, undefined, 1)\n}\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBreak (_data, _pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return new Token(Type.break, undefined, 1)\n}\n\n/**\n * @param {number} value\n * @param {number} bytes\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction createToken (value, bytes, options) {\n if (options) {\n if (options.allowNaN === false && Number.isNaN(value)) {\n throw new Error(`${decodeErrPrefix} NaN values are not supported`)\n }\n if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {\n throw new Error(`${decodeErrPrefix} Infinity values are not supported`)\n }\n }\n return new Token(Type.float, value, bytes)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat16 (data, pos, _minor, options) {\n return createToken(readFloat16(data, pos + 1), 3, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat32 (data, pos, _minor, options) {\n return createToken(readFloat32(data, pos + 1), 5, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat64 (data, pos, _minor, options) {\n return createToken(readFloat64(data, pos + 1), 9, options)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n * @param {EncodeOptions} options\n */\nexport function encodeFloat (writer, token, options) {\n const float = token.value\n\n if (float === false) {\n writer.pushByte(Type.float.majorEncoded | MINOR_FALSE)\n } else if (float === true) {\n writer.pushByte(Type.float.majorEncoded | MINOR_TRUE)\n } else if (float === null) {\n writer.pushByte(Type.float.majorEncoded | MINOR_NULL)\n } else if (float === undefined) {\n writer.pushByte(Type.float.majorEncoded | MINOR_UNDEFINED)\n } else {\n let decoded\n let success = false\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n ui8a[0] = 0xf9\n writer.push(ui8a.slice(0, 3))\n success = true\n } else {\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n ui8a[0] = 0xfa\n writer.push(ui8a.slice(0, 5))\n success = true\n }\n }\n }\n if (!success) {\n encodeFloat64(float)\n decoded = readFloat64(ui8a, 1)\n ui8a[0] = 0xfb\n writer.push(ui8a.slice(0, 9))\n }\n }\n}\n\n/**\n * @param {Token} token\n * @param {EncodeOptions} options\n * @returns {number}\n */\nencodeFloat.encodedSize = function encodedSize (token, options) {\n const float = token.value\n\n if (float === false || float === true || float === null || float === undefined) {\n return 1\n }\n\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n let decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n return 3\n }\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n return 5\n }\n }\n return 9\n}\n\nconst buffer = new ArrayBuffer(9)\nconst dataView = new DataView(buffer, 1)\nconst ui8a = new Uint8Array(buffer, 0)\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat16 (inp) {\n if (inp === Infinity) {\n dataView.setUint16(0, 0x7c00, false)\n } else if (inp === -Infinity) {\n dataView.setUint16(0, 0xfc00, false)\n } else if (Number.isNaN(inp)) {\n dataView.setUint16(0, 0x7e00, false)\n } else {\n dataView.setFloat32(0, inp)\n const valu32 = dataView.getUint32(0)\n const exponent = (valu32 & 0x7f800000) >> 23\n const mantissa = valu32 & 0x7fffff\n\n if (exponent === 0xff) {\n // too big, Infinity, but this should be hard (impossible?) to trigger\n dataView.setUint16(0, 0x7c00, false)\n } else if (exponent === 0x00) {\n // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int\n // Use valu32 for sign bit since bitwise ops on floats lose -0 sign\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)\n } else { // standard numbers\n // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127\n const logicalExponent = exponent - 127\n // Now we know that 2^exponent <= 0 logically\n if (logicalExponent < -24) {\n /* No unambiguous representation exists, this float is not a half float\n and is too small to be represented using a half, round off to zero.\n Consistent with the reference implementation. */\n // should be difficult (impossible?) to get here in JS\n dataView.setUint16(0, 0)\n } else if (logicalExponent < -14) {\n /* Offset the remaining decimal places by shifting the significand, the\n value is lost. This is an implementation decision that works around the\n absence of standard half-float in the language. */\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)\n } else {\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)\n }\n }\n }\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat16 (ui8a, pos) {\n if (ui8a.length - pos < 2) {\n throw new Error(`${decodeErrPrefix} not enough data for float16`)\n }\n\n const half = (ui8a[pos] << 8) + ui8a[pos + 1]\n if (half === 0x7c00) {\n return Infinity\n }\n if (half === 0xfc00) {\n return -Infinity\n }\n if (half === 0x7e00) {\n return NaN\n }\n const exp = (half >> 10) & 0x1f\n const mant = half & 0x3ff\n let val\n if (exp === 0) {\n val = mant * (2 ** -24)\n } else if (exp !== 31) {\n val = (mant + 1024) * (2 ** (exp - 25))\n } else {\n // may not be possible to get here\n val = mant === 0 ? Infinity : NaN\n }\n return (half & 0x8000) ? -val : val\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat32 (inp) {\n dataView.setFloat32(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat32 (ui8a, pos) {\n if (ui8a.length - pos < 4) {\n throw new Error(`${decodeErrPrefix} not enough data for float32`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat64 (inp) {\n dataView.setFloat64(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat64 (ui8a, pos) {\n if (ui8a.length - pos < 8) {\n throw new Error(`${decodeErrPrefix} not enough data for float64`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)\n}\n\n/**\n * @typedef {Token & {\n * _keyBytes?: Uint8Array,\n * _keyBytesFloat64?: Uint8Array\n * }} TokenEx\n */\n\n/**\n * The canonical CBOR bytes for a major 7 map key. The four simple values encode\n * to a single byte and every float to its 3, 5 or 9 byte form, exactly as\n * {@link encodeFloat} writes them. This mirrors the width selection in\n * `encodeFloat` because the sorter needs the bytes in hand to compare.\n * @param {Token} token\n * @param {boolean} float64\n * @returns {Uint8Array}\n */\nfunction encodeMajorSevenBytes (token, float64) {\n const float = token.value\n if (float === false) {\n return Uint8Array.of(Type.float.majorEncoded | MINOR_FALSE)\n }\n if (float === true) {\n return Uint8Array.of(Type.float.majorEncoded | MINOR_TRUE)\n }\n if (float === null) {\n return Uint8Array.of(Type.float.majorEncoded | MINOR_NULL)\n }\n if (float === undefined) {\n return Uint8Array.of(Type.float.majorEncoded | MINOR_UNDEFINED)\n }\n if (!float64) {\n encodeFloat16(float)\n if (float === readFloat16(ui8a, 1) || Number.isNaN(float)) {\n ui8a[0] = 0xf9\n return ui8a.slice(0, 3)\n }\n encodeFloat32(float)\n if (float === readFloat32(ui8a, 1)) {\n ui8a[0] = 0xfa\n return ui8a.slice(0, 5)\n }\n }\n encodeFloat64(float)\n ui8a[0] = 0xfb\n return ui8a.slice(0, 9)\n}\n\n/**\n * Get the canonical CBOR bytes for a major 7 map key, honouring\n * `options.float64`. Bytes are cached because Array.sort compares each key\n * multiple times.\n * @param {Token} token\n * @param {EncodeOptions} [options]\n * @returns {Uint8Array}\n */\nfunction majorSevenBytes (token, options) {\n const tokenEx = /** @type {TokenEx} */ (token)\n const float64 = options?.float64 === true\n const cached = float64 ? tokenEx._keyBytesFloat64 : tokenEx._keyBytes\n if (cached !== undefined) {\n return cached\n }\n\n const bytes = encodeMajorSevenBytes(token, float64)\n if (float64) {\n tokenEx._keyBytesFloat64 = bytes\n } else {\n tokenEx._keyBytes = bytes\n }\n return bytes\n}\n\n/**\n * Order two major 7 map keys by RFC 7049 §3.9 canonical order: shorter encoding\n * first, then bytewise. Because the four simple values encode to one byte they\n * sort ahead of every float, and comparing the `float64`-honouring encoded bytes\n * (rather than the numeric value) makes negative floats, mixed encoding widths\n * and `NaN` deterministic regardless of insertion order.\n * @param {Token} tok1\n * @param {Token} tok2\n * @param {EncodeOptions} [options]\n * @returns {number}\n */\nencodeFloat.compareTokens = function compareTokens (tok1, tok2, options) {\n const b1 = majorSevenBytes(tok1, options)\n const b2 = majorSevenBytes(tok2, options)\n if (b1.length !== b2.length) {\n return b1.length < b2.length ? -1 : 1\n }\n return compare(b1, b2)\n}\n","import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport * as negint from './1negint.js'\nimport * as bytes from './2bytes.js'\nimport * as string from './3string.js'\nimport * as array from './4array.js'\nimport * as map from './5map.js'\nimport * as tag from './6tag.js'\nimport * as float from './7float.js'\nimport { decodeErrPrefix } from './common.js'\nimport { fromArray } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n */\nfunction invalidMinor (data, pos, minor) {\n throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)\n}\n\n/**\n * @param {string} msg\n * @returns {()=>any}\n */\nfunction errorer (msg) {\n return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }\n}\n\n/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */\nexport const jump = []\n\n// unsigned integer, 0x00..0x17 (0..23)\nfor (let i = 0; i <= 0x17; i++) {\n jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]\n}\njump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows\njump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows\njump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows\njump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows\njump[0x1c] = invalidMinor\njump[0x1d] = invalidMinor\njump[0x1e] = invalidMinor\njump[0x1f] = invalidMinor\n// negative integer, -1-0x00..-1-0x17 (-1..-24)\nfor (let i = 0x20; i <= 0x37; i++) {\n jump[i] = invalidMinor // negintDecode, handled by quick[]\n}\njump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows\njump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows\njump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows\njump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows\njump[0x3c] = invalidMinor\njump[0x3d] = invalidMinor\njump[0x3e] = invalidMinor\njump[0x3f] = invalidMinor\n// byte string, 0x00..0x17 bytes follow\nfor (let i = 0x40; i <= 0x57; i++) {\n jump[i] = bytes.decodeBytesCompact\n}\njump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow\njump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow\njump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow\njump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow\njump[0x5c] = invalidMinor\njump[0x5d] = invalidMinor\njump[0x5e] = invalidMinor\njump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by \"break\"\n// UTF-8 string 0x00..0x17 bytes follow\nfor (let i = 0x60; i <= 0x77; i++) {\n jump[i] = string.decodeStringCompact\n}\njump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow\njump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow\njump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow\njump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow\njump[0x7c] = invalidMinor\njump[0x7d] = invalidMinor\njump[0x7e] = invalidMinor\njump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by \"break\"\n// array, 0x00..0x17 data items follow\nfor (let i = 0x80; i <= 0x97; i++) {\n jump[i] = array.decodeArrayCompact\n}\njump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow\njump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow\njump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow\njump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow\njump[0x9c] = invalidMinor\njump[0x9d] = invalidMinor\njump[0x9e] = invalidMinor\njump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by \"break\"\n// map, 0x00..0x17 pairs of data items follow\nfor (let i = 0xa0; i <= 0xb7; i++) {\n jump[i] = map.decodeMapCompact\n}\njump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow\njump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow\njump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow\njump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow\njump[0xbc] = invalidMinor\njump[0xbd] = invalidMinor\njump[0xbe] = invalidMinor\njump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by \"break\"\n// tags\nfor (let i = 0xc0; i <= 0xd7; i++) {\n jump[i] = tag.decodeTagCompact\n}\njump[0xd8] = tag.decodeTag8\njump[0xd9] = tag.decodeTag16\njump[0xda] = tag.decodeTag32\njump[0xdb] = tag.decodeTag64\njump[0xdc] = invalidMinor\njump[0xdd] = invalidMinor\njump[0xde] = invalidMinor\njump[0xdf] = invalidMinor\n// 0xe0..0xf3 simple values, unsupported\nfor (let i = 0xe0; i <= 0xf3; i++) {\n jump[i] = errorer('simple values are not supported')\n}\njump[0xf4] = invalidMinor // false, handled by quick[]\njump[0xf5] = invalidMinor // true, handled by quick[]\njump[0xf6] = invalidMinor // null, handled by quick[]\njump[0xf7] = float.decodeUndefined // undefined\njump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported\njump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)\njump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)\njump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)\njump[0xfc] = invalidMinor\njump[0xfd] = invalidMinor\njump[0xfe] = invalidMinor\njump[0xff] = float.decodeBreak // \"break\" stop code\n\n/** @type {Token[]} */\nexport const quick = []\n// ints <24\nfor (let i = 0; i < 24; i++) {\n quick[i] = new Token(Type.uint, i, 1)\n}\n// negints >= -24\nfor (let i = -1; i >= -24; i--) {\n quick[31 - i] = new Token(Type.negint, i, 1)\n}\n// empty bytes\nquick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)\n// empty string\nquick[0x60] = new Token(Type.string, '', 1)\n// empty list\nquick[0x80] = new Token(Type.array, 0, 1)\n// empty map\nquick[0xa0] = new Token(Type.map, 0, 1)\n// false\nquick[0xf4] = new Token(Type.false, false, 1)\n// true\nquick[0xf5] = new Token(Type.true, true, 1)\n// null\nquick[0xf6] = new Token(Type.null, null, 1)\n\n/**\n * @param {Token} token\n * @returns {AllocatedByteView|undefined}\n */\nexport function quickEncodeToken (token) {\n switch (token.type) {\n case Type.false:\n return fromArray([0xf4])\n case Type.true:\n return fromArray([0xf5])\n case Type.null:\n return fromArray([0xf6])\n case Type.bytes:\n if (!token.value.length) {\n return fromArray([0x40])\n }\n return\n case Type.string:\n if (token.value === '') {\n return fromArray([0x60])\n }\n return\n case Type.array:\n if (token.value === 0) {\n return fromArray([0x80])\n }\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.map:\n if (token.value === 0) {\n return fromArray([0xa0])\n }\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.uint:\n if (token.value < 24) {\n return fromArray([Number(token.value)])\n }\n return\n case Type.negint:\n if (token.value >= -24) {\n return fromArray([31 - Number(token.value)])\n }\n }\n}\n","import { is } from './is.js'\nimport { Token, Type } from './token.js'\nimport { Bl, U8Bl } from './bl.js'\nimport { encodeErrPrefix } from './common.js'\nimport { quickEncodeToken } from './jump.js'\nimport { asU8A, compare, fromString } from './byte-utils.js'\n\nimport { encodeUint, encodeUintValue } from './0uint.js'\nimport { encodeNegint } from './1negint.js'\nimport { encodeBytes } from './2bytes.js'\nimport { encodeString } from './3string.js'\nimport { encodeArray } from './4array.js'\nimport { encodeMap } from './5map.js'\nimport { encodeTag } from './6tag.js'\nimport { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'\n\n/**\n * @typedef {import('../interface.js').EncodeOptions} EncodeOptions\n * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder\n * @typedef {import('../interface.js').Reference} Reference\n * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder\n * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder\n * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').ByteView} ByteView\n * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView\n */\n\n/** @type {EncodeOptions} */\nconst defaultEncodeOptions = {\n float64: false,\n mapSorter,\n quickEncodeToken\n}\n\n/** @type {EncodeOptions} */\nexport const rfc8949EncodeOptions = Object.freeze({\n mapSorter: rfc8949MapSorter,\n quickEncodeToken\n})\n\n/** @returns {TokenTypeEncoder[]} */\nexport function makeCborEncoders () {\n const encoders = []\n encoders[Type.uint.major] = encodeUint\n encoders[Type.negint.major] = encodeNegint\n encoders[Type.bytes.major] = encodeBytes\n encoders[Type.string.major] = encodeString\n encoders[Type.array.major] = encodeArray\n encoders[Type.map.major] = encodeMap\n encoders[Type.tag.major] = encodeTag\n encoders[Type.float.major] = encodeFloat\n return encoders\n}\n\nconst cborEncoders = makeCborEncoders()\n\nconst defaultWriter = new Bl()\n\n/** @implements {Reference} */\nclass Ref {\n /**\n * @param {object|any[]} obj\n * @param {Reference|undefined} parent\n */\n constructor (obj, parent) {\n this.obj = obj\n this.parent = parent\n }\n\n /**\n * @param {object|any[]} obj\n * @returns {boolean}\n */\n includes (obj) {\n /** @type {Reference|undefined} */\n let p = this\n do {\n if (p.obj === obj) {\n return true\n }\n } while (p = p.parent) // eslint-disable-line\n return false\n }\n\n /**\n * @param {Reference|undefined} stack\n * @param {object|any[]} obj\n * @returns {Reference}\n */\n static createCheck (stack, obj) {\n if (stack && stack.includes(obj)) {\n throw new Error(`${encodeErrPrefix} object contains circular references`)\n }\n return new Ref(obj, stack)\n }\n}\n\nconst simpleTokens = {\n null: new Token(Type.null, null),\n undefined: new Token(Type.undefined, undefined),\n true: new Token(Type.true, true),\n false: new Token(Type.false, false),\n emptyArray: new Token(Type.array, 0),\n emptyMap: new Token(Type.map, 0)\n}\n\n/** @type {{[typeName: string]: StrictTypeEncoder}} */\nconst typeEncoders = {\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n number (obj, _typ, _options, _refStack) {\n if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {\n return new Token(Type.float, obj)\n } else if (obj >= 0) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n bigint (obj, _typ, _options, _refStack) {\n if (obj >= BigInt(0)) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n Uint8Array (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n string (obj, _typ, _options, _refStack) {\n return new Token(Type.string, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n boolean (obj, _typ, _options, _refStack) {\n return obj ? simpleTokens.true : simpleTokens.false\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n null (_obj, _typ, _options, _refStack) {\n return simpleTokens.null\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n undefined (_obj, _typ, _options, _refStack) {\n return simpleTokens.undefined\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n ArrayBuffer (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n DataView (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Array (obj, _typ, options, refStack) {\n if (!obj.length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyArray, new Token(Type.break)]\n }\n return simpleTokens.emptyArray\n }\n refStack = Ref.createCheck(refStack, obj)\n const entries = []\n let i = 0\n for (const e of obj) {\n entries[i++] = objectToTokens(e, options, refStack)\n }\n if (options.addBreakTokens) {\n return [new Token(Type.array, obj.length), entries, new Token(Type.break)]\n }\n return [new Token(Type.array, obj.length), entries]\n },\n\n /**\n * @param {any} obj\n * @param {string} typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Object (obj, typ, options, refStack) {\n // could be an Object or a Map\n const isMap = typ !== 'Object'\n // it's slightly quicker to use Object.keys() than Object.entries()\n const keys = isMap ? obj.keys() : Object.keys(obj)\n const maxLength = isMap ? obj.size : keys.length\n\n /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */\n let entries\n\n if (maxLength) {\n // Pre-allocate the array with the expected size\n entries = new Array(maxLength)\n refStack = Ref.createCheck(refStack, obj)\n const skipUndefined = !isMap && options.ignoreUndefinedProperties\n\n let i = 0\n for (const key of keys) {\n const value = isMap ? obj.get(key) : obj[key]\n if (skipUndefined && value === undefined) {\n continue\n }\n entries[i++] = [\n objectToTokens(key, options, refStack),\n objectToTokens(value, options, refStack)\n ]\n }\n\n // Truncate only if properties were skipped\n if (i < maxLength) {\n entries.length = i\n }\n }\n\n if (!entries?.length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyMap, new Token(Type.break)]\n }\n return simpleTokens.emptyMap\n }\n\n sortMapEntries(entries, options)\n if (options.addBreakTokens) {\n return [new Token(Type.map, entries.length), entries, new Token(Type.break)]\n }\n return [new Token(Type.map, entries.length), entries]\n },\n\n /**\n * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded\n * form of the wrapped value. The value is recursively tokenised through\n * `objectToTokens()` so any registered `typeEncoders` apply to it.\n *\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Tagged (obj, _typ, options, refStack) {\n return [\n new Token(Type.tag, obj.tag),\n objectToTokens(obj.value, options, refStack)\n ]\n }\n}\n\ntypeEncoders.Map = typeEncoders.Object\ntypeEncoders.Buffer = typeEncoders.Uint8Array\nfor (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {\n typeEncoders[`${typ}Array`] = typeEncoders.DataView\n}\n\n/**\n * @param {any} obj\n * @param {EncodeOptions} [options]\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\nfunction objectToTokens (obj, options = {}, refStack) {\n const typ = is(obj)\n const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]\n if (typeof customTypeEncoder === 'function') {\n const tokens = customTypeEncoder(obj, typ, options, refStack)\n if (tokens != null) {\n return tokens\n }\n }\n const typeEncoder = typeEncoders[typ]\n if (!typeEncoder) {\n throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)\n }\n return typeEncoder(obj, typ, options, refStack)\n}\n\n/*\nCBOR key sorting is a mess.\n\nThe canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9\nincludes the wording:\n\n> The keys in every map must be sorted lowest value to highest.\n> Sorting is performed on the bytes of the representation of the key\n> data items without paying attention to the 3/5 bit splitting for\n> major types.\n> ...\n> * If two keys have different lengths, the shorter one sorts\n earlier;\n> * If two keys have the same length, the one with the lower value\n in (byte-wise) lexical order sorts earlier.\n\n1. It is not clear what \"bytes of the representation of the key\" means: is it\n the CBOR representation, or the binary representation of the object itself?\n Consider the int and uint difference here.\n2. It is not clear what \"without paying attention to\" means: do we include it\n and compare on that? Or do we omit the special prefix byte, (mostly) treating\n the key in its plain binary representation form.\n\nThe FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR\nwording and clarifies it according to their understanding.\nhttps://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding\n\n> The keys in every map must be sorted lowest value to highest. Sorting is\n> performed on the bytes of the representation of the key data items without\n> paying attention to the 3/5 bit splitting for major types. The sorting rules\n> are:\n> * If the major types are different, the one with the lower value in numerical\n> order sorts earlier.\n> * If two keys have different lengths, the shorter one sorts earlier;\n> * If two keys have the same length, the one with the lower value in\n> (byte-wise) lexical order sorts earlier.\n\nSome other implementations, such as borc, do a full encode then do a\nlength-first, byte-wise-second comparison:\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151\n\nThis has the benefit of being able to easily handle arbitrary keys, including\ncomplex types (maps and arrays).\n\nWe'll opt for the FIDO approach, since it affords some efficies since we don't\nneed a full encode of each key to determine order and can defer to the types\nto determine how to most efficiently order their values (i.e. int and uint\nordering can be done on the numbers, no need for byte-wise, for example).\n\nRecommendation: stick to single key types or you'll get into trouble, and prefer\nstring keys because it's much simpler that way.\n*/\n\n/**\n * @param {TokenOrNestedTokens[]} entries\n * @param {EncodeOptions} options\n */\nfunction sortMapEntries (entries, options) {\n // cast because entries carry the wider TokenOrNestedTokens element type while\n // MapSorter narrows to (Token | Token[])[]; the original direct sort relied on\n // sort's bivariant parameter check, the wrapper below re-states it\n const mapSorter = /** @type {(e1: TokenOrNestedTokens, e2: TokenOrNestedTokens, options?: EncodeOptions) => number} */ (options.mapSorter)\n if (mapSorter) {\n // pass options so a sorter can honour encode options (e.g. major 7 keys\n // order by their float64-honouring encoding); custom sorters that take\n // only (e1, e2) simply ignore the extra argument\n entries.sort((e1, e2) => mapSorter(e1, e2, options))\n }\n}\n\n/**\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @param {EncodeOptions} [options]\n * @returns {number}\n */\nfunction mapSorter (e1, e2, options) {\n // the key position ([0]) could have a single token or an array\n // almost always it'll be a single token but complex key might get involved\n const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]\n const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]\n\n // different key type majors\n if (keyToken1.type.major !== keyToken2.type.major) {\n return keyToken1.type.compare(keyToken2.type)\n }\n\n const major = keyToken1.type.major\n // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)\n const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2, options)\n if (tcmp === 0) {\n // duplicate key or complex type where the first token matched,\n // i.e. a map or array and we're only comparing the opening token\n console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')\n }\n return tcmp\n}\n\n/**\n * @typedef {Token & { _keyBytes?: AllocatedByteView }} TokenEx\n *\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction rfc8949MapSorter (e1, e2) {\n if (e1[0] instanceof Token && e2[0] instanceof Token) {\n const t1 = /** @type {TokenEx} */ (e1[0])\n const t2 = /** @type {TokenEx} */ (e2[0])\n\n if (!t1._keyBytes) {\n t1._keyBytes = encodeRfc8949(t1.value)\n }\n\n if (!t2._keyBytes) {\n t2._keyBytes = encodeRfc8949(t2.value)\n }\n\n return compare(t1._keyBytes, t2._keyBytes)\n }\n\n throw new Error('rfc8949MapSorter: complex key types are not supported yet')\n}\n\n/**\n * @param {any} data\n * @returns {AllocatedByteView}\n */\nfunction encodeRfc8949 (data) {\n return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {TokenOrNestedTokens} tokens\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n */\nfunction tokensToEncoded (writer, tokens, encoders, options) {\n if (Array.isArray(tokens)) {\n for (const token of tokens) {\n tokensToEncoded(writer, token, encoders, options)\n }\n } else {\n encoders[tokens.type.major](writer, tokens, options)\n }\n}\n\n// CBOR major type prefixes, cached from Type for hot path performance\nconst MAJOR_UINT = Type.uint.majorEncoded\nconst MAJOR_NEGINT = Type.negint.majorEncoded\nconst MAJOR_BYTES = Type.bytes.majorEncoded\nconst MAJOR_STRING = Type.string.majorEncoded\nconst MAJOR_ARRAY = Type.array.majorEncoded\nconst MAJOR_MAP = Type.map.majorEncoded\n\n// Simple value bytes (CBOR major type 7 + minor value)\nconst SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE\nconst SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE\nconst SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL\nconst SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED\n\nconst neg1b = BigInt(-1)\nconst pos1b = BigInt(1)\n\n/**\n * Compact direct-path writes avoid the full uint boundary chain.\n * @param {ByteWriter} writer\n * @param {number} major\n * @param {number|bigint} uint\n */\nfunction directEncodeUintValue (writer, major, uint) {\n if (uint < 24) {\n writer.pushByte(major | Number(uint))\n } else {\n encodeUintValue(writer, major, uint)\n }\n}\n\n/**\n * Check if direct encoding can be used for the given options.\n * Direct encoding bypasses token creation for most values.\n * @param {EncodeOptions} options\n * @returns {boolean}\n */\nfunction canDirectEncode (options) {\n // Cannot use direct encode with addBreakTokens (needs special break token handling).\n // Direct encode checks typeEncoders per-value, falling back to tokens as needed.\n // Maps fall back to token-based encoding for efficient key sorting.\n return options.addBreakTokens !== true\n}\n\n/**\n * Encode a map through the default deterministic sorter while keeping values\n * on the direct path. Only keys need tokens for comparison.\n * @param {ByteWriter} writer\n * @param {any} data\n * @param {string} typ\n * @param {EncodeOptions} options\n * @param {Reference|undefined} refStack\n */\nfunction directEncodeMap (writer, data, typ, options, refStack) {\n const isMap = typ === 'Map'\n const keys = isMap ? data.keys() : Object.keys(data)\n const maxLength = isMap ? data.size : keys.length\n\n if (!maxLength) {\n writer.pushByte(MAJOR_MAP)\n return\n }\n\n refStack = Ref.createCheck(refStack, data)\n const skipUndefined = !isMap && options.ignoreUndefinedProperties\n const entries = new Array(maxLength)\n let length = 0\n\n for (const key of keys) {\n const value = isMap ? data.get(key) : data[key]\n if (skipUndefined && value === undefined) {\n continue\n }\n entries[length++] = [objectToTokens(key, options, refStack), value]\n }\n\n if (length === 0) {\n writer.pushByte(MAJOR_MAP)\n return\n }\n if (length < maxLength) {\n entries.length = length\n }\n\n entries.sort((e1, e2) => mapSorter(e1, e2, options))\n directEncodeUintValue(writer, MAJOR_MAP, length)\n for (const [key, value] of entries) {\n tokensToEncoded(writer, key, cborEncoders, options)\n directEncode(writer, value, options, refStack)\n }\n}\n\n/**\n * Direct encode a value to the writer, bypassing token creation for most types.\n * Falls back to token-based encoding for custom type encoders.\n * @param {ByteWriter} writer\n * @param {any} data\n * @param {EncodeOptions} options\n * @param {Reference|undefined} refStack\n */\nfunction directEncode (writer, data, options, refStack) {\n const typ = is(data)\n\n // Check for custom encoder for THIS specific type\n const customEncoder = options.typeEncoders && options.typeEncoders[typ]\n if (customEncoder) {\n const tokens = customEncoder(data, typ, options, refStack)\n if (tokens != null) {\n // Custom encoder returned tokens, serialize immediately\n tokensToEncoded(writer, tokens, cborEncoders, options)\n return\n }\n // Custom encoder returned null, fall through to default handling\n }\n\n // Direct encode based on type\n switch (typ) {\n case 'null':\n writer.pushByte(SIMPLE_NULL)\n return\n\n case 'undefined':\n writer.pushByte(SIMPLE_UNDEFINED)\n return\n\n case 'boolean':\n writer.pushByte(data ? SIMPLE_TRUE : SIMPLE_FALSE)\n return\n\n case 'number':\n if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {\n // Float, use token encoder for complex float encoding\n encodeFloat(writer, new Token(Type.float, data), options)\n } else if (data >= 0) {\n directEncodeUintValue(writer, MAJOR_UINT, data)\n } else {\n // Negative integer\n directEncodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)\n }\n return\n\n case 'bigint':\n if (data >= BigInt(0)) {\n directEncodeUintValue(writer, MAJOR_UINT, data)\n } else {\n directEncodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)\n }\n return\n\n case 'string': {\n const bytes = fromString(data)\n directEncodeUintValue(writer, MAJOR_STRING, bytes.length)\n writer.push(bytes)\n return\n }\n\n case 'Uint8Array':\n directEncodeUintValue(writer, MAJOR_BYTES, data.length)\n writer.push(data)\n return\n\n case 'Array':\n if (!data.length) {\n writer.pushByte(MAJOR_ARRAY) // Empty array: 0x80\n return\n }\n refStack = Ref.createCheck(refStack, data)\n directEncodeUintValue(writer, MAJOR_ARRAY, data.length)\n for (const elem of data) {\n directEncode(writer, elem, options, refStack)\n }\n return\n\n case 'Object':\n case 'Map':\n if (options.mapSorter === mapSorter) {\n directEncodeMap(writer, data, typ, options, refStack)\n } else {\n const tokens = typeEncoders.Object(data, typ, options, refStack)\n tokensToEncoded(writer, tokens, cborEncoders, options)\n }\n return\n\n default:\n // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)\n {\n const typeEncoder = typeEncoders[typ]\n if (!typeEncoder) {\n throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)\n }\n const tokens = typeEncoder(data, typ, options, refStack)\n tokensToEncoded(writer, tokens, cborEncoders, options)\n }\n }\n}\n\n/**\n * @template {ArrayBufferLike} T\n * @overload\n * @param {any} data\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n * @param {Uint8Array<T>} destination\n * @returns {Uint8Array<T>}\n */\n/**\n * @overload\n * @param {any} data\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n * @returns {AllocatedByteView}\n */\n/**\n * @param {any} data\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n * @param {ByteView} [destination]\n * @returns {ByteView}\n */\nfunction encodeCustom (data, encoders, options, destination) {\n // arg ordering is different to encodeInto for backward compatibility\n const hasDest = destination instanceof Uint8Array\n let writeTo = hasDest ? new U8Bl(destination) : defaultWriter\n\n const tokens = objectToTokens(data, options)\n if (!Array.isArray(tokens) && options.quickEncodeToken) {\n const quickBytes = options.quickEncodeToken(tokens)\n if (quickBytes) {\n if (hasDest) {\n // Copy quick bytes into destination buffer\n writeTo.push(quickBytes)\n return writeTo.toBytes()\n }\n return quickBytes\n }\n const encoder = encoders[tokens.type.major]\n if (encoder.encodedSize) {\n const size = encoder.encodedSize(tokens, options)\n if (!hasDest) {\n writeTo = new Bl(size)\n }\n encoder(writeTo, tokens, options)\n // this would be a problem with encodedSize() functions\n if (writeTo.chunks.length !== 1) {\n throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)\n }\n return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])\n }\n }\n writeTo.reset()\n tokensToEncoded(writeTo, tokens, encoders, options)\n return writeTo.toBytes(true)\n}\n\n/**\n * @param {any} data\n * @param {EncodeOptions} [options]\n * @returns {AllocatedByteView}\n */\nfunction encode (data, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n\n // Use direct encode path when possible\n if (canDirectEncode(options)) {\n defaultWriter.reset()\n directEncode(defaultWriter, data, options, undefined)\n return defaultWriter.toBytes(true)\n }\n\n return encodeCustom(data, cborEncoders, options)\n}\n\n/**\n * @template {ArrayBufferLike} T\n * @param {any} data\n * @param {Uint8Array<T>} destination\n * @param {EncodeOptions} [options]\n * @returns {{ written: number }}\n */\nfunction encodeInto (data, destination, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n\n // Use direct encode path when possible\n if (canDirectEncode(options)) {\n const writer = new U8Bl(destination)\n directEncode(writer, data, options, undefined)\n return { written: writer.toBytes().length }\n }\n\n const result = encodeCustom(data, cborEncoders, options, destination)\n return { written: result.length }\n}\n\nexport { objectToTokens, encode, encodeCustom, encodeInto, Ref }\n","import { decodeErrPrefix } from './common.js'\nimport { Type } from './token.js'\nimport { jump, quick } from './jump.js'\nimport { asU8A } from './byte-utils.js'\n\n/**\n * @typedef {import('./token.js').Token} Token\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer\n * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl\n */\n\nconst defaultDecodeOptions = {\n strict: false,\n allowIndefinite: true,\n allowUndefined: true,\n allowBigInt: true\n}\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass Tokeniser {\n /**\n * @param {Uint8Array} data\n * @param {DecodeOptions} options\n */\n constructor (data, options = {}) {\n this._pos = 0\n this.data = data\n this.options = options\n }\n\n pos () {\n return this._pos\n }\n\n done () {\n return this._pos >= this.data.length\n }\n\n next () {\n const byt = this.data[this._pos]\n let token = quick[byt]\n if (token === undefined) {\n const decoder = jump[byt]\n // if we're here then there's something wrong with our jump or quick lists!\n if (!decoder) {\n throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)\n }\n const minor = byt & 31\n token = decoder(this.data, this._pos, minor, this.options)\n }\n // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)\n this._pos += token.encodedLength\n return token\n }\n}\n\nconst DONE = Symbol.for('DONE')\nconst BREAK = Symbol.for('BREAK')\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|typeof BREAK|typeof DONE}\n */\nfunction tokenToArray (token, tokeniser, options) {\n const arr = []\n for (let i = 0; i < token.value; i++) {\n const value = tokensToObject(tokeniser, options)\n if (value === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length array\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)\n }\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)\n }\n arr[i] = value\n }\n return arr\n}\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|typeof BREAK|typeof DONE}\n */\nfunction tokenToMap (token, tokeniser, options) {\n const useMaps = options.useMaps === true\n const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true\n const obj = useMaps ? undefined : {}\n const m = useMaps ? new Map() : undefined\n for (let i = 0; i < token.value; i++) {\n const key = tokensToObject(tokeniser, options)\n if (key === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length map\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)\n }\n if (key === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)\n }\n if (!useMaps && typeof key !== 'string') {\n throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)\n }\n if (rejectDuplicateMapKeys) {\n // @ts-ignore\n if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {\n throw new Error(`${decodeErrPrefix} found repeat map key \"${key}\"`)\n }\n }\n const value = tokensToObject(tokeniser, options)\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)\n }\n if (useMaps) {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n m.set(key, value)\n } else if (key === '__proto__') {\n // a plain assignment would invoke the prototype setter instead of creating\n // an own property, losing the entry and mutating the object's prototype\n Object.defineProperty(obj, key, { value, configurable: true, enumerable: true, writable: true })\n } else {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n obj[key] = value\n }\n }\n // @ts-ignore c'mon man\n return useMaps ? m : obj\n}\n\n/**\n * Generator that yields [key, value] entries from a CBOR map token.\n * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).\n * @param {Token} token - The map token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {Generator<[any, any], void, unknown>}\n */\nfunction * tokenToMapEntries (token, tokeniser, options) {\n for (let i = 0; i < token.value; i++) {\n const key = tokensToObject(tokeniser, options)\n if (key === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length map\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)\n }\n if (key === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)\n }\n const value = tokensToObject(tokeniser, options)\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)\n }\n yield [key, value]\n }\n}\n\n/**\n * Creates a TagDecodeControl object for tag decoders.\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {TagDecodeControl}\n */\nfunction createTagDecodeControl (tokeniser, options) {\n /** @type {TagDecodeControl & {_called: boolean}} */\n const decode = function () {\n if (decode._called) {\n throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)\n }\n decode._called = true\n const value = tokensToObject(tokeniser, options)\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} tag content missing`)\n }\n if (value === BREAK) {\n throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)\n }\n return value\n }\n\n decode.entries = function () {\n if (decode._called) {\n throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)\n }\n decode._called = true\n\n const token = tokeniser.next()\n if (!Type.equals(token.type, Type.map)) {\n throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)\n }\n\n const entries = []\n for (const entry of tokenToMapEntries(token, tokeniser, options)) {\n entries.push(entry)\n }\n return entries\n }\n\n decode._called = false\n return decode\n}\n\n/**\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|typeof BREAK|typeof DONE}\n */\nfunction tokensToObject (tokeniser, options) {\n // should we support array as an argument?\n // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?\n if (tokeniser.done()) {\n return DONE\n }\n\n const token = tokeniser.next()\n\n if (Type.equals(token.type, Type.break)) {\n return BREAK\n }\n\n if (token.type.terminal) {\n return token.value\n }\n\n if (Type.equals(token.type, Type.array)) {\n return tokenToArray(token, tokeniser, options)\n }\n\n if (Type.equals(token.type, Type.map)) {\n return tokenToMap(token, tokeniser, options)\n }\n\n if (Type.equals(token.type, Type.tag)) {\n if (options.tags && typeof options.tags[token.value] === 'function') {\n const decodeControl = createTagDecodeControl(tokeniser, options)\n const result = options.tags[token.value](decodeControl)\n if (!decodeControl._called) {\n throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)\n }\n return result\n }\n throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)\n }\n throw new Error('unsupported')\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {[any, Uint8Array]}\n */\nfunction decodeFirst (data, options) {\n if (!(data instanceof Uint8Array)) {\n throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)\n }\n options = Object.assign({}, defaultDecodeOptions, options)\n // Convert Buffer to plain Uint8Array for faster slicing in decode path\n const u8aData = asU8A(data)\n const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)\n const decoded = tokensToObject(tokeniser, options)\n if (decoded === DONE) {\n throw new Error(`${decodeErrPrefix} did not find any content to decode`)\n }\n if (decoded === BREAK) {\n throw new Error(`${decodeErrPrefix} got unexpected break`)\n }\n return [decoded, data.subarray(tokeniser.pos())]\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {any}\n */\nfunction decode (data, options) {\n const [decoded, remainder] = decodeFirst(data, options)\n if (remainder.length > 0) {\n throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)\n }\n return decoded\n}\n\nexport { Tokeniser, tokensToObject, decode, decodeFirst }\n","/**\n * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl\n * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder\n */\n\n/**\n * A wrapper class for representing a CBOR tag with an arbitrary nested value.\n *\n * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit\n * a CBOR tag header followed by the encoded form of `value`, and it can be\n * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)\n * to round-trip a tag through decode without losing the tag number.\n *\n * Use `Tagged` for one-off tag handling where defining a dedicated\n * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when\n * wrapping a structure in a single application-specific tag (COSE, dCBOR\n * envelopes, etc.).\n *\n * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer\n * a dedicated `typeEncoders` entry instead.\n */\nexport class Tagged {\n /**\n * @param {number} tag - CBOR tag number, a non-negative integer\n * @param {any} value - The value to be tagged; encoded recursively\n */\n constructor (tag, value) {\n if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {\n throw new TypeError('Tagged: tag must be a non-negative integer')\n }\n this.tag = tag\n this.value = value\n }\n\n /**\n * Build a tag decoder for use in `decode()`'s `tags` option that returns the\n * decoded content wrapped in a `Tagged` instance, preserving the tag number\n * for the caller to inspect.\n *\n * @param {number} tag - The CBOR tag number this decoder will be registered for\n * @returns {TaggedTagDecoder}\n *\n * @example\n * import { decode, Tagged } from 'cborg'\n * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })\n * // value instanceof Tagged; value.tag === 16\n */\n static decoder (tag) {\n return (decode) => new Tagged(tag, decode())\n }\n\n /**\n * Build a `tags` option for `decode()` that wraps each listed tag number in\n * a `Tagged` instance, preserving those tags through decode without\n * registering a dedicated decoder per tag.\n *\n * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve\n * @returns {{[tagNumber: number]: TaggedTagDecoder}}\n *\n * @example\n * import { decode, Tagged } from 'cborg'\n * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })\n */\n static preserve (...tagNumbers) {\n /** @type {{[tagNumber: number]: TaggedTagDecoder}} */\n const tags = {}\n for (const tag of tagNumbers) {\n tags[tag] = Tagged.decoder(tag)\n }\n return tags\n }\n}\n\n// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'\n// for instances, allowing the default Tagged typeEncoder to match.\nObject.defineProperty(Tagged.prototype, Symbol.toStringTag, {\n value: 'Tagged'\n})\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\nimport {\n decode as cborgDecode,\n encodeInto as cborgEncodeInto,\n Token,\n Tokenizer,\n Type,\n} from \"cborg\";\nimport type { Encodable } from \"../cbor.js\";\n\n/** Decodes text keeping a leading U+FEFF, which a default TextDecoder drops. */\nconst bomPreservingDecoder = new TextDecoder(\"utf-8\", { ignoreBOM: true });\n\n/** Encodes text into fresh arrays, never into a pool shared with other code. */\nconst textEncoder = new TextEncoder();\n\n/**\n * Tokenizer that keeps a leading byte order mark in text strings. cborg's own\n * decoder drops it, which would hand back a different string than the one\n * the bytes hold.\n */\nclass TextTokenizer extends Tokenizer {\n next(): Token {\n const start = this.pos();\n const token = super.next();\n if (token.type === Type.string) {\n // The header is one byte, plus 1, 2, 4 or 8 length bytes past minor 23\n const minor = this.data[start] & 0x1f;\n const header = minor < 24 ? 1 : 1 + (1 << (minor - 24));\n const text = this.data.subarray(start + header, this.pos());\n if (text[0] === 0xef && text[1] === 0xbb && text[2] === 0xbf) {\n token.value = bomPreservingDecoder.decode(text);\n }\n }\n return token;\n }\n}\n\n/**\n * Decodes bytes the Rust validator already checked into what cborg makes of\n * them, maps as `Map`. Decoded byte strings are copies, never views into the\n * input.\n *\n * @internal\n */\nexport function parse(data: Uint8Array): unknown {\n // cborg copies byte strings out with slice(), which on a Node Buffer\n // returns a view, so decode from a plain view over the same bytes\n const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n\n // A custom tokenizer does not get cborg's decode defaults, so the one for\n // 64-bit integers is set here explicitly\n const options = {\n allowBigInt: true,\n useMaps: true,\n rejectDuplicateMapKeys: true,\n };\n return cborgDecode(bytes, {\n ...options,\n tokenizer: new TextTokenizer(bytes, options),\n }) as unknown;\n}\n\n/**\n * Reports whether a string is well-formed UTF-16. A lone surrogate has no\n * UTF-8 form, and encoding it would silently turn it into U+FFFD.\n */\nfunction isWellFormed(text: string): boolean {\n for (let i = 0; i < text.length; i++) {\n const unit = text.charCodeAt(i);\n if (unit >= 0xd800 && unit <= 0xdbff) {\n const next = text.charCodeAt(i + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) {\n return false;\n }\n i++;\n } else if (unit >= 0xdc00 && unit <= 0xdfff) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Serializes a value bound to its codec into the bytes the WASM boundary\n * takes, canonical by cborg's ordering and verified again on the Rust side.\n *\n * cborg's own encode reuses one writer across all callers and can hand out\n * views into it, exposing earlier outputs through their buffer. Encoding into\n * a buffer owned here keeps plaintext out of that shared writer. Text is\n * encoded here too, as cborg would draw it from Node's shared Buffer pool.\n * Every scratch buffer and text encoding is wiped before it is dropped.\n *\n * @internal\n */\nexport function serialize<T>(item: Encodable<T>): Uint8Array {\n const value = item.codec.encode(item.value);\n\n const texts: Uint8Array[] = [];\n const options = {\n typeEncoders: {\n string: (text: string) => {\n if (!isWellFormed(text)) {\n throw new Error(\"text is not well-formed, it holds a lone surrogate\");\n }\n const token = new Token(Type.string, text);\n token.encodedBytes = textEncoder.encode(text);\n texts.push(token.encodedBytes);\n return token;\n },\n },\n };\n try {\n for (let size = 256; ; size *= 2) {\n const scratch = new Uint8Array(size);\n try {\n const { written } = cborgEncodeInto(value, scratch, options);\n return scratch.slice(0, written);\n } catch (err) {\n if (\n !(err instanceof Error) ||\n !err.message.includes(\"destination buffer is too small\")\n ) {\n throw err;\n }\n } finally {\n scratch.fill(0);\n }\n }\n } finally {\n for (const text of texts) {\n text.fill(0);\n }\n }\n}\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * Typed codecs over the restricted CBOR type system used across Dark Bio.\n *\n * https://datatracker.ietf.org/doc/html/rfc8949\n *\n * Only a minimal subset of CBOR is supported: booleans, null, 64-bit\n * integers, text strings, byte strings, arrays and maps with integer keys. The\n * encoding is deterministic (RFC 8949 Section 4.2.1). Integers take their\n * shortest form, map keys are sorted by their encoded bytes, and there are no\n * indefinite lengths, floats or tags.\n *\n * A codec declares the shape of a value the way a Rust type deriving `Cbor`\n * does. Values are bound to their codec before they are encoded, and bytes\n * before they are decoded. The `cose` and `cwt` functions take them the same\n * way. {@link encode} and {@link decode} reject any encoding that breaks the\n * rules above. The cborg library handles the bytes, so a codec converts to and\n * from what cborg takes, such as a `Map` for a map.\n *\n * @example\n * ```ts\n * import { cbor } from \"@darkbio/crypto\";\n *\n * const Triple = cbor.tuple(cbor.uint, cbor.text, cbor.bytes);\n * const bytes = await cbor.encode(Triple.value([1n, \"two\", new Uint8Array([3])]));\n * // bytes holds 83 01 63 74 77 6f 41 03 in hex\n *\n * const [a, b, c] = await cbor.decode(Triple.bytes(bytes));\n * console.log(a, b, c); // 1n two Uint8Array(1) [ 3 ]\n * ```\n *\n * @module\n */\n\nimport { cbor_verify } from \"./wasm/darkbio_crypto_wasm.js\";\nimport { parse, serialize } from \"./internal/cborg.js\";\nimport { ensureInit } from \"./internal/init.js\";\nimport { U64_MAX } from \"./internal/limits.js\";\n\n/** A value bound to the codec that encodes it. */\nexport interface Encodable<T> {\n /** The codec that encodes the value. */\n readonly codec: Codec<T>;\n /** The value to encode. */\n readonly value: T;\n}\n\n/** Bytes bound to the codec that decodes them. */\nexport interface Decodable<T> {\n /** The codec that decodes the bytes. */\n readonly codec: Codec<T>;\n /** The CBOR bytes to decode. */\n readonly bytes: Uint8Array;\n}\n\n/**\n * A codec between a value of type T and the representation cborg encodes and\n * decodes. Both directions throw a {@link CodecError} on a value of the wrong\n * shape.\n */\nexport interface Codec<T> {\n /** Converts a value into what cborg encodes, checking its shape. */\n encode(value: T): unknown;\n /** Converts what cborg decoded into a value, checking its shape. */\n decode(value: unknown): T;\n /** Binds a value to this codec for encoding. */\n value(value: T): Encodable<T>;\n /** Binds bytes to this codec for decoding. */\n bytes(data: Uint8Array): Decodable<T>;\n}\n\n/** A required field of a map, a codec at an integer key. */\nexport interface Field<T> {\n /** The integer key of the field in the map. */\n readonly key: number;\n /** The codec of the field's value. */\n readonly codec: Codec<T>;\n /** Marks the field as required. */\n readonly required: true;\n}\n\n/** An optional field of a map, absent from the map when undefined. */\nexport interface OptionalField<T> {\n /** The integer key of the field in the map. */\n readonly key: number;\n /** The codec of the field's value. */\n readonly codec: Codec<T>;\n /** Marks the field as optional. */\n readonly required: false;\n}\n\n/** The fields of a map codec, by name. */\nexport type Fields = Record<string, Field<unknown> | OptionalField<unknown>>;\n\n/** The value type of a map codec, required fields present and optional ones optional. */\nexport type Values<F extends Fields> = {\n [K in keyof F as F[K] extends Field<unknown> ? K : never]: F[K] extends Field<\n infer T\n >\n ? T\n : never;\n} & {\n [\n K in keyof F as F[K] extends OptionalField<unknown> ? K : never\n ]?: F[K] extends OptionalField<infer T> ? T : never;\n};\n\n/** The item codecs of a tuple codec, one per position of the value types. */\nexport type Codecs<T extends unknown[]> = { [I in keyof T]: Codec<T[I]> };\n\n/**\n * A value of the wrong shape for a codec. The path names where in the value\n * the mismatch is, array items as `[i]` and map fields as `.name`, empty at\n * the top.\n */\nexport class CodecError extends Error {\n /** What is wrong with the value. */\n readonly reason: string;\n /** Where in the value the mismatch is, empty at the top. */\n readonly path: string;\n\n /**\n * Creates an error for a value of the wrong shape.\n *\n * @param reason - What is wrong with the value\n * @param path - Where in the value the mismatch is, empty at the top\n */\n constructor(reason: string, path = \"\") {\n super(path === \"\" ? reason : `${reason} at ${path}`);\n this.name = \"CodecError\";\n this.reason = reason;\n this.path = path;\n }\n}\n\n/** Runs a step of a codec, prefixing the path of a failure inside it. */\nfunction within<T>(segment: string, run: () => T): T {\n try {\n return run();\n } catch (err) {\n if (err instanceof CodecError) {\n throw new CodecError(err.reason, segment + err.path);\n }\n throw err;\n }\n}\n\n/**\n * Builds a codec from its two directions, adding the value and bytes bindings.\n * Both directions should throw a {@link CodecError} on a value of the wrong\n * shape.\n *\n * @example\n * ```ts\n * import { cbor } from \"@darkbio/crypto\";\n *\n * // A date carried as whole seconds since the Unix epoch\n * const date = cbor.codec<Date>(\n * (value) => cbor.uint.encode(BigInt(Math.floor(value.getTime() / 1000))),\n * (value) => new Date(Number(cbor.uint.decode(value)) * 1000),\n * );\n * const bytes = await cbor.encode(date.value(new Date(\"2026-01-01T00:00:00Z\")));\n * console.log(await cbor.decode(date.bytes(bytes))); // 2026-01-01T00:00:00.000Z\n * ```\n *\n * @param encode - Converts a value into what cborg encodes\n * @param decode - Converts what cborg decoded into a value\n * @returns The codec\n */\nexport function codec<T>(\n encode: (value: T) => unknown,\n decode: (value: unknown) => T,\n): Codec<T> {\n const self: Codec<T> = {\n encode,\n decode,\n value: (value) => ({ codec: self, value }),\n bytes: (data) => ({ codec: self, bytes: data }),\n };\n return self;\n}\n\n/** Builds a codec whose two directions share one check. */\nfunction primitive<T>(\n check: (value: unknown) => value is T,\n reason: string,\n): Codec<T> {\n const guard = (value: unknown): T => {\n if (!check(value)) {\n throw new CodecError(reason);\n }\n return value;\n };\n return codec(guard, guard);\n}\n\nconst I64_MIN = -(1n << 63n);\nconst I64_MAX = (1n << 63n) - 1n;\n\n/** Reads an integer cborg produced, a number within the safe range or a bigint beyond it. */\nfunction integer(value: unknown, reason: string): bigint {\n if (typeof value === \"number\" && Number.isSafeInteger(value)) {\n return BigInt(value);\n }\n if (typeof value === \"bigint\") {\n return value;\n }\n throw new CodecError(reason);\n}\n\n/** A boolean. */\nexport const bool: Codec<boolean> = primitive(\n (value): value is boolean => typeof value === \"boolean\",\n \"not a boolean\",\n);\n\n/** Null, the counterpart of Rust's `cbor::Null` and of a `None` option. */\nexport const nil: Codec<null> = primitive(\n (value): value is null => value === null,\n \"not null\",\n);\n\n/**\n * A UTF-8 text string. Decoding keeps every character, a leading U+FEFF\n * included. Encoding rejects a string with a lone surrogate, since it has no\n * UTF-8 form.\n */\nexport const text: Codec<string> = primitive(\n (value): value is string => typeof value === \"string\",\n \"not text\",\n);\n\n/** A byte string. */\nexport const bytes: Codec<Uint8Array> = primitive(\n (value): value is Uint8Array => value instanceof Uint8Array,\n \"not bytes\",\n);\n\n/**\n * Anything, passed through as cborg decoded it, the counterpart of\n * `cbor::Raw`. The value is not checked against any shape, but {@link encode}\n * and {@link decode} still check its encoding.\n */\nexport const raw: Codec<unknown> = codec(\n (value) => value,\n (value) => value,\n);\n\n/** An unsigned 64-bit integer, a bigint in both directions. */\nexport const uint: Codec<bigint> = codec(\n (value) => {\n if (typeof value !== \"bigint\" || value < 0n || value > U64_MAX) {\n throw new CodecError(\"not an unsigned 64 bit integer\");\n }\n return value;\n },\n (value) => {\n const parsed = integer(value, \"not an unsigned 64 bit integer\");\n if (parsed < 0n || parsed > U64_MAX) {\n throw new CodecError(\"not an unsigned 64 bit integer\");\n }\n return parsed;\n },\n);\n\n/** A signed 64-bit integer, a bigint in both directions. */\nexport const int: Codec<bigint> = codec(\n (value) => {\n if (typeof value !== \"bigint\" || value < I64_MIN || value > I64_MAX) {\n throw new CodecError(\"not a signed 64 bit integer\");\n }\n return value;\n },\n (value) => {\n const parsed = integer(value, \"not a signed 64 bit integer\");\n if (parsed < I64_MIN || parsed > I64_MAX) {\n throw new CodecError(\"not a signed 64 bit integer\");\n }\n return parsed;\n },\n);\n\n/**\n * A value or null, the counterpart of `Option<T>` in an array or as a\n * nullable map field.\n *\n * @param item - The codec of the value when it is not null\n * @returns The codec\n */\nexport function nullable<T>(item: Codec<T>): Codec<T | null> {\n return codec(\n (value) => (value === null ? null : item.encode(value)),\n (value) => (value === null ? null : item.decode(value)),\n );\n}\n\n/**\n * A member of a set of small integers, the counterpart of a Rust enum encoded\n * as its discriminant.\n *\n * @param values - The integers the value may take\n * @returns The codec\n */\nexport function enumeration<E extends number>(values: readonly E[]): Codec<E> {\n const members = new Set<number>(values);\n const guard = (value: unknown): E => {\n if (typeof value !== \"number\" || !members.has(value)) {\n throw new CodecError(\"not a member of the enumeration\");\n }\n return value as E;\n };\n return codec(guard, guard);\n}\n\n/**\n * An array of any length of one kind of item, the counterpart of `Array<T>`.\n *\n * @param item - The codec of every item\n * @returns The codec\n */\nexport function array<T>(item: Codec<T>): Codec<T[]> {\n return codec(\n (value) => {\n if (!Array.isArray(value)) {\n throw new CodecError(\"not an array\");\n }\n return value.map((element: T, i) =>\n within(`[${i}]`, () => item.encode(element)),\n );\n },\n (value) => {\n if (!Array.isArray(value)) {\n throw new CodecError(\"not an array\");\n }\n return value.map((element: unknown, i) =>\n within(`[${i}]`, () => item.decode(element)),\n );\n },\n );\n}\n\n/**\n * An array of a fixed length with an item codec per position, the counterpart\n * of a tuple or a struct with `#[cbor(array)]`.\n *\n * @param items - The codec of each item, in order\n * @returns The codec\n */\nexport function tuple<T extends unknown[]>(...items: Codecs<T>): Codec<T> {\n const codecs: Codec<unknown>[] = items;\n return codec(\n (value) => {\n if (!Array.isArray(value) || value.length !== codecs.length) {\n throw new CodecError(`not an array of ${codecs.length}`);\n }\n return codecs.map((item, i) =>\n within(`[${i}]`, () => item.encode(value[i])),\n );\n },\n (value) => {\n if (!Array.isArray(value) || value.length !== codecs.length) {\n throw new CodecError(`not an array of ${codecs.length}`);\n }\n return codecs.map((item, i) =>\n within(`[${i}]`, () => item.decode((value as unknown[])[i])),\n ) as T;\n },\n );\n}\n\n/**\n * Declares a required map field.\n *\n * @param key - The integer key of the field in the map\n * @param codec - The codec of the field's value\n * @returns The field\n * @throws CodecError if the key is not a safe integer\n */\nexport function field<T>(key: number, codec: Codec<T>): Field<T> {\n if (!Number.isSafeInteger(key)) {\n throw new CodecError(\"map key is not an integer\");\n }\n return { key, codec, required: true };\n}\n\n/**\n * Declares a map field that may be absent, the counterpart of an\n * `Option<T>` field. The field is left out of the map when its value is\n * undefined.\n *\n * @param field - The field to make optional\n * @returns The optional field\n */\nexport function optional<T>(field: Field<T>): OptionalField<T> {\n return { key: field.key, codec: field.codec, required: false };\n}\n\n/**\n * An integer-keyed map with exactly the declared fields, the counterpart of\n * a struct with `#[cbor(key = N)]` fields. Both ways, a field the map does\n * not declare and a required field missing are refused, as is a key that is\n * not an integer. Only own properties of a value count as its fields.\n *\n * @example\n * ```ts\n * import { cbor } from \"@darkbio/crypto\";\n *\n * const Bar = cbor.map({\n * x: cbor.field(1, cbor.uint), // required\n * y: cbor.optional(cbor.field(2, cbor.bytes)), // omitted when undefined\n * z: cbor.field(3, cbor.nullable(cbor.uint)), // always present, a value or null\n * });\n * const bytes = await cbor.encode(Bar.value({ x: 7n, z: null }));\n * // bytes holds a2 01 07 03 f6 in hex\n *\n * console.log(await cbor.decode(Bar.bytes(bytes))); // { x: 7n, z: null }\n * ```\n *\n * @param fields - The fields of the map, by name\n * @returns The codec\n * @throws CodecError if two fields share a key\n */\nexport function map<F extends Fields>(fields: F): Codec<Values<F>> {\n const entries = Object.entries(fields).map(\n ([name, field]) => [name, { ...field }] as const,\n );\n const declared = new Set(entries.map(([name]) => name));\n const names = new Map<number, string>();\n for (const [name, field] of entries) {\n if (names.has(field.key)) {\n throw new CodecError(`map key ${field.key} declared twice`);\n }\n names.set(field.key, name);\n }\n return codec(\n (value) => {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new CodecError(\"not an object\");\n }\n const record = value as Record<string, unknown>;\n for (const name of Object.keys(record)) {\n if (!declared.has(name)) {\n throw new CodecError(`unexpected field ${name}`);\n }\n }\n const encoded = new Map<number, unknown>();\n for (const [name, field] of entries) {\n const item = Object.hasOwn(record, name) ? record[name] : undefined;\n if (item === undefined) {\n if (field.required) {\n throw new CodecError(`missing field ${name}`);\n }\n continue;\n }\n encoded.set(\n field.key,\n within(`.${name}`, () => field.codec.encode(item)),\n );\n }\n return encoded;\n },\n (value) => {\n if (!(value instanceof Map)) {\n throw new CodecError(\"not a map\");\n }\n const decoded: [string, unknown][] = [];\n for (const key of (value as Map<unknown, unknown>).keys()) {\n if (typeof key !== \"number\" || !Number.isSafeInteger(key)) {\n throw new CodecError(\"map key is not an integer\");\n }\n if (!names.has(key)) {\n throw new CodecError(`unexpected key ${key}`);\n }\n }\n for (const [name, field] of entries) {\n if (!(value as Map<unknown, unknown>).has(field.key)) {\n if (field.required) {\n throw new CodecError(`missing key ${field.key}`);\n }\n continue;\n }\n decoded.push([\n name,\n within(`.${name}`, () =>\n field.codec.decode((value as Map<unknown, unknown>).get(field.key)),\n ),\n ]);\n }\n return Object.fromEntries(decoded) as Values<F>;\n },\n );\n}\n\n/**\n * Encodes a value bound to its codec into deterministic CBOR.\n *\n * @param item - The value and the codec to encode it with\n * @returns The CBOR bytes\n * @throws CodecError on a value of the wrong shape\n * @throws If the encoding falls outside the restricted type system, such as a\n * float in a raw value or text with a lone surrogate\n */\nexport async function encode<T>(item: Encodable<T>): Promise<Uint8Array> {\n const data = serialize(item);\n await ensureInit();\n cbor_verify(data);\n return data;\n}\n\n/**\n * Decodes deterministic CBOR bound to its codec. The bytes must pass\n * {@link verify} before anything is decoded.\n *\n * @param item - The bytes and the codec to decode them with\n * @returns The decoded value\n * @throws If the bytes are not valid restricted CBOR\n * @throws CodecError on bytes of the wrong shape\n */\nexport async function decode<T>(item: Decodable<T>): Promise<T> {\n await ensureInit();\n cbor_verify(item.bytes);\n return item.codec.decode(parse(item.bytes));\n}\n\n/**\n * Verifies that data is exactly one complete CBOR item under the restricted\n * type system.\n *\n * It checks UTF-8 text, deterministic integer and length encodings, integer\n * map keys in order without duplicates, and the nesting limit. It does not\n * check application-specific schemas or values. The `cose` and `cwt`\n * functions apply the same check to every payload they sign, embed or return.\n *\n * @param data - The CBOR bytes to validate\n * @throws If the data is not valid restricted CBOR\n */\nexport async function verify(data: Uint8Array): Promise<void> {\n await ensureInit();\n cbor_verify(data);\n}\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * Renders bytes as lowercase hex.\n *\n * @internal\n */\nexport function toHex(data: Uint8Array): string {\n return Array.from(data, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\",\n );\n}\n\n/**\n * Reports whether two byte arrays hold the same bytes.\n *\n * @internal\n */\nexport function equal(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * Composite ML-DSA-65 + Ed25519 digital signatures.\n *\n * https://datatracker.ietf.org/doc/html/draft-ietf-lamps-pq-composite-sigs\n *\n * A key signs a message with ML-DSA-65 and Ed25519 at once, and a signature\n * verifies only if both halves do. Keys and signatures round-trip through\n * fixed-size byte arrays. Keys also support PEM serialization.\n *\n * @example\n * ```ts\n * import { xdsa } from \"@darkbio/crypto\";\n *\n * const secret = await xdsa.SecretKey.generate();\n * const verifier = secret.publicKey();\n * const text = new TextEncoder();\n *\n * const signature = secret.sign(text.encode(\"hello\"));\n * console.log(verifier.verify(text.encode(\"hello\"), signature)); // true\n * console.log(verifier.verify(text.encode(\"tampered\"), signature)); // false\n *\n * const restored = await xdsa.PublicKey.fromPem(verifier.toPem());\n * console.log(restored.fingerprint().equals(verifier.fingerprint())); // true\n * ```\n *\n * @module\n */\n\nimport {\n xdsa_secret_key_size,\n xdsa_public_key_size,\n xdsa_signature_size,\n xdsa_fingerprint_size,\n XdsaSecretKey as WasmSecretKey,\n XdsaPublicKey as WasmPublicKey,\n XdsaSignature as WasmSignature,\n XdsaFingerprint as WasmFingerprint,\n} from \"./wasm/darkbio_crypto_wasm.js\";\nimport { ensureInit, requireInit } from \"./internal/init.js\";\nimport { codec, CodecError, type Codec } from \"./cbor.js\";\nimport { equal, toHex } from \"./internal/bytes.js\";\n\n/**\n * Size of the secret key seed in bytes, the 32-byte ML-DSA-65 seed followed by\n * the 32-byte Ed25519 seed.\n */\nexport const SECRET_KEY_SIZE = 64;\n\n/**\n * Size of the public key in bytes, the 1952-byte ML-DSA-65 key followed by the\n * 32-byte Ed25519 key.\n */\nexport const PUBLIC_KEY_SIZE = 1984;\n\n/**\n * Size of a signature in bytes, the 3309-byte ML-DSA-65 signature followed by\n * the 64-byte Ed25519 signature.\n */\nexport const SIGNATURE_SIZE = 3373;\n\n/** Size of a key fingerprint in bytes. */\nexport const FINGERPRINT_SIZE = 32;\n\n/**\n * Returns the sizes in bytes as the Rust library defines them, the same values\n * as the constants of this module.\n */\nexport async function sizes(): Promise<{\n secretKey: number;\n publicKey: number;\n signature: number;\n fingerprint: number;\n}> {\n await ensureInit();\n return {\n secretKey: xdsa_secret_key_size(),\n publicKey: xdsa_public_key_size(),\n signature: xdsa_signature_size(),\n fingerprint: xdsa_fingerprint_size(),\n };\n}\n\n/** A 256-bit unique identifier for an xDSA key. */\nexport class Fingerprint {\n /** @internal */\n readonly _wasm: WasmFingerprint;\n\n private constructor(inner: WasmFingerprint) {\n this._wasm = inner;\n }\n\n /** @internal */\n static _fromWasm(inner: WasmFingerprint): Fingerprint {\n return new Fingerprint(inner);\n }\n\n /**\n * Creates a fingerprint from a 32-byte array.\n *\n * @throws If `bytes` is not 32 bytes long\n */\n static async fromBytes(bytes: Uint8Array): Promise<Fingerprint> {\n await ensureInit();\n return new Fingerprint(WasmFingerprint.from_bytes(bytes));\n }\n\n /** Converts a fingerprint into a 32-byte array. */\n toBytes(): Uint8Array {\n return this._wasm.to_bytes();\n }\n\n /** Renders a fingerprint as lowercase hex. */\n toHex(): string {\n return toHex(this.toBytes());\n }\n\n /** Reports whether another fingerprint is the same. */\n equals(other: Fingerprint): boolean {\n return equal(this.toBytes(), other.toBytes());\n }\n}\n\n/** An xDSA signature, an ML-DSA-65 signature paired with an Ed25519 one. */\nexport class Signature {\n /** @internal */\n readonly _wasm: WasmSignature;\n\n private constructor(inner: WasmSignature) {\n this._wasm = inner;\n }\n\n /** @internal */\n static _fromWasm(inner: WasmSignature): Signature {\n return new Signature(inner);\n }\n\n /**\n * Creates a signature from a 3373-byte array. The halves are only checked\n * when the signature is verified.\n *\n * @throws If `bytes` is not 3373 bytes long\n */\n static async fromBytes(bytes: Uint8Array): Promise<Signature> {\n await ensureInit();\n return new Signature(WasmSignature.from_bytes(bytes));\n }\n\n /** Converts a signature into a 3373-byte array. */\n toBytes(): Uint8Array {\n return this._wasm.to_bytes();\n }\n}\n\n/**\n * An xDSA public key, an ML-DSA-65 key paired with an Ed25519 key, for\n * verifying quantum resistant digital signatures.\n */\nexport class PublicKey {\n /** @internal */\n readonly _wasm: WasmPublicKey;\n\n private constructor(inner: WasmPublicKey) {\n this._wasm = inner;\n }\n\n /** @internal */\n static _fromWasm(inner: WasmPublicKey): PublicKey {\n return new PublicKey(inner);\n }\n\n /**\n * Creates a public key from a 1984-byte array.\n *\n * @throws If `bytes` is not 1984 bytes long or not a valid composite key\n */\n static async fromBytes(bytes: Uint8Array): Promise<PublicKey> {\n await ensureInit();\n return new PublicKey(WasmPublicKey.from_bytes(bytes));\n }\n\n /**\n * Parses a PEM string into a public key. The input must be exactly one\n * `PUBLIC KEY` block, with no leading whitespace, strict base64 and LF or\n * CRLF line endings throughout.\n *\n * @throws If the PEM is malformed or holds another kind of key\n */\n static async fromPem(pem: string): Promise<PublicKey> {\n await ensureInit();\n return new PublicKey(WasmPublicKey.from_pem(pem));\n }\n\n /** Converts a public key into a 1984-byte array. */\n toBytes(): Uint8Array {\n return this._wasm.to_bytes();\n }\n\n /** Serializes a public key into a `PUBLIC KEY` PEM block with LF line endings. */\n toPem(): string {\n return this._wasm.to_pem();\n }\n\n /** Reports whether another public key is the same. */\n equals(other: PublicKey): boolean {\n return equal(this.toBytes(), other.toBytes());\n }\n\n /** Returns a 256-bit unique identifier for this key. */\n fingerprint(): Fingerprint {\n return Fingerprint._fromWasm(this._wasm.fingerprint());\n }\n\n /**\n * Verifies a digital signature of the message. Both the ML-DSA-65 and the\n * Ed25519 halves must verify.\n *\n * @param message - The signed message\n * @param signature - The signature to check\n * @returns True if the signature is valid for this key and message, false\n * otherwise\n */\n verify(message: Uint8Array, signature: Signature): boolean {\n return this._wasm.verify(message, signature._wasm);\n }\n}\n\n/**\n * An xDSA secret key, an ML-DSA-65 key paired with an Ed25519 key, for\n * creating quantum resistant digital signatures. The key stays in WASM memory\n * unless {@link SecretKey.toBytes} or {@link SecretKey.toPem} copies it out.\n */\nexport class SecretKey {\n private inner: WasmSecretKey | undefined;\n\n private constructor(inner: WasmSecretKey) {\n this.inner = inner;\n }\n\n /** @internal */\n get _wasm(): WasmSecretKey {\n if (this.inner === undefined) {\n throw new Error(\"secret key used after dispose\");\n }\n return this.inner;\n }\n\n /** Generates a new, random secret key. */\n static async generate(): Promise<SecretKey> {\n await ensureInit();\n return new SecretKey(WasmSecretKey.generate());\n }\n\n /**\n * Creates a secret key from a 64-byte seed.\n *\n * @throws If `bytes` is not 64 bytes long\n */\n static async fromBytes(bytes: Uint8Array): Promise<SecretKey> {\n await ensureInit();\n return new SecretKey(WasmSecretKey.from_bytes(bytes));\n }\n\n /**\n * Parses a PEM string into a secret key. The input must be exactly one\n * `PRIVATE KEY` block, with no leading whitespace, strict base64 and LF or\n * CRLF line endings throughout.\n *\n * @throws If the PEM is malformed or holds another kind of key\n */\n static async fromPem(pem: string): Promise<SecretKey> {\n await ensureInit();\n return new SecretKey(WasmSecretKey.from_pem(pem));\n }\n\n /** Converts a secret key into its 64-byte seed. */\n toBytes(): Uint8Array {\n return this._wasm.to_bytes();\n }\n\n /** Serializes a secret key into a `PRIVATE KEY` PEM block with LF line endings. */\n toPem(): string {\n return this._wasm.to_pem();\n }\n\n /** Retrieves the public counterpart of the secret key. */\n publicKey(): PublicKey {\n return PublicKey._fromWasm(this._wasm.public_key());\n }\n\n /** Returns a 256-bit unique identifier for this key, the same as its public key's. */\n fingerprint(): Fingerprint {\n return Fingerprint._fromWasm(this._wasm.fingerprint());\n }\n\n /**\n * Creates a digital signature of the message.\n *\n * @param message - The message to sign\n * @returns The signature\n */\n sign(message: Uint8Array): Signature {\n return Signature._fromWasm(this._wasm.sign(message));\n }\n\n /**\n * Wipes the secret key held in WASM memory. Every later use of this key\n * throws, and disposing it again does nothing. Copies already exported, such\n * as by {@link SecretKey.toBytes}, are not affected. Without a dispose, the\n * key is only wiped if the garbage collector finalizes it, which is not\n * guaranteed.\n */\n dispose(): void {\n const inner = this.inner;\n this.inner = undefined;\n inner?.free();\n }\n}\n\n/** Private COSE algorithm identifier of composite ML-DSA-65 + Ed25519 signatures. */\nexport const ALGORITHM_ID = -70000;\n\n/**\n * Codec of a public key as its 1984 bytes. Decoding throws a\n * {@link CodecError} unless the bytes are a valid key. Calling its decode\n * directly needs any async function of this package to have run first.\n */\nexport const publicKey: Codec<PublicKey> = codec(\n (key) => {\n if (!(key instanceof PublicKey)) {\n throw new CodecError(\"not a public key\");\n }\n return key.toBytes();\n },\n (value) => {\n if (!(value instanceof Uint8Array)) {\n throw new CodecError(\"not a public key\");\n }\n requireInit();\n try {\n return PublicKey._fromWasm(WasmPublicKey.from_bytes(value));\n } catch (err) {\n throw new CodecError(\n `not a public key: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n },\n);\n\n/**\n * Codec of a fingerprint as its 32 bytes. Decoding throws a {@link CodecError}\n * unless the value is 32 bytes. Calling its decode directly needs any async\n * function of this package to have run first.\n */\nexport const fingerprint: Codec<Fingerprint> = codec(\n (print) => {\n if (!(print instanceof Fingerprint)) {\n throw new CodecError(\"not a fingerprint\");\n }\n return print.toBytes();\n },\n (value) => {\n if (!(value instanceof Uint8Array)) {\n throw new CodecError(\"not a fingerprint\");\n }\n requireInit();\n try {\n return Fingerprint._fromWasm(WasmFingerprint.from_bytes(value));\n } catch (err) {\n throw new CodecError(\n `not a fingerprint: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n },\n);\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * X-Wing HPKE encryption.\n *\n * https://datatracker.ietf.org/doc/html/rfc9180\n * https://datatracker.ietf.org/doc/html/draft-connolly-cfrg-xwing-kem\n *\n * Messages are encrypted to a public key with X-Wing, a hybrid of ML-KEM-768\n * and X25519, and sealed with ChaCha20-Poly1305. Encryption and decryption use\n * an application domain, prefixed with `dark-bio-v1:`, which both sides must\n * agree on. The ciphertext also authenticates a second message that must be\n * supplied separately.\n *\n * A {@link Sender} and {@link Receiver} pair shares one encapsulated key across\n * many messages, which must be opened in the order they were sealed. The\n * domain is fixed when the contexts are created.\n *\n * @example\n * ```ts\n * import { xhpke } from \"@darkbio/crypto\";\n *\n * const secret = await xhpke.SecretKey.generate();\n * const text = new TextEncoder();\n * const domain = text.encode(\"example\");\n *\n * const sealed = secret.publicKey().seal(text.encode(\"secret\"), text.encode(\"header\"), domain);\n * const plaintext = secret.open(sealed, text.encode(\"header\"), domain);\n * console.log(new TextDecoder().decode(plaintext)); // secret\n *\n * // A tampered header fails authentication\n * try {\n * secret.open(sealed, text.encode(\"other\"), domain);\n * } catch {\n * console.log(\"rejected\");\n * }\n * ```\n *\n * @example\n * ```ts\n * import { xhpke } from \"@darkbio/crypto\";\n *\n * const secret = await xhpke.SecretKey.generate();\n * const domain = new TextEncoder().encode(\"example\");\n *\n * const { sender, encapKey } = secret.publicKey().newSender(domain);\n * const receiver = secret.newReceiver(encapKey, domain);\n *\n * for (const message of [\"first\", \"second\"]) {\n * const ciphertext = sender.seal(new TextEncoder().encode(message), new Uint8Array());\n * const plaintext = receiver.open(ciphertext, new Uint8Array());\n * console.log(new TextDecoder().decode(plaintext)); // first, then second\n * }\n * ```\n *\n * @module\n */\n\nimport {\n xhpke_secret_key_size,\n xhpke_public_key_size,\n xhpke_encap_key_size,\n xhpke_fingerprint_size,\n XhpkeSecretKey as WasmSecretKey,\n XhpkePublicKey as WasmPublicKey,\n XhpkeFingerprint as WasmFingerprint,\n XhpkeSender as WasmSender,\n XhpkeReceiver as WasmReceiver,\n} from \"./wasm/darkbio_crypto_wasm.js\";\nimport { ensureInit, requireInit } from \"./internal/init.js\";\nimport { codec, CodecError, type Codec } from \"./cbor.js\";\nimport { equal, toHex } from \"./internal/bytes.js\";\n\n/** Size of the secret key seed in bytes. */\nexport const SECRET_KEY_SIZE = 32;\n\n/** Size of the public key in bytes. */\nexport const PUBLIC_KEY_SIZE = 1216;\n\n/**\n * Size of the encapsulated key in bytes, the prefix of every\n * {@link PublicKey.seal} output.\n */\nexport const ENCAP_KEY_SIZE = 1120;\n\n/** Size of a key fingerprint in bytes. */\nexport const FINGERPRINT_SIZE = 32;\n\n/**\n * Returns the sizes in bytes as the Rust library defines them, the same values\n * as the constants of this module.\n */\nexport async function sizes(): Promise<{\n secretKey: number;\n publicKey: number;\n encapKey: number;\n fingerprint: number;\n}> {\n await ensureInit();\n return {\n secretKey: xhpke_secret_key_size(),\n publicKey: xhpke_public_key_size(),\n encapKey: xhpke_encap_key_size(),\n fingerprint: xhpke_fingerprint_size(),\n };\n}\n\n/** A 256-bit unique identifier for an xHPKE key. */\nexport class Fingerprint {\n /** @internal */\n readonly _wasm: WasmFingerprint;\n\n private constructor(inner: WasmFingerprint) {\n this._wasm = inner;\n }\n\n /** @internal */\n static _fromWasm(inner: WasmFingerprint): Fingerprint {\n return new Fingerprint(inner);\n }\n\n /**\n * Creates a fingerprint from a 32-byte array.\n *\n * @throws If `bytes` is not 32 bytes long\n */\n static async fromBytes(bytes: Uint8Array): Promise<Fingerprint> {\n await ensureInit();\n return new Fingerprint(WasmFingerprint.from_bytes(bytes));\n }\n\n /** Converts a fingerprint into a 32-byte array. */\n toBytes(): Uint8Array {\n return this._wasm.to_bytes();\n }\n\n /** Renders a fingerprint as lowercase hex. */\n toHex(): string {\n return toHex(this.toBytes());\n }\n\n /** Reports whether another fingerprint is the same. */\n equals(other: Fingerprint): boolean {\n return equal(this.toBytes(), other.toBytes());\n }\n}\n\n/** An X-Wing public key for encrypting HPKE messages. */\nexport class PublicKey {\n /** @internal */\n readonly _wasm: WasmPublicKey;\n\n private constructor(inner: WasmPublicKey) {\n this._wasm = inner;\n }\n\n /** @internal */\n static _fromWasm(inner: WasmPublicKey): PublicKey {\n return new PublicKey(inner);\n }\n\n /**\n * Creates a public key from a 1216-byte array.\n *\n * @throws If `bytes` is not 1216 bytes long or not a valid X-Wing key\n */\n static async fromBytes(bytes: Uint8Array): Promise<PublicKey> {\n await ensureInit();\n return new PublicKey(WasmPublicKey.from_bytes(bytes));\n }\n\n /**\n * Parses a PEM string into a public key. The input must be exactly one\n * `PUBLIC KEY` block, with no leading whitespace, strict base64 and LF or\n * CRLF line endings throughout.\n *\n * @throws If the PEM is malformed or holds another kind of key\n */\n static async fromPem(pem: string): Promise<PublicKey> {\n await ensureInit();\n return new PublicKey(WasmPublicKey.from_pem(pem));\n }\n\n /** Converts a public key into a 1216-byte array. */\n toBytes(): Uint8Array {\n return this._wasm.to_bytes();\n }\n\n /** Serializes a public key into a `PUBLIC KEY` PEM block with LF line endings. */\n toPem(): string {\n return this._wasm.to_pem();\n }\n\n /** Reports whether another public key is the same. */\n equals(other: PublicKey): boolean {\n return equal(this.toBytes(), other.toBytes());\n }\n\n /**\n * Returns a 256-bit unique identifier for this key, the SHA-256 hash of the\n * public key bytes.\n */\n fingerprint(): Fingerprint {\n return Fingerprint._fromWasm(this._wasm.fingerprint());\n }\n\n /**\n * Creates an HPKE sender context for multi-message encryption to this\n * public key. Messages it seals must be opened in order by a\n * {@link Receiver} created from the returned encapsulated key.\n *\n * HPKE runs in base mode, which does not authenticate the sender. The\n * recipient cannot verify who created the context.\n *\n * @param domain - Application domain, fixed for every message of the context\n * @returns The stateful sender and the 1120-byte encapsulated key, which\n * must be transmitted to the recipient\n */\n newSender(domain: Uint8Array): { sender: Sender; encapKey: Uint8Array } {\n const wasmSender = this._wasm.new_sender(domain);\n const encapKey = wasmSender.encap_key();\n return { sender: Sender._fromWasm(wasmSender), encapKey };\n }\n\n /**\n * Encrypts a message to this public key, also authenticating a second\n * message that is not included in the output. Opening it with\n * {@link SecretKey.open} needs the same second message and domain.\n *\n * HPKE runs in base mode, which does not authenticate the sender. The\n * recipient cannot verify who sealed the message.\n *\n * @param msgToSeal - The message to encrypt\n * @param msgToAuth - The message to authenticate but not include\n * @param domain - Application domain, which both sides must agree on\n * @returns The 1120-byte encapsulated key followed by the ciphertext\n */\n seal(\n msgToSeal: Uint8Array,\n msgToAuth: Uint8Array,\n domain: Uint8Array,\n ): Uint8Array {\n return this._wasm.seal(msgToSeal, msgToAuth, domain);\n }\n}\n\n/**\n * An X-Wing secret key for decrypting HPKE messages. The key stays in WASM\n * memory unless {@link SecretKey.toBytes} or {@link SecretKey.toPem} copies it\n * out.\n */\nexport class SecretKey {\n private inner: WasmSecretKey | undefined;\n\n private constructor(inner: WasmSecretKey) {\n this.inner = inner;\n }\n\n /** @internal */\n get _wasm(): WasmSecretKey {\n if (this.inner === undefined) {\n throw new Error(\"secret key used after dispose\");\n }\n return this.inner;\n }\n\n /** Generates a new, random secret key. */\n static async generate(): Promise<SecretKey> {\n await ensureInit();\n return new SecretKey(WasmSecretKey.generate());\n }\n\n /**\n * Creates a secret key from a 32-byte seed.\n *\n * @throws If `bytes` is not 32 bytes long\n */\n static async fromBytes(bytes: Uint8Array): Promise<SecretKey> {\n await ensureInit();\n return new SecretKey(WasmSecretKey.from_bytes(bytes));\n }\n\n /**\n * Parses a PEM string into a secret key. The input must be exactly one\n * `PRIVATE KEY` block, with no leading whitespace, strict base64 and LF or\n * CRLF line endings throughout.\n *\n * @throws If the PEM is malformed or holds another kind of key\n */\n static async fromPem(pem: string): Promise<SecretKey> {\n await ensureInit();\n return new SecretKey(WasmSecretKey.from_pem(pem));\n }\n\n /** Converts a secret key into its 32-byte seed. */\n toBytes(): Uint8Array {\n return this._wasm.to_bytes();\n }\n\n /** Serializes a secret key into a `PRIVATE KEY` PEM block with LF line endings. */\n toPem(): string {\n return this._wasm.to_pem();\n }\n\n /** Retrieves the public counterpart of the secret key. */\n publicKey(): PublicKey {\n return PublicKey._fromWasm(this._wasm.public_key());\n }\n\n /**\n * Returns a 256-bit unique identifier for this key, the SHA-256 hash of the\n * public key bytes.\n */\n fingerprint(): Fingerprint {\n return Fingerprint._fromWasm(this._wasm.fingerprint());\n }\n\n /**\n * Creates an HPKE receiver context for multi-message decryption. Messages\n * must be opened in the order the {@link Sender} sealed them.\n *\n * HPKE runs in base mode, which does not authenticate the sender. The\n * recipient cannot verify who created the context.\n *\n * @param encapKey - The 1120-byte encapsulated key from {@link PublicKey.newSender}\n * @param domain - The same application domain the sender uses\n * @returns The stateful receiver\n * @throws If `encapKey` is not 1120 bytes long or is malformed\n */\n newReceiver(encapKey: Uint8Array, domain: Uint8Array): Receiver {\n return Receiver._fromWasm(this._wasm.new_receiver(encapKey, domain));\n }\n\n /**\n * Decrypts a message sealed to this key and checks the second message it\n * authenticates.\n *\n * HPKE runs in base mode, which does not authenticate the sender. The\n * recipient cannot verify who sealed the message.\n *\n * @param sealed - The 1120-byte encapsulated key followed by the\n * ciphertext, as {@link PublicKey.seal} returns them\n * @param msgToAuth - The same second message used during sealing\n * @param domain - The same application domain used during sealing\n * @returns The decrypted message\n * @throws If the data is malformed, sealed to another key or tampered with,\n * or `msgToAuth` or `domain` differ\n */\n open(\n sealed: Uint8Array,\n msgToAuth: Uint8Array,\n domain: Uint8Array,\n ): Uint8Array {\n return this._wasm.open(sealed, msgToAuth, domain);\n }\n\n /**\n * Wipes the secret key held in WASM memory. Every later use of this key\n * throws, and disposing it again does nothing. Copies already exported, such\n * as by {@link SecretKey.toBytes}, and receivers already created from it are\n * not affected. Without a dispose, the key is only wiped if the garbage\n * collector finalizes it, which is not guaranteed.\n */\n dispose(): void {\n const inner = this.inner;\n this.inner = undefined;\n inner?.free();\n }\n}\n\n/**\n * A stateful HPKE encryption context for multi-message communication, created\n * by {@link PublicKey.newSender}. Each seal uses the next nonce in the\n * sequence, so identical messages encrypt differently. The matching\n * {@link Receiver} must open messages in the order they were sealed.\n */\nexport class Sender {\n private inner: WasmSender | undefined;\n\n private constructor(inner: WasmSender) {\n this.inner = inner;\n }\n\n /** @internal */\n static _fromWasm(inner: WasmSender): Sender {\n return new Sender(inner);\n }\n\n private get wasm(): WasmSender {\n if (this.inner === undefined) {\n throw new Error(\"sender used after dispose\");\n }\n return this.inner;\n }\n\n /**\n * Encrypts a message using the next nonce in the sequence.\n *\n * @param msgToSeal - The message to encrypt\n * @param msgToAuth - The message to authenticate but not include\n * @returns The ciphertext\n */\n seal(msgToSeal: Uint8Array, msgToAuth: Uint8Array): Uint8Array {\n return this.wasm.seal(msgToSeal, msgToAuth);\n }\n\n /**\n * Wipes the keys of this context held in WASM memory. Every later use of the\n * sender throws, and disposing it again does nothing. Without a dispose, the\n * keys are only wiped if the garbage collector finalizes the sender, which is\n * not guaranteed.\n */\n dispose(): void {\n const inner = this.inner;\n this.inner = undefined;\n inner?.free();\n }\n}\n\n/**\n * A stateful HPKE decryption context for multi-message communication, created\n * by {@link SecretKey.newReceiver}. Messages must be opened in the order the\n * {@link Sender} sealed them.\n */\nexport class Receiver {\n private inner: WasmReceiver | undefined;\n\n private constructor(inner: WasmReceiver) {\n this.inner = inner;\n }\n\n /** @internal */\n static _fromWasm(inner: WasmReceiver): Receiver {\n return new Receiver(inner);\n }\n\n private get wasm(): WasmReceiver {\n if (this.inner === undefined) {\n throw new Error(\"receiver used after dispose\");\n }\n return this.inner;\n }\n\n /**\n * Decrypts a message using the next nonce in the sequence.\n *\n * @param msgToOpen - The ciphertext from {@link Sender.seal}\n * @param msgToAuth - The same second message used during sealing\n * @returns The decrypted message\n * @throws If the message is out of order or was tampered with, or\n * `msgToAuth` differs\n */\n open(msgToOpen: Uint8Array, msgToAuth: Uint8Array): Uint8Array {\n return this.wasm.open(msgToOpen, msgToAuth);\n }\n\n /**\n * Wipes the keys of this context held in WASM memory. Every later use of the\n * receiver throws, and disposing it again does nothing. Without a dispose,\n * the keys are only wiped if the garbage collector finalizes the receiver,\n * which is not guaranteed.\n */\n dispose(): void {\n const inner = this.inner;\n this.inner = undefined;\n inner?.free();\n }\n}\n\n/** Private COSE algorithm identifier of X-Wing (ML-KEM-768 + X25519). */\nexport const ALGORITHM_ID = -70001;\n\n/**\n * Codec of a public key as its 1216 bytes. Decoding throws a\n * {@link CodecError} unless the bytes are a valid key. Calling its decode\n * directly needs any async function of this package to have run first.\n */\nexport const publicKey: Codec<PublicKey> = codec(\n (key) => {\n if (!(key instanceof PublicKey)) {\n throw new CodecError(\"not a public key\");\n }\n return key.toBytes();\n },\n (value) => {\n if (!(value instanceof Uint8Array)) {\n throw new CodecError(\"not a public key\");\n }\n requireInit();\n try {\n return PublicKey._fromWasm(WasmPublicKey.from_bytes(value));\n } catch (err) {\n throw new CodecError(\n `not a public key: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n },\n);\n\n/**\n * Codec of a fingerprint as its 32 bytes. Decoding throws a {@link CodecError}\n * unless the value is 32 bytes. Calling its decode directly needs any async\n * function of this package to have run first.\n */\nexport const fingerprint: Codec<Fingerprint> = codec(\n (print) => {\n if (!(print instanceof Fingerprint)) {\n throw new CodecError(\"not a fingerprint\");\n }\n return print.toBytes();\n },\n (value) => {\n if (!(value instanceof Uint8Array)) {\n throw new CodecError(\"not a fingerprint\");\n }\n requireInit();\n try {\n return Fingerprint._fromWasm(WasmFingerprint.from_bytes(value));\n } catch (err) {\n throw new CodecError(\n `not a fingerprint: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n },\n);\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * COSE signing and encryption with xDSA and xHPKE.\n *\n * https://datatracker.ietf.org/doc/html/rfc9052\n * https://datatracker.ietf.org/doc/html/draft-ietf-cose-hpke\n *\n * Signatures are COSE_Sign1 envelopes carrying the signer's fingerprint and a\n * timestamp in the protected header. Encryption is COSE_Encrypt0 around a\n * signed envelope, so every message created by {@link seal} is also signed.\n * Payloads and authenticated messages are values bound to a `cbor` codec.\n * Signing, verification, encryption and decryption use an application domain,\n * prefixed with `dark-bio-v1:`, which both sides must agree on.\n *\n * ## Domain separation and freshness\n *\n * Choose distinct domains for distinct application operations. Domains\n * prevent a message for one purpose from being accepted for another; they do\n * not stop repeated use within the same domain. Verification accepts a\n * signature whose timestamp is at most `maxDriftSecs` seconds in the past or\n * future. An undefined `maxDriftSecs` skips this timestamp check. Applications\n * that require one-time acceptance must also track a message identifier,\n * nonce or challenge to reject replays.\n *\n * ## Wire profile\n *\n * Interoperating implementations must match these Dark Bio conventions:\n *\n * - Envelopes are untagged COSE_Sign1 and COSE_Encrypt0 arrays. CBOR tags are\n * not accepted. Headers are deterministic maps with integer keys.\n * - The private algorithm IDs are -70000 for xDSA and -70001 for xHPKE. The\n * protected `kid` is the appropriate public key's fingerprint. Signatures\n * require the private timestamp header -70002 and name it in `crit`.\n * - For signatures, the Sig_structure external_aad is the CBOR encoding of\n * `[bstr(\"dark-bio-v1:\" || domain), msgToAuth]`. An embedded payload is the\n * CBOR encoding of the caller's value.\n * - For {@link signDetached}, the caller's message is authenticated in that\n * external_aad, while the Sig_structure payload is an empty byte string and\n * the envelope payload is null. A generic COSE detached-payload API that\n * puts the caller's message in the Sig_structure payload must be adapted to\n * this convention.\n * - For encryption, the Enc_structure external_aad is the CBOR encoding of\n * `msgToAuth`, and the complete encoded Enc_structure is the HPKE AAD. HPKE\n * key derivation uses `\"dark-bio-v1:\" || domain` as its info. The X-Wing\n * encapsulated key is carried in unprotected header -4.\n * - The encryption plaintext is the encoded COSE_Sign1 followed by zero bytes,\n * as many as the sender's {@link Padding} policy picks. The signature does\n * not cover them, while the encryption authenticates them. A receiver finds\n * the end of the COSE_Sign1 by decoding it and refuses a nonzero byte after\n * it. It accepts any number of zeros, none included, so a sender can change\n * its policy without its receivers.\n *\n * Here bstr denotes a CBOR byte string and || denotes byte concatenation. The\n * domain and `msgToAuth` are not included in the returned envelope, so both\n * parties must know them or transmit them separately.\n *\n * @example\n * ```ts\n * import { cbor, cose, xdsa, xhpke } from \"@darkbio/crypto\";\n *\n * const signer = await xdsa.SecretKey.generate();\n * const domain = new TextEncoder().encode(\"example\");\n * const context = cbor.text.value(\"context\");\n *\n * // Sign a payload, binding a second message supplied separately\n * const envelope = await cose.sign(cbor.text.value(\"hello\"), context, signer, domain);\n * const payload = await cose.verify(cbor.text.bytes(envelope), context, signer.publicKey(), domain, 60);\n * console.log(payload); // hello\n *\n * // Sign and encrypt to a recipient in one step, then open and verify it back\n * const recipient = await xhpke.SecretKey.generate();\n * const padding = cose.Padding.buckets({ floor: 8192, step: 20 });\n * const sealed = await cose.seal(cbor.text.value(\"secret\"), context, signer, recipient.publicKey(), domain, padding);\n * const opened = await cose.open(cbor.text.bytes(sealed), context, recipient, signer.publicKey(), domain, 60);\n * console.log(opened); // secret\n * ```\n *\n * @module\n */\n\nimport type { Decodable, Encodable } from \"./cbor.js\";\nimport { parse, serialize } from \"./internal/cborg.js\";\nimport {\n CosePadding as WasmPadding,\n cose_sign,\n cose_sign_detached,\n cose_verify,\n cose_verify_detached,\n cose_signer,\n cose_peek,\n cose_recipient,\n cose_seal,\n cose_open,\n cose_encrypt,\n cose_decrypt,\n} from \"./wasm/darkbio_crypto_wasm.js\";\nimport { ensureInit } from \"./internal/init.js\";\nimport { U32_MAX, U64_MAX } from \"./internal/limits.js\";\nimport {\n SecretKey as XdsaSecretKey,\n PublicKey as XdsaPublicKey,\n Fingerprint as XdsaFingerprint,\n} from \"./xdsa.js\";\nimport {\n SecretKey as XhpkeSecretKey,\n PublicKey as XhpkePublicKey,\n Fingerprint as XhpkeFingerprint,\n} from \"./xhpke.js\";\n\n/**\n * How many zero bytes a sender appends to the signed envelope inside the\n * encryption, so the ciphertext's length shows little about the message.\n *\n * Receivers strip any number of zeros, so the policy is the sender's alone and\n * can change without them.\n */\nexport class Padding {\n private constructor(private readonly build: () => WasmPadding) {}\n\n /** @internal */\n _toWasm(): WasmPadding {\n return this.build();\n }\n\n /** No padding: the plaintext is the signed envelope alone. */\n static none(): Padding {\n return new Padding(() => WasmPadding.none());\n }\n\n /**\n * Zeros after the signed envelope, up to the smallest size that fits. Sizes\n * start at `floor`, and each next one is the previous one plus `1/step` of\n * it, rounded up.\n *\n * @throws If `floor` or `step` is not an integer from 1 to 4,294,967,295\n */\n static buckets({ floor, step }: { floor: number; step: number }): Padding {\n for (const [name, value] of [\n [\"floor\", floor],\n [\"step\", step],\n ] as const) {\n if (!Number.isSafeInteger(value) || value < 1 || value > U32_MAX) {\n throw new Error(`padding ${name} must be a positive 32 bit integer`);\n }\n }\n return new Padding(() => WasmPadding.buckets(floor, step));\n }\n}\n\n/**\n * Converts the drift bound of a verification for the WASM boundary.\n */\nfunction driftToBigInt(maxDriftSecs?: number): bigint | undefined {\n if (maxDriftSecs === undefined) return undefined;\n if (!Number.isFinite(maxDriftSecs)) {\n throw new Error(\n \"maxDriftSecs must be a non-negative number within 64 bits\",\n );\n }\n const secs = BigInt(Math.floor(maxDriftSecs));\n if (secs < 0n || secs > U64_MAX) {\n throw new Error(\n \"maxDriftSecs must be a non-negative number within 64 bits\",\n );\n }\n return secs;\n}\n\n/**\n * Creates a COSE_Sign1 signature with an embedded payload.\n *\n * Uses the current system time as the signature timestamp.\n *\n * @param msgToEmbed - The message to sign, embedded in the envelope\n * @param msgToAuth - Additional authenticated data, signed but not embedded\n * @param signer - The xDSA secret key to sign with\n * @param domain - Application domain for separating protocol purposes\n * @returns The serialized COSE_Sign1 envelope\n * @throws CodecError if a message does not fit its codec\n * @throws If a message falls outside the restricted CBOR type system\n */\nexport async function sign<E, A>(\n msgToEmbed: Encodable<E>,\n msgToAuth: Encodable<A>,\n signer: XdsaSecretKey,\n domain: Uint8Array,\n): Promise<Uint8Array> {\n await ensureInit();\n return cose_sign(\n serialize(msgToEmbed),\n serialize(msgToAuth),\n signer._wasm,\n domain,\n );\n}\n\n/**\n * Creates a COSE_Sign1 signature without an embedded payload, the envelope\n * payload being null.\n *\n * The caller's message is authenticated in external_aad, and the payload in\n * the signature input is empty. See the module's wire profile for\n * interoperability. Uses the current system time as the signature timestamp.\n *\n * @param msgToAuth - The message to sign, not embedded in the envelope\n * @param signer - The xDSA secret key to sign with\n * @param domain - Application domain for separating protocol purposes\n * @returns The serialized COSE_Sign1 envelope\n * @throws CodecError if the message does not fit its codec\n * @throws If the message falls outside the restricted CBOR type system\n */\nexport async function signDetached<A>(\n msgToAuth: Encodable<A>,\n signer: XdsaSecretKey,\n domain: Uint8Array,\n): Promise<Uint8Array> {\n await ensureInit();\n return cose_sign_detached(serialize(msgToAuth), signer._wasm, domain);\n}\n\n/**\n * Verifies a COSE_Sign1 signature and returns the embedded payload.\n *\n * Uses the current system time for the drift check.\n *\n * @param msgToCheck - The serialized COSE_Sign1 envelope, bound to the codec\n * of its payload\n * @param msgToAuth - The same additional authenticated data used during signing\n * @param verifier - The xDSA public key to verify against\n * @param domain - Application domain for separating protocol purposes\n * @param maxDriftSecs - Maximum allowed timestamp difference in seconds, past\n * or future. A value of n accepts differences up to and including n, with\n * fractions rounded down. Undefined skips the check.\n * @returns The decoded payload\n * @throws If the envelope is malformed, carries no payload or does not verify\n * for this key, `msgToAuth` and `domain`, or its timestamp drifts too far\n * @throws If `maxDriftSecs` is negative or beyond 64 bits\n * @throws CodecError if the payload or `msgToAuth` does not fit its codec\n */\nexport async function verify<T, A>(\n msgToCheck: Decodable<T>,\n msgToAuth: Encodable<A>,\n verifier: XdsaPublicKey,\n domain: Uint8Array,\n maxDriftSecs?: number,\n): Promise<T> {\n await ensureInit();\n const payload = cose_verify(\n msgToCheck.bytes,\n serialize(msgToAuth),\n verifier._wasm,\n domain,\n driftToBigInt(maxDriftSecs),\n );\n return msgToCheck.codec.decode(parse(payload));\n}\n\n/**\n * Verifies a COSE_Sign1 signature with a detached payload.\n *\n * Uses the current system time for the drift check.\n *\n * @param msgToCheck - The serialized COSE_Sign1 envelope, with a null payload\n * @param msgToAuth - The same message used during signing\n * @param verifier - The xDSA public key to verify against\n * @param domain - Application domain for separating protocol purposes\n * @param maxDriftSecs - Maximum allowed timestamp difference in seconds, past\n * or future. A value of n accepts differences up to and including n, with\n * fractions rounded down. Undefined skips the check.\n * @throws If the envelope is malformed, embeds a payload or does not verify\n * for this key, `msgToAuth` and `domain`, or its timestamp drifts too far\n * @throws If `maxDriftSecs` is negative or beyond 64 bits\n * @throws CodecError if `msgToAuth` does not fit its codec\n */\nexport async function verifyDetached<A>(\n msgToCheck: Uint8Array,\n msgToAuth: Encodable<A>,\n verifier: XdsaPublicKey,\n domain: Uint8Array,\n maxDriftSecs?: number,\n): Promise<void> {\n await ensureInit();\n cose_verify_detached(\n msgToCheck,\n serialize(msgToAuth),\n verifier._wasm,\n domain,\n driftToBigInt(maxDriftSecs),\n );\n}\n\n/**\n * Extracts the signer's fingerprint from a COSE_Sign1 envelope without\n * verifying it.\n *\n * This allows looking up the appropriate verification key before attempting\n * full signature verification. The fingerprint is unauthenticated.\n *\n * @param signature - The serialized COSE_Sign1 envelope\n * @returns The signer's fingerprint from the protected header's `kid`\n * @throws If the envelope is malformed\n */\nexport async function signer(signature: Uint8Array): Promise<XdsaFingerprint> {\n await ensureInit();\n return XdsaFingerprint._fromWasm(cose_signer(signature));\n}\n\n/**\n * Extracts the embedded payload from a COSE_Sign1 envelope without verifying\n * it.\n *\n * The payload is unauthenticated and must not be trusted until verified with\n * {@link verify}. Use {@link signer} to extract the signer's fingerprint for\n * key lookup.\n *\n * @param signature - The serialized COSE_Sign1 envelope, bound to the codec of\n * its payload\n * @returns The decoded, unverified payload\n * @throws If the envelope is malformed or carries no payload\n * @throws CodecError if the payload does not fit its codec\n */\nexport async function peek<T>(signature: Decodable<T>): Promise<T> {\n await ensureInit();\n return signature.codec.decode(parse(cose_peek(signature.bytes)));\n}\n\n/**\n * Extracts the recipient's fingerprint from a COSE_Encrypt0 envelope without\n * decrypting it.\n *\n * This allows looking up the appropriate decryption key before attempting\n * full decryption. The fingerprint is unauthenticated.\n *\n * @param ciphertext - The serialized COSE_Encrypt0 envelope\n * @returns The recipient's fingerprint from the protected header's `kid`\n * @throws If the envelope is malformed\n */\nexport async function recipient(\n ciphertext: Uint8Array,\n): Promise<XhpkeFingerprint> {\n await ensureInit();\n return XhpkeFingerprint._fromWasm(cose_recipient(ciphertext));\n}\n\n/**\n * Signs a message then encrypts it to a recipient.\n *\n * Uses the current system time as the signature timestamp.\n *\n * @param msgToSeal - The message to sign and encrypt\n * @param msgToAuth - Additional authenticated data, signed and bound to the\n * encryption but not embedded\n * @param signerKey - The xDSA secret key to sign with\n * @param recipientKey - The xHPKE public key to encrypt to\n * @param domain - Application domain for HPKE key derivation\n * @param padding - Sender's policy for zeros after the signed envelope\n * @returns The serialized COSE_Encrypt0 envelope holding the encrypted\n * COSE_Sign1\n * @throws CodecError if a message does not fit its codec\n * @throws If a message falls outside the restricted CBOR type system\n * @throws If `padding` is not a {@link Padding}\n */\nexport async function seal<S, A>(\n msgToSeal: Encodable<S>,\n msgToAuth: Encodable<A>,\n signerKey: XdsaSecretKey,\n recipientKey: XhpkePublicKey,\n domain: Uint8Array,\n padding: Padding,\n): Promise<Uint8Array> {\n // Plain JavaScript callers can pass any value as the policy\n if (!(padding instanceof Padding)) {\n throw new Error(\"padding must be a Padding instance\");\n }\n await ensureInit();\n const wasmPadding = padding._toWasm();\n let plaintext: Uint8Array | undefined;\n try {\n plaintext = serialize(msgToSeal);\n return cose_seal(\n plaintext,\n serialize(msgToAuth),\n signerKey._wasm,\n recipientKey._wasm,\n domain,\n wasmPadding,\n );\n } finally {\n plaintext?.fill(0);\n wasmPadding.free();\n }\n}\n\n/**\n * Decrypts and verifies a sealed message.\n *\n * Uses the current system time for the drift check.\n *\n * @param msgToOpen - The serialized COSE_Encrypt0 envelope, bound to the codec\n * of its payload\n * @param msgToAuth - The same additional authenticated data used during sealing\n * @param recipientKey - The xHPKE secret key to decrypt with\n * @param senderKey - The xDSA public key to verify the signature against\n * @param domain - Application domain for HPKE key derivation\n * @param maxDriftSecs - Maximum allowed timestamp difference in seconds, past\n * or future. A value of n accepts differences up to and including n, with\n * fractions rounded down. Undefined skips the check.\n * @returns The decoded payload\n * @throws If the envelope is malformed, does not decrypt or verify for these\n * keys, `msgToAuth` and `domain`, or its timestamp drifts too far\n * @throws If `maxDriftSecs` is negative or beyond 64 bits\n * @throws CodecError if the payload or `msgToAuth` does not fit its codec\n */\nexport async function open<T, A>(\n msgToOpen: Decodable<T>,\n msgToAuth: Encodable<A>,\n recipientKey: XhpkeSecretKey,\n senderKey: XdsaPublicKey,\n domain: Uint8Array,\n maxDriftSecs?: number,\n): Promise<T> {\n await ensureInit();\n const payload = cose_open(\n msgToOpen.bytes,\n serialize(msgToAuth),\n recipientKey._wasm,\n senderKey._wasm,\n domain,\n driftToBigInt(maxDriftSecs),\n );\n try {\n return msgToOpen.codec.decode(parse(payload));\n } finally {\n payload.fill(0);\n }\n}\n\n/**\n * Encrypts an already signed COSE_Sign1 envelope to a recipient.\n *\n * For most use cases, prefer {@link seal}, which signs and encrypts in one\n * step. Use this only when re-encrypting a message from {@link decrypt} to a\n * different recipient without access to the original signer's key. The\n * envelope is encrypted as given, without being checked.\n *\n * @param sign1 - The COSE_Sign1 envelope, such as one from {@link decrypt}\n * @param msgToAuth - The same additional authenticated data used during sealing\n * @param recipientKey - The xHPKE public key to encrypt to\n * @param domain - Application domain for HPKE key derivation\n * @param padding - Sender's policy for zeros after the signed envelope\n * @returns The serialized COSE_Encrypt0 envelope\n * @throws CodecError if `msgToAuth` does not fit its codec\n * @throws If `padding` is not a {@link Padding}\n */\nexport async function encrypt<A>(\n sign1: Uint8Array,\n msgToAuth: Encodable<A>,\n recipientKey: XhpkePublicKey,\n domain: Uint8Array,\n padding: Padding,\n): Promise<Uint8Array> {\n if (!(padding instanceof Padding)) {\n throw new Error(\"padding must be a Padding instance\");\n }\n await ensureInit();\n const wasmPadding = padding._toWasm();\n try {\n return cose_encrypt(\n sign1,\n serialize(msgToAuth),\n recipientKey._wasm,\n domain,\n wasmPadding,\n );\n } finally {\n wasmPadding.free();\n }\n}\n\n/**\n * Decrypts a sealed message without verifying the signature.\n *\n * This allows inspecting the signer before verification. Use {@link signer}\n * to extract the signer's fingerprint, then {@link verify} with the same\n * `msgToAuth` and `domain` to verify.\n *\n * It strips the zero bytes after the COSE_Sign1, accepting any number of them,\n * and returns the COSE_Sign1 as encoded.\n *\n * @param msgToOpen - The serialized COSE_Encrypt0 envelope\n * @param msgToAuth - The same additional authenticated data used during sealing\n * @param recipientKey - The xHPKE secret key to decrypt with\n * @param domain - Application domain for HPKE key derivation\n * @returns The decrypted COSE_Sign1 envelope, not yet verified\n * @throws If the envelope is malformed or does not decrypt for this key,\n * `msgToAuth` and `domain`, or a nonzero byte follows the COSE_Sign1\n * @throws CodecError if `msgToAuth` does not fit its codec\n */\nexport async function decrypt<A>(\n msgToOpen: Uint8Array,\n msgToAuth: Encodable<A>,\n recipientKey: XhpkeSecretKey,\n domain: Uint8Array,\n): Promise<Uint8Array> {\n await ensureInit();\n return cose_decrypt(\n msgToOpen,\n serialize(msgToAuth),\n recipientKey._wasm,\n domain,\n );\n}\n","// crypto-ts: cryptography primitives and wrappers\n// Copyright 2026 Dark Bio AG. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * CBOR Web Tokens on top of COSE Sign1.\n *\n * https://datatracker.ietf.org/doc/html/rfc8392\n *\n * Tokens carry a set of claims encoded as a CBOR map. Standard CWT and EAT\n * claims are declared as fields under {@link claims}. A token's claim set is a\n * `cbor.map` of them, with custom claims as fields at other integer keys.\n *\n * {@link verify} checks the signature against the supplied key and, when\n * requested, the `nbf` and `exp` time bounds. Applications must establish\n * trust in that key, check issuer and audience claims, and apply their own\n * attestation policy. EAT claim relationships and proof of possession of a\n * `cnf` key are not automatically checked.\n *\n * @example\n * ```ts\n * import { cbor, cwt, xdsa } from \"@darkbio/crypto\";\n *\n * const DeviceCert = cbor.map({\n * sub: cwt.claims.subject,\n * exp: cwt.claims.expiration,\n * nbf: cwt.claims.notBefore,\n * cnf: cwt.claims.confirmXdsa,\n * ueid: cwt.claims.eat.ueid,\n * });\n * const issuer = await xdsa.SecretKey.generate();\n * const device = await xdsa.SecretKey.generate();\n * const domain = new TextEncoder().encode(\"device-cert\");\n * const now = 1_700_000_000n;\n *\n * // Example RAND UEID from the generated identity, type 0x01 and 16 identifier bytes.\n * // Provision it once and retain it for the device's lifetime, even if keys change.\n * const ueid = new Uint8Array([0x01, ...device.fingerprint().toBytes().slice(0, 16)]);\n *\n * const cert = { sub: \"ark-0001\", exp: now + 3600n, nbf: now, cnf: device.publicKey(), ueid };\n * const token = await cwt.issue(DeviceCert.value(cert), issuer, domain);\n *\n * const verified = await cwt.verify(DeviceCert.bytes(token), issuer.publicKey(), domain, now + 60n);\n * console.log(verified.sub, verified.cnf.equals(device.publicKey())); // ark-0001 true\n *\n * // Outside the validity window the token is rejected\n * await cwt.verify(DeviceCert.bytes(token), issuer.publicKey(), domain, now + 7200n).catch(() => {\n * console.log(\"expired\");\n * });\n * ```\n *\n * @module\n */\n\nimport {\n bool,\n bytes,\n codec,\n CodecError,\n enumeration,\n field,\n map,\n text,\n uint,\n type Codec,\n type Decodable,\n type Encodable,\n} from \"./cbor.js\";\nimport { parse, serialize } from \"./internal/cborg.js\";\nimport {\n cwt_issue,\n cwt_verify,\n cwt_signer,\n cwt_peek,\n} from \"./wasm/darkbio_crypto_wasm.js\";\nimport { ensureInit } from \"./internal/init.js\";\nimport { U64_MAX } from \"./internal/limits.js\";\nimport * as xdsa from \"./xdsa.js\";\nimport * as xhpke from \"./xhpke.js\";\n\n/** The debug port state, per RFC 9711 Section 4.2.9. */\nexport enum DebugState {\n /** Debug is currently enabled. */\n Enabled = 0,\n /** Debug is currently disabled. */\n Disabled = 1,\n /** Debug was disabled at boot and has not been enabled since. */\n DisabledSinceBoot = 2,\n /**\n * All debug has been disabled since boot. End users and developers cannot\n * re-enable it, but the manufacturer identified by `oemid` may do so. The\n * `oemid` claim must be present, and the application must enforce this.\n */\n DisabledPermanently = 3,\n /**\n * All debug facilities are permanently disabled, including manufacturer\n * facilities, and none can be re-enabled.\n */\n DisabledFullyPermanently = 4,\n}\n\n/** The token's intended purpose, per RFC 9711 Section 4.3.3. */\nexport enum IntendedUse {\n /** General-purpose attestation. */\n Generic = 1,\n /** Attestation for service registration. */\n Registration = 2,\n /** Attestation prior to key/config provisioning. */\n Provisioning = 3,\n /** Attestation for certificate signing requests. */\n CertIssuance = 4,\n /** Attestation accompanying a proof-of-possession. */\n ProofOfPossession = 5,\n}\n\n/**\n * An OEM identifier in one of the three forms RFC 9711 allows:\n *\n * - `pen`, an IANA private enterprise number\n * - `ieee`, a 3-byte IEEE organizationally unique identifier\n * - `random`, a 16-byte random identifier\n */\nexport type Oemid =\n { pen: bigint } | { ieee: Uint8Array } | { random: Uint8Array };\n\n/** Codec of an OEM identifier, an unsigned integer or 3 or 16 bytes. */\nexport const oemid: Codec<Oemid> = codec(\n (value) => {\n if (typeof value !== \"object\" || value === null) {\n throw new CodecError(\"not an OEM identifier\");\n }\n const forms = Object.keys(value);\n if (forms.length !== 1) {\n throw new CodecError(\"not an OEM identifier of exactly one form\");\n }\n const data = (value as Record<string, unknown>)[forms[0]];\n switch (forms[0]) {\n case \"pen\":\n return uint.encode(data as bigint);\n case \"ieee\":\n if (!(data instanceof Uint8Array) || data.length !== 3) {\n throw new CodecError(\"IEEE OEM identifier is not 3 bytes\");\n }\n return data;\n case \"random\":\n if (!(data instanceof Uint8Array) || data.length !== 16) {\n throw new CodecError(\"random OEM identifier is not 16 bytes\");\n }\n return data;\n default:\n throw new CodecError(\"not an OEM identifier\");\n }\n },\n (value) => {\n if (value instanceof Uint8Array) {\n if (value.length === 3) {\n return { ieee: value };\n }\n if (value.length === 16) {\n return { random: value };\n }\n throw new CodecError(\"OEM identifier is not 3 or 16 bytes\");\n }\n try {\n return { pen: uint.decode(value) };\n } catch {\n throw new CodecError(\"not an OEM identifier\");\n }\n },\n);\n\n/**\n * Codec of a version, the text wrapped in a one-element array as RFC 9711\n * has it. The optional scheme element is not supported.\n */\nexport const version: Codec<string> = codec(\n (value) => [text.encode(value)],\n (value) => {\n if (\n !Array.isArray(value) ||\n value.length !== 1 ||\n typeof value[0] !== \"string\"\n ) {\n throw new CodecError(\"not a version\");\n }\n return value[0];\n },\n);\n\n/**\n * Codec of a confirmation, a public key the token's subject holds (RFC 8747).\n * The key is wrapped in a COSE_Key of exactly the key type and the key bytes.\n *\n * A verified token authenticates this key binding, but does not prove that\n * the presenter holds the matching secret key. Applications must check that\n * separately using their protocol's proof-of-possession mechanism.\n *\n * @param algorithm - The COSE algorithm identifier of the key type\n * @param key - The codec of the key\n * @returns The codec\n */\nexport function confirmation<K>(algorithm: number, key: Codec<K>): Codec<K> {\n const coseKey = map({\n type: field(1, enumeration([algorithm])),\n key: field(-2, key),\n });\n const claim = map({ key: field(1, coseKey) });\n return codec(\n (value: K) => claim.encode({ key: { type: algorithm, key: value } }),\n (value) => claim.decode(value).key.key,\n );\n}\n\n/** The numeric members of an enum object. */\nfunction members<E extends number>(values: Record<string, E | string>): E[] {\n return Object.values(values).filter(\n (value): value is E => typeof value === \"number\",\n );\n}\n\n/**\n * The registered claims, RFC 8392 for the token ones and RFC 9711 for the\n * attestation ones under `eat`. A claim set is a `cbor.map` of these.\n */\nexport const claims = {\n /** The issuer, the principal that issued the token (key 1). */\n issuer: field(1, text),\n /** The subject, the principal the token is about (key 2). */\n subject: field(2, text),\n /** The audience, the recipients the token is meant for (key 3). */\n audience: field(3, text),\n /**\n * The expiration time in seconds since the Unix epoch. The token is\n * rejected at or after it (key 4).\n */\n expiration: field(4, uint),\n /**\n * The not-before time in seconds since the Unix epoch. The token is\n * rejected before it (key 5).\n */\n notBefore: field(5, uint),\n /** The issue time in seconds since the Unix epoch (key 6). */\n issuedAt: field(6, uint),\n /** The token identifier, opaque bytes unique to the token (key 7). */\n tokenId: field(7, bytes),\n /**\n * The confirmation, an xDSA public key the subject holds (key 8). A\n * verified token does not prove that the presenter holds the secret key.\n */\n confirmXdsa: field(8, confirmation(xdsa.ALGORITHM_ID, xdsa.publicKey)),\n /**\n * The confirmation, an xHPKE public key the subject holds (key 8). A\n * verified token does not prove that the presenter holds the secret key.\n */\n confirmXhpke: field(8, confirmation(xhpke.ALGORITHM_ID, xhpke.publicKey)),\n /**\n * The Entity Attestation Token claims of RFC 9711.\n *\n * These declare the claims and check their wire representations.\n * Applications must evaluate the claims against their attestation policy and\n * enforce RFC 9711's relationships between claims. For example, `hwModel`\n * and `oemBoot` require `oemid`, `hwVersion` requires `hwModel`, and\n * `swVersion` requires `swName`. {@link DebugState.DisabledPermanently} also\n * requires `oemid`. {@link verify} does not check these relationships.\n */\n eat: {\n /**\n * The universal entity identifier, a globally unique device identifier\n * such as a serial number or IMEI (key 256). Its first byte is the type\n * prefix of RFC 9711 Section 4.2.1.\n *\n * A RAND UEID uses prefix 0x01 followed by 16, 24 or 32 bytes of random\n * identifier data, provisioned once for the device. The bytes are carried\n * as supplied, so callers must check the prefix, length and identifier\n * policy.\n */\n ueid: field(256, bytes),\n /** The hardware manufacturer, in one of the {@link Oemid} forms (key 258). */\n oemid: field(258, oemid),\n /** The product or board model identifier, as the manufacturer defines it (key 259). */\n hwModel: field(259, bytes),\n /** The hardware revision identifier (key 260). */\n hwVersion: field(260, version),\n /** The number of seconds since the last boot (key 261). */\n uptime: field(261, uint),\n /** Whether every boot stage was OEM authorized, so secure boot passed (key 262). */\n oemBoot: field(262, bool),\n /** The state of the device's debug facilities at attestation time (key 263). */\n debugStatus: field(263, enumeration(members(DebugState))),\n /** The number of times the device has booted, never decreasing (key 267). */\n bootCount: field(267, uint),\n /** Random bytes drawn at boot, the same in every token of one boot cycle (key 268). */\n bootSeed: field(268, bytes),\n /** The name of the firmware or software running on the device (key 270). */\n swName: field(270, text),\n /** The software version identifier (key 271). */\n swVersion: field(271, version),\n /** The purpose the token was issued for (key 275). */\n intendedUse: field(275, enumeration(members(IntendedUse))),\n },\n};\n\n/** Converts the clock of a verification for the WASM boundary. */\nfunction nowToBigInt(now?: number | bigint): bigint | undefined {\n if (now === undefined) return undefined;\n if (\n typeof now !== \"bigint\" &&\n (typeof now !== \"number\" || !Number.isFinite(now))\n ) {\n throw new Error(\"now must be a non-negative Unix timestamp within 64 bits\");\n }\n const secs = typeof now === \"bigint\" ? now : BigInt(Math.floor(now));\n if (secs < 0n || secs > U64_MAX) {\n throw new Error(\"now must be a non-negative Unix timestamp within 64 bits\");\n }\n return secs;\n}\n\n/**\n * Issues a CWT by signing the claims with COSE Sign1.\n *\n * The claims must encode as a CBOR map, such as a `cbor.map` of the\n * {@link claims} fields. Uses the current system time as the COSE signature\n * timestamp.\n *\n * @param claims - The claims to include in the token\n * @param signer - The xDSA secret key to sign with\n * @param domain - Application domain for separating protocol purposes\n * @returns The serialized CWT\n * @throws CodecError if the claims do not fit their codec\n * @throws If the claims do not encode as a CBOR map\n */\nexport async function issue<C>(\n claims: Encodable<C>,\n signer: xdsa.SecretKey,\n domain: Uint8Array,\n): Promise<Uint8Array> {\n await ensureInit();\n return cwt_issue(serialize(claims), signer._wasm, domain);\n}\n\n/**\n * Verifies a CWT's COSE signature and temporal validity, then returns the\n * decoded claims.\n *\n * When `now` is given, the `nbf` claim (key 5) must be present and\n * `nbf <= now`. If the `exp` claim (key 4) is present too, `now < exp` must\n * also hold. When `now` is undefined, temporal validation is skipped entirely.\n *\n * The COSE signature timestamp is not checked, since temporal validity comes\n * from the CWT claims. The codec determines the accepted claim schema.\n * Successful verification does not establish issuer trust, enforce an\n * audience, evaluate attestation policy or EAT claim relationships, or prove\n * possession of a confirmation key. The application must perform those checks.\n *\n * @param token - The serialized CWT, bound to the codec of its claims\n * @param verifier - The xDSA public key to verify against\n * @param domain - Application domain for separating protocol purposes\n * @param now - Time of the check in seconds since the Unix epoch, with\n * fractions rounded down, or undefined to skip the time checks\n * @returns The decoded claims\n * @throws If the token is malformed, does not verify for this key and\n * `domain`, or fails a time check\n * @throws If `now` is negative or beyond 64 bits\n * @throws CodecError if the claims do not fit their codec\n */\nexport async function verify<C>(\n token: Decodable<C>,\n verifier: xdsa.PublicKey,\n domain: Uint8Array,\n now?: number | bigint,\n): Promise<C> {\n await ensureInit();\n const payload = cwt_verify(\n token.bytes,\n verifier._wasm,\n domain,\n nowToBigInt(now),\n );\n return token.codec.decode(parse(payload));\n}\n\n/**\n * Extracts the signer's fingerprint from a CWT without verifying the\n * signature.\n *\n * The fingerprint is unauthenticated. Use it to look up the appropriate\n * verification key before calling {@link verify}.\n *\n * @param token - The serialized CWT\n * @returns The signer's fingerprint\n * @throws If the token is malformed\n */\nexport async function signer(token: Uint8Array): Promise<xdsa.Fingerprint> {\n await ensureInit();\n return xdsa.Fingerprint._fromWasm(cwt_signer(token));\n}\n\n/**\n * Extracts and decodes the claims from a CWT without verifying the signature.\n *\n * The claims are unauthenticated and must not be trusted until verified with\n * {@link verify}. Use {@link signer} to extract the signer's fingerprint for\n * key lookup. The one intended use of this function is self-signed key\n * discovery.\n *\n * @param token - The serialized CWT, bound to the codec of its claims\n * @returns The decoded, unverified claims\n * @throws If the token is malformed\n * @throws CodecError if the claims do not fit their codec\n */\nexport async function peek<C>(token: Decodable<C>): Promise<C> {\n await ensureInit();\n return token.codec.decode(parse(cwt_peek(token.bytes)));\n}\n"],"x_google_ignoreList":[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22],"mappings":";;;;;;;;GAKa,IAAb,MAAa,EAAY;CACrB,OAAO,OAAO,GAAK;EACf,IAAM,IAAM,OAAO,OAAO,EAAY,SAAS;EAG/C,OAFA,EAAI,YAAY,GAChB,GAAwB,SAAS,GAAK,EAAI,WAAW,CAAG,GACjD;CACX;CACA,qBAAqB;EACjB,IAAM,IAAM,KAAK;EAGjB,OAFA,KAAK,YAAY,GACjB,GAAwB,WAAW,IAAI,GAChC;CACX;CACA,OAAO;EACH,IAAM,IAAM,KAAK,mBAAmB;EACpC,EAAK,uBAAuB,GAAK,CAAC;CACtC;CASA,OAAO,QAAQ,GAAO,GAAM;EACxB,IAAM,IAAM,EAAK,oBAAoB,GAAO,CAAI;EAChD,OAAO,EAAY,OAAO,CAAG;CACjC;CAKA,OAAO,OAAO;EACV,IAAM,IAAM,EAAK,iBAAiB;EAClC,OAAO,EAAY,OAAO,CAAG;CACjC;AACJ;AACI,OAAO,YAAS,EAAY,UAAU,OAAO,WAAW,EAAY,UAAU;AAKlF,IAAa,IAAb,MAAa,EAAgB;CACzB,OAAO,OAAO,GAAK;EACf,IAAM,IAAM,OAAO,OAAO,EAAgB,SAAS;EAGnD,OAFA,EAAI,YAAY,GAChB,GAA4B,SAAS,GAAK,EAAI,WAAW,CAAG,GACrD;CACX;CACA,qBAAqB;EACjB,IAAM,IAAM,KAAK;EAGjB,OAFA,KAAK,YAAY,GACjB,GAA4B,WAAW,IAAI,GACpC;CACX;CACA,OAAO;EACH,IAAM,IAAM,KAAK,mBAAmB;EACpC,EAAK,2BAA2B,GAAK,CAAC;CAC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